<template>
  <div class="stlldbqk_container">
    <div class="stlldbqk_title">
      <div>选择水电站:</div>
      <a-select
        v-model:value="from.baseId"
        show-search
        placeholder=" "
        :options="jidiOptions"
        :filter-option="filterOption"
        @change="handleChange"
        style="width: 200px; margin: 0px 10px"
      ></a-select>
      <a-select
        v-model:value="from.stcd"
        show-search
        placeholder="请选择电站"
        :options="stcdOptions"
        :filter-option="filterOption"
        style="width: 200px"
      ></a-select>
      <a-button type="primary" style="margin: 0px 10px" @click="Search()"
        >搜索</a-button
      >
      <a-button @click="resetSearch()">重置</a-button>
    </div>
    <div class="table">
      <BasicTable
        ref="tableRef"
        :columns="columns"
        :scrollY="480"
        :list-url="vmsstbprptGetKendoList"
        :search-params="searchParams"
        :transform-data="customTransform"
        :enable-sort="true"
        @sort-change="handleSortChange"
      >
        <template #dvtp="{ record }">
          {{
            record.dvtp == 2 ? '引水式' : record.dvtp == 3 ? '混合式' : '坝后式'
          }}
        </template>
        <template #stindx="{ record }">
          {{ record.dvtp == 2 ? '生态流量' : '出库流量' }}
        </template>
        <template #coenvwState="{ column, record }">
          <a-tag :color="record.coenvwState > 0 ? 'success' : ''">
            {{ record.coenvwState > 0 ? '在线' : '离线' }}
          </a-tag>
        </template>
        <template #action="{ column, record }">
          <a-button type="link" size="small" @click="handleView(record)"
            >查看详情</a-button
          >
        </template>
      </BasicTable>
    </div>
  </div>
</template>

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

const modelStore = useModelStore();
const props = defineProps<{
  baseId?: any;
  titleData?: any;
}>();
const tableRef = ref();
const columns = ref([
  {
    title: '所属基地',
    key: 'baseName',
    dataIndex: 'baseName',
    merge: true, // 启用行合并
    visible: true
  },
  {
    title: '电站名称',
    key: 'stnm',
    dataIndex: 'stnm',
    visible: true
  },
  {
    title: '开发方式',
    key: 'dvtp',
    dataIndex: 'dvtp',
    visible: true,
    slots: { customRender: 'dvtp' }
  },
  {
    title: '生态流量站类型',
    key: 'stindx',
    dataIndex: 'stindx',
    visible: true,
    slots: { customRender: 'stindx' }
  },
  {
    title: '建成时间',
    key: 'jcdt',
    dataIndex: 'jcdt',
    visible: true,
    sorter: true,
    customRender: ({ record }: any) => {
      const date = record.jcdt;
      if (!date) return '-';
      if (typeof date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(date)) {
        return date;
      }
      if (typeof date === 'string' && date.includes(' ')) {
        return date.split(' ')[0];
      }
      return date;
    }
  },
  {
    title: '监测状态',
    key: 'coenvwState',
    dataIndex: 'coenvwState',
    visible: true,
    slots: { customRender: 'coenvwState' }
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    slots: { customRender: 'action' }
  }
]);
const sort = {
  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 JidiSelectEventStore = useJidiSelectEventStore();
// JidiSelectEventStore.jidiData
let jidiOptions = computed(() => {
  return [
    ...JidiSelectEventStore.jidiData.map((item: any) => ({
      value: item.wbsCode,
      label: item.wbsName
    }))
  ];
});
const from = ref({
  baseId: props.baseId || 'all',
  stcd: ''
});

// 排序状态管理
const sortInfo = ref<{ field: string; order: string | null }>({
  field: '',
  order: null
});

// 动态计算搜索参数（包含排序）
const searchParams = computed(() => {
  let baseSort;

  // 如果用户触发了排序，将其加入排序数组
  if (sortInfo.value.field && sortInfo.value.order) {
    baseSort = [
      {
        field: sortInfo.value.field,
        dir: sortInfo.value.order === 'ascend' ? 'asc' : 'desc'
      }
    ];
  } else {
    baseSort = [
      { field: 'baseStepSort', dir: 'asc' },
      { field: 'hbrvcd', dir: 'asc' },
      { field: 'rstcdStepSort', dir: 'asc' },
      { field: 'siteStepSort', dir: 'asc' }
    ];
  }

  return {
    sort: baseSort,
    group: [],
    select: [
      'baseName',
      'stnm',
      'ennm',
      'jcdt',
      'stindx',
      'coenvwState',
      'sttpCode',
      'stcd',
      'rstcd',
      'stCode',
      'stName',
      'dvtp'
    ],
    groupResultFlat: false
  };
});

// 监听 props.baseId 变化，同步到 from.value.baseId
watch(
  () => props.baseId,
  newBaseId => {
    // 只在有有效值且与当前值不同时才更新
    if (newBaseId && newBaseId !== from.value.baseId) {
      from.value.baseId = newBaseId;
      from.value.stcd = ''; // 重置电站选择
      // 异步等待 DOM 更新后再搜索
      nextTick(() => {
        handleChange(); // 先刷新电站列表
        Search(); // 再执行搜索
      });
    }
  },
  { immediate: false }
);

const filterOption = (input: string, option: any) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const stcdOptions = ref([]);
const handleChange = async () => {
  try {
    let params = {
      filter: {
        logic: 'and',
        filters: [
          from.value.baseId != 'all'
            ? {
                field: 'baseId',
                operator: 'contains',
                dataType: 'string',
                value: from.value.baseId
              }
            : 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']
    };
    let res = await vmsstbprptGetKendoList(params);
    if (res?.data?.success && res?.data?.data) {
      let data = res.data.data;
      stcdOptions.value = data.map((item: any) => ({
        value: item.stcd,
        label: item.stnm
      }));
    } else {
      stcdOptions.value = [];
    }
  } catch (error) {
    console.error('获取电站列表失败:', error);
    stcdOptions.value = [];
  }
};
const Search = () => {
  let filters = [
    from.value.stcd
      ? {
          field: 'stcd',
          operator: 'eq',
          value: from.value.stcd
        }
      : null,
    from.value.baseId != 'all'
      ? {
          field: 'baseId',
          operator: 'eq',
          value: from.value.baseId
        }
      : null,
    {
      field: 'runState',
      operator: 'eq',
      value: 4
    },
    {
      field: 'sttpCode',
      operator: 'eq',
      dataType: 'string',
      value: props.titleData?.sttpCode || 'ENG'
    },
    {
      field: 'DTIN',
      operator: 'eq',
      dataType: 'string',
      value: 1
    },
    {
      field: 'bldsttCcode',
      operator: 'eq',
      dataType: 'string',
      value: 2
    }
  ].filter(Boolean);
  const filter = {
    logic: 'and',
    filters
  };
  tableRef.value?.getList(filter);
};

// 处理排序变化
const handleSortChange = (info: {
  field: string;
  order: 'ascend' | 'descend' | null;
}) => {
  sortInfo.value.field = info.field || '';
  sortInfo.value.order = info.order || null;

  // 等待 DOM 和响应式状态更新完成后再触发搜索，确保 BasicTable 拿到最新的 searchParams
  nextTick(() => {
    Search();
  });
};

const resetSearch = () => {
  from.value = {
    baseId: 'all',
    stcd: ''
  };
  Search();
};
// 自定义数据转换
const customTransform = (res: any) => {
  return {
    records: res?.data?.data || [],
    total: res?.data?.total || 0
  };
};
const handleView = (record: any) => {
  modelStore.modalVisible = true;
  modelStore.params.sttp = 'ENG';
  modelStore.title = record.stnm;
  modelStore.params.stcd = record.stcd;
  modelStore.params.eqtp = 'QGC';
  modelStore.filterStll = 'qecInterval';
};
onMounted(() => {
  handleChange();
  Search();
});
onUnmounted(() => {});
</script>

<style scoped lang="scss">
.stlldbqk_container {
  width: 100%;
  .stlldbqk_title {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .table {
    width: 100%;
    height: 560px;
  }
}
</style>
