<template>
  <div class="huanbao-ej-container">
    <!-- Tab切换 -->
    <a-tabs v-model:activeKey="tabIndex" @change="handleTabChange">
      <a-tab-pane
        v-for="tab in tabs"
        :key="String(tab.orderInx)"
        :tab="tab.name"
      />
    </a-tabs>
    <!-- 搜索表单 -->
    <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="jiDiList"
          @change="handleBaseChange"
        />
        <a-select
          v-model:value="searchData.stcd"
          placeholder=" "
          style="width: 200px"
          show-search
          :filter-option="filterOption"
          :options="rstcdOptions"
        />
        <a-input
          v-if="tabIndex !== '7'"
          v-model:value="searchData.stnm"
          placeholder="请输入测站名称"
          style="width: 200px"
          allow-clear
        />

        <a-button type="primary" @click="handleSearch">查询</a-button>
        <a-tooltip title="重置">
          <a-button @click="handleReset">重置</a-button>
        </a-tooltip>
      </a-space>
    </div>
    <!-- 列表 -->
    <BasicTable
      ref="tableRef"
      :scrollY="400"
      :columns="columns"
      :list-url="vmsstbprptGetKendoList"
      :search-params="searchParams"
      :transform-data="customTransform"
    >
      <template #coenvwState="{ column, record }">
        <a-tag :color="record.coenvwState > 0 ? 'green' : '#999'">
          {{ record.coenvwState > 0 ? '在线' : '离线' }}
        </a-tag>
      </template>
      <template #dvtp="{ column, record }">
        {{ dvtpText(record.dvtp) }}
      </template>
      <template #stindxForEng="{ column, record }">
        {{ record.dvtp == 2 ? '生态流量' : '出库流量' }}
      </template>
      <template #action="{ column, record }">
        <a @click="handleViewDetail(record, 'detail')" class="text-link">
          查看详情
        </a>
      </template>
    </BasicTable>
  </div>
</template>

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

const JidiSelectEventStore = useJidiSelectEventStore();

// ==================== Props 定义 ====================
const props = defineProps<{
  baseId?: string;
  tabs?: any[];
  activeKey?: string | number;
}>();

// ==================== 状态管理 ====================
const tabIndex = ref(String(props.activeKey ?? ''));
const searchData = ref<any>({
  baseId: props.baseId || 'all',
  stnm: null,
  stcd: null
});
const modelStore = useModelStore();
const tableRef = ref();

// ==================== 基地列表数据 ====================
const jiDiList: any = ref([]);
const rstcdOptions: any = ref([]);

// ==================== 表格列定义 ====================
const columns = computed(() => {
  // 生态流量(tabIndex=7)的列
  if (tabIndex.value === '7') {
    return [
      {
        key: 'baseName',
        title: '所属基地',
        dataIndex: 'baseName',
        width: '150px',
        merge: true
      },
      {
        key: 'stnm',
        title: '电站名称',
        dataIndex: 'stnm',
        width: '176px'
      },
      {
        key: 'dvtp',
        title: '开发方式',
        dataIndex: 'dvtp',
        width: '120px',

        slots: { customRender: 'dvtp' }
      },
      {
        key: 'stindx',
        title: '生态流量站类型',
        dataIndex: 'stindx',

        slots: { customRender: 'stindxForEng' }
      },
      {
        key: 'jcdt',
        title: '建成时间',
        dataIndex: 'jcdt',
        width: '150px',
        sort: true
      },
      {
        key: 'coenvwState',
        title: '监测状态',
        dataIndex: 'coenvwState',
        width: '120px',

        slots: { customRender: 'coenvwState' }
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        align: 'center' as const,
        fixed: 'right' as const,
        slots: { customRender: 'action' }
      }
    ];
  }

  // 其他类型的列
  const baseColumns = [
    {
      key: 'baseName',
      title: '所属基地',
      dataIndex: 'baseName',
      width: '150px',
      merge: true
    },
    {
      key: 'stnm',
      title: '测站名称',
      dataIndex: 'stnm',
      width: '176px'
    },
    {
      key: 'ennm',
      title: '电站',
      dataIndex: 'ennm',
      width: '150px',

      slots: { customRender: 'ennm' }
    },
    {
      key: 'jcdt',
      title: '建成时间',
      dataIndex: 'jcdt',
      width: '150px',
      sort: true
    },
    {
      key: 'stindx',
      title: '监测指标',
      dataIndex: 'stindx',
      width: '150px'
    }
  ];

  // 气象站(tabIndex=4)不显示监测状态
  if (tabIndex.value !== '4') {
    baseColumns.push({
      key: 'coenvwState',
      title: '监测状态',
      dataIndex: 'coenvwState',
      width: '120px',
      slots: { customRender: 'coenvwState' }
    } as any);
  }

  baseColumns.push({
    title: '操作',
    key: 'action',
    width: 100,
    align: 'center' as const,
    fixed: 'right' as const,
    slots: { customRender: 'action' }
  } as any);

  return baseColumns;
});

// ==================== 搜索参数 ====================
const searchParams = computed(() => {
  return {
    sort: [
      {
        field: 'baseStepSort',
        dir: 'asc'
      },
      {
        field: 'hbrvcd',
        dir: 'asc'
      },
      {
        field: 'rstcdStepSort',
        dir: 'asc'
      },
      {
        field: 'siteStepSort',
        dir: 'asc'
      }
    ],
    group: [],
    select: [
      'baseName',
      'stnm',
      'ennm',
      'jcdt',
      'stindx',
      'coenvwState',
      'sttpCode',
      'stcd',
      'rstcd',
      'stCode',
      'stName',
      'dvtp'
    ],
    groupResultFlat: false
  };
});

// ==================== 方法 ====================
const handleTabChange = (key: string) => {
  tabIndex.value = key;
  handleReset();
  handleSearch();
};

const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const getRstcdData = async () => {
  const parmas = {
    filter: {
      logic: 'and',
      filters: [
        searchData.value.baseId != 'all'
          ? {
              field: 'baseId',
              operator: 'contains',
              dataType: 'string',
              value: '02'
            }
          : null,
        {
          field: 'sttpCode',
          operator: 'eq',
          dataType: 'string',
          value: 'ENG'
        }
      ].filter(Boolean)
    },
    sort: [
      {
        field: 'baseId',
        dir: 'asc'
      },
      {
        field: 'rvcdStepSort',
        dir: 'asc'
      },
      {
        field: 'rstcdStepSort',
        dir: 'asc'
      },
      {
        field: 'siteStepSort',
        dir: 'asc'
      }
    ],
    select: ['stcd', 'stnm']
  };
  const res = await vmsstbprptGetKendoList(parmas);
  rstcdOptions.value = res.data.data.map((item) => {
    return {
      value: item.stcd,
      label: item.stnm
    };
  });
};
const handleBaseChange = () => {
  searchData.value.stcd = null
  getRstcdData();
  // handleSearch();
};

const dvtpText = (dvtp: number) => {
  if (dvtp === 2) return '引水式';
  if (dvtp === 3) return '混合式';
  return '坝后式';
};

const handleSearch = () => {
  let filters: any[] = [];

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

  // 根据tabIndex添加不同的过滤条件
  switch (tabIndex.value) {
    case '1': // 水温监测
      filters.push(
        { field: 'mway', operator: 'eq', dataType: 'string', value: 2 },
        {
          field: 'sttpFullPath',
          operator: 'contains',
          dataType: 'string',
          value: 'ENV,ENVM,WT'
        }
      );
      break;
    case '2': // 国家水质站
      filters.push(
        { field: 'mway', operator: 'eq', dataType: 'string', value: 2 },
        {
          field: 'sttpFullPath',
          operator: 'contains',
          dataType: 'string',
          value: 'ENV,ENVM,WQ'
        },
        { field: 'dtinType', operator: 'eq', dataType: 'string', value: 1 }
      );
      break;
    case '9': // 河道水质监测
      filters.push(
        { field: 'mway', operator: 'eq', dataType: 'string', value: 2 },
        { field: 'sttpCode', operator: 'eq', dataType: 'string', value: 'WQ' },
        { field: 'dtinType', operator: 'eq', dataType: 'string', value: 0 }
      );
      break;
    case '10': // 增殖站水质站
      filters.push(
        { field: 'mway', operator: 'eq', dataType: 'string', value: 2 },
        {
          field: 'sttpCode',
          operator: 'eq',
          dataType: 'string',
          value: 'WQFB'
        },
        { field: 'dtinType', operator: 'eq', dataType: 'string', value: 0 }
      );
      break;
    case '4': // 气象监测
      filters.push(
        { field: 'mway', operator: 'eq', dataType: 'string', value: 2 },
        {
          field: 'sttpFullPath',
          operator: 'contains',
          dataType: 'string',
          value: 'MM'
        }
      );
      break;
    case '5': // 国家水文站
      filters.push(
        {
          logic: 'or',
          filters: [
            {
              field: 'sttpFullPath',
              operator: 'contains',
              dataType: 'string',
              value: 'ST,ZQ'
            },
            {
              field: 'sttpFullPath',
              operator: 'contains',
              dataType: 'string',
              value: 'ST,ZZ'
            }
          ]
        },
        { field: 'mway', operator: 'eq', dataType: 'string', value: 2 },
        { field: 'sttpCode', operator: 'in', value: ['ZZ', 'ZQ'] },
        { field: 'dtinType', operator: 'eq', dataType: 'string', value: 1 }
      );
      break;
    case '6': // 水文监测
      filters.push(
        {
          logic: 'or',
          filters: [
            {
              field: 'sttpFullPath',
              operator: 'contains',
              dataType: 'string',
              value: 'ST,ZQ'
            },
            {
              field: 'sttpFullPath',
              operator: 'contains',
              dataType: 'string',
              value: 'ST,ZZ'
            }
          ]
        },
        { field: 'sttpCode', operator: 'in', value: ['ZZ', 'ZQ'] },
        { field: 'mway', operator: 'eq', dataType: 'string', value: 2 },
        { field: 'dtinType', operator: 'eq', dataType: 'string', value: 0 }
      );
      break;
    case '7': // 生态流量
      filters.push(
        {
          field: 'runState',
          operator: 'eq',
          value: 4
        },
        { field: 'sttpCode', operator: 'eq', dataType: 'string', value: 'ENG' },
        { field: 'DTIN', operator: 'eq', dataType: 'string', value: 1 },
        { field: 'bldsttCcode', operator: 'eq', dataType: 'string', value: 2 }
      );
      break;
    case '8': // 视频监控
      filters.push(
        {
          field: 'sttpFullPath',
          operator: 'contains',
          dataType: 'string',
          value: 'VD,VD'
        },
        { field: 'dtin', operator: 'eq', dataType: 'string', value: 1 }
      );
      break;
    case '11': // 栖息地
      filters.push({
        field: 'sttpCode',
        operator: 'eq',
        dataType: 'string',
        value: 'FH'
      });
      break;
  }
  let filter = {
    logic: 'and',
    filters: filters
  };
  tableRef.value?.getList(filter);
};

const handleReset = () => {
  searchData.value = {
    baseId: 'all',
    stnm: null,
    stcd: null
  };
  getRstcdData()
  handleSearch();
};

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

// 获取sttpCode对应的详情类型
const getSttpCode = (sttpCode: string) => {
  const codeMap: Record<string, string> = {
    DW: 'DW',
    DW_1: 'DW',
    DW_2: 'DW',
    DW_3: 'DW',
    DW_4: 'DW',
    DW_5: 'DW',
    DW_6: 'DW',
    DW_9: 'DW',
    EQS: 'EQS',
    EQ: 'EQ',
    EQ_1: 'EQ',
    EQ_2: 'EQ',
    EQ_3: 'EQ',
    EQ_4: 'EQ',
    EQ_5: 'EQ',
    EQ_6: 'EQ',
    EQ_7: 'EQ',
    FB: 'EQ',
    FPC: 'FP',
    'FPC,': 'FP',
    FP: 'FP',
    FP_1: 'FP',
    FP_2: 'FP',
    FP_3: 'FP',
    FP_4: 'FP',
    FP_5: 'FP',
    FH: 'FH',
    'FH,': 'FH',
    SG: 'SG',
    'SG,': 'SG',
    TE: 'TE',
    'TE,': 'TE',
    VA: 'VA',
    'VA,': 'VA',
    VP: 'VP',
    'VP,': 'VP',
    WE: 'WE',
    'WE,': 'WE',
    WQ: 'WQ',
    'WQ,': 'WQ',
    WQH: 'WQ',
    WT: 'WT',
    'WT,': 'WT',
    WTRV: 'WT',
    'WTRV,': 'WT',
    WTVT: 'WT',
    'WTVT,': 'WT'
  };
  return codeMap[sttpCode] || '';
};

// 查看详情
const handleViewDetail = (record: any, type: string) => {
  if (type === 'dz') {
    modelStore.modalVisible = true;
    modelStore.params.sttp = 'ENG';
    modelStore.title = record.ennm;
    modelStore.params.stcd = record.rstcd;
  } else {
    const sttpCode = record.sttpCode || '';

    if (sttpCode === 'MM') {
      modelStore.modalVisible = true;
      modelStore.params.sttp = 'MM';
      modelStore.title = record.stnm;
      modelStore.params.stcd = record.stcd;
    } else if (sttpCode === 'ENG') {
      modelStore.modalVisible = true;
      modelStore.params.sttp = getSttpCode(sttpCode) || sttpCode;
      modelStore.params.eqtp = 'QEC';
      modelStore.params.stcd = record.stcd;
      modelStore.title = record.stnm;
    } else if (sttpCode.includes('VD')) {
      modelStore.modalVisible = true;
      modelStore.params.sttp = 'VD';
      modelStore.params.stcd = record.stcd;
      modelStore.title = record.stnm;
    } else if (sttpCode.includes('WT')) {
      modelStore.modalVisible = true;
      modelStore.params.sttp = getSttpCode(sttpCode) || sttpCode;
      modelStore.params.stcd = record.stcd;
      modelStore.title = record.stnm;
      modelStore.params.enfc =
        sttpCode === 'WTVT' || sttpCode === 'WTVT,' ? '1' : '0';
    } else {
      modelStore.modalVisible = true;
      modelStore.params.sttp = sttpCode;
      modelStore.params.stcd = record.stcd;
      modelStore.title = record.stnm;
    }
  }
};

// ==================== 生命周期 ====================
onMounted(() => {
  JidiSelectEventStore.jidiData?.forEach((element: any) => {
    jiDiList.value.push({
      label: element.wbsName,
      value: element.wbsCode
    });
  });
  getRstcdData()
  handleSearch();
});
</script>

<style scoped lang="scss">
.huanbao-ej-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;
  }

  :deep(.ant-table-wrapper) {
    flex: 1;
    overflow: hidden;
  }
}

.text-link {
  color: #2f6b98;

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