<template>
  <div class="huanbao-two-layers-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <a-space size="middle">
        <div>所属基地:</div>
        <a-select
          v-model:value="searchData.baseid"
          placeholder="请选择基地"
          style="width: 200px"
          show-search
          :filter-option="filterOption"
          :options="baseOptions"
          @change="handleBaseChange"
        />
        <div>类型:</div>
        <a-select
          v-model:value="searchData.type"
          placeholder="请选择类型"
          style="width: 200px"
          :options="typeOptions"
          @change="handleTypeChange"
        />
        <div>建设状态:</div>
        <a-select
          v-model:value="searchData.bldstt"
          placeholder="请选择状态"
          style="width: 150px"
          :options="bldsttOptions"
          @change="handleBldsttChange"
        />
        <a-input
          v-model:value="searchData.search"
          placeholder="搜索名称/电站"
          style="width: 200px"
          allow-clear
          @press-enter="handleSearch"
        />
        <a-button type="primary" @click="handleSearch">查询</a-button>
        <a-tooltip title="重置">
          <a-button @click="handleReset">重置</a-button>
        </a-tooltip>
      </a-space>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <BasicTable
        ref="tableRef"
        :columns="columns"
        :scroll-y="500"
        :list-url="envOpdGetKendoListCust"
        :search-params="tableSearchParams"
        :transform-data="customTransform"
        row-key="stcd"
      >
        <template #stnm="{ record }">
          <a
            v-if="record.stnm && record.stnm !== '-'"
            @click="handleViewDetail(record, 'DW')"
            class="text_hocer"
            >{{ record.stnm }}</a
          >
        </template>
        <template #ennm="{ record }">
          <a
            v-if="record.ennm && record.ennm !== '-'"
            @click="handleViewDetail(record, 'ENG')"
            class="text_hocer"
            >{{ record.ennm }}</a
          >
        </template>
      </BasicTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import BasicTable from '@/components/BasicTable/index.vue';
import { envOpdGetKendoListCust, getBaseList } from '@/api/home';
import { useModelStore } from '@/store/modules/model';

const modelStore = useModelStore();
// ==================== Props 定义 ====================
const props = defineProps<{
  data?: any;
  currentJidiInfo?: any;
  res?: any;
}>();

// ==================== 状态管理 ====================
const tableRef = ref();
const baseList = ref<any[]>([]);

// 搜索数据
const searchData = ref<any>({
  baseid: props.currentJidiInfo?.wbsCode || 'all',
  type: props.data?.type || '',
  bldstt: props.res?.bldstt || '',
  hydrodtin: props.res?.hydrodtin || '',
  search: ''
});

// 基地选项
const baseOptions = computed(() => {
  const options = [];
  baseList.value.forEach(item => {
    options.push({
      label: item.wbsName || item.basename,
      value: item.wbsCode || item.baseid
    });
  });
  return options;
});

// 类型选项
const typeOptions = [
  { label: '全部', value: '' },
  { label: '鱼类增殖站', value: 'FB' },
  { label: '过鱼设施', value: 'FP' },
  { label: '珍稀植物园', value: 'VP' },
  { label: '动物救助站', value: 'VA' },
  { label: '低温水减缓设施', value: 'DW' },
  { label: '鱼类栖息地', value: 'FH' },
  { label: '生态流量泄放设施', value: 'EQ' }
];

// 建设状态选项
const bldsttOptions = [
  { label: '全部', value: '' },
  { label: '未建', value: '0' },
  { label: '在建', value: '1' },
  { label: '已建', value: '2' }
];

// ==================== 列配置 ====================
const columns = [
  {
    title: '名称',
    key: 'stnm',
    dataIndex: 'stnm',
    width: 150
  },
  {
    title: '建设情况',
    key: 'bldsttCcodeName',
    dataIndex: 'bldsttCcodeName',
    width: 120
  },
  {
    title: '类型',
    key: 'sttpName',
    dataIndex: 'sttpName',
    width: 120
  },
  {
    title: '接入日期',
    key: 'dtinTm',
    dataIndex: 'dtinTm',
    width: 120
  },
  {
    title: '关联电站',
    key: 'ennm',
    dataIndex: 'ennm',
    width: 150
  },
  {
    title: '关联基地',
    key: 'baseName',
    dataIndex: 'baseName',
    width: 150
  }
];

// ==================== 表格搜索参数 ====================
const tableSearchParams = computed(() => {
  return {
    sort: [
      { field: 'baseStepSort', dir: 'asc' },
      { field: 'dtin', dir: 'desc' },
      { field: 'rvcdStepSort', dir: 'asc' },
      { field: 'rstcdStepSort', dir: 'asc' },
      { field: 'siteStepSort', dir: 'asc' }
    ],
    select: [
      'stnm',
      'bldsttCcodeName',
      'sttpName',
      'dtinTm',
      'ennm',
      'baseName',
      'stcd',
      'sttpCode'
    ],
    group: [],
    groupResultFlat: false
  };
});

// 数据转换
const customTransform = (res: any) => {
  return {
    records: res?.data?.data || [],
    total: res?.data?.total || 0
  };
};

// ==================== 过滤条件构建 ====================
const buildSearchFilter = () => {
  const filters: any[] = [];

  if (searchData.value.baseid && searchData.value.baseid !== 'all') {
    filters.push({
      field: 'baseId',
      operator: 'eq',
      value: searchData.value.baseid
    });
  }

  if (searchData.value.type) {
    const operator = searchData.value.type === 'EQ' ? 'contains' : 'eq';
    filters.push({
      field: 'sttpCode',
      operator: operator,
      value: searchData.value.type
    });
  }

  if (searchData.value.bldstt !== undefined && searchData.value.bldstt !== '') {
    filters.push({
      field: 'bldsttCcode',
      operator: 'eq',
      value: searchData.value.bldstt
    });
  }

  if (
    searchData.value.hydrodtin !== undefined &&
    searchData.value.hydrodtin !== ''
  ) {
    filters.push({
      field: 'dtin',
      operator: 'eq',
      value: searchData.value.hydrodtin
    });
  }

  if (searchData.value.search) {
    filters.push({
      logic: 'or',
      filters: [
        {
          field: 'baseName',
          operator: 'contains',
          value: searchData.value.search
        },
        { field: 'stnm', operator: 'contains', value: searchData.value.search },
        { field: 'ennm', operator: 'contains', value: searchData.value.search }
      ]
    });
  }

  return {
    logic: 'and',
    filters: filters.filter(
      f => f.value !== undefined && f.value !== null && f.value !== ''
    )
  };
};

// ==================== 获取基地列表 ====================
const fetchBaseList = async () => {
  try {
    const params = {
      filter: {
        logic: 'and',
        filters: [
          {
            field: 'wbsType',
            operator: 'eq',
            dataType: 'string',
            value: 'PSB'
          },
          { field: 'treeLevel', operator: 'eq', dataType: 'string', value: '1' }
        ]
      },
      sort: [{ field: 'orderIndex', dir: 'asc' }]
    };

    const res = await getBaseList(params);
    if (res?.data?.data) {
      baseList.value = res.data.data;
    }
  } catch (error) {
    console.error('获取基地列表失败:', error);
  }
};

// ==================== 事件处理 ====================
const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const handleBaseChange = () => {
  handleSearch();
};

const handleTypeChange = () => {
  handleSearch();
};

const handleBldsttChange = () => {
  handleSearch();
};

const handleSearch = () => {
  const filter = buildSearchFilter();
  tableRef.value?.getList(filter);
};

const handleReset = () => {
  searchData.value = {
    baseid: props.currentJidiInfo?.wbsCode || 'all',
    type: props.data?.type || '',
    bldstt: '',
    hydrodtin: '',
    search: ''
  };
  const filter = buildSearchFilter();
  tableRef.value?.reset();
  tableRef.value?.getList(filter);
};

const handleViewDetail = (record: any, type: any) => {
  console.log('查看详情:', record);
  if (type == 'ENG') {
    modelStore.modalVisible = true;
    modelStore.params = record;
    modelStore.params.sttp = 'ENG';
    modelStore.title = record.ennm;
    modelStore.params.stcd = record.stcd;
  } else {
    console.log('查看详情:', record);
    modelStore.modalVisible = true;
    modelStore.params = record;
    modelStore.params.sttp = record.sttpCode;
    // debugger
    modelStore.title = record.stnm;
    modelStore.params.stcd = record.stcd;
  }
  // TODO: 后续实现详情查看功能
};

// ==================== 生命周期 ====================
onMounted(() => {
  fetchBaseList();
  handleSearch();
});
</script>

<style scoped lang="scss">
.huanbao-two-layers-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  box-sizing: border-box;

  .search-form {
    margin-bottom: 16px;
    border-radius: 4px;
  }

  .table-wrapper {
    flex: 1;
    overflow: hidden;
  }
}

.text_hocer {
  color: #2f6b98;
}

.text_hocer:hover {
  color: #40a9ff;
}
</style>
