<template>
  <div class="approval-search">
    <BasicSearch
      ref="basicSearchRef"
      :searchList="searchList"
      :initial-values="initSearchData"
      :zhujianfujian="'fu'"
      @reset="handleResetWrapper"
      @finish="onSearchFinish"
      @values-change="onValuesChange"
      ><template #jcdt>
        <a-date-picker
          class="w-[120px]"
          v-model:value="jcdt.min"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="起始时间"
          :showToday="false"
        >
          <template #renderExtraFooter>
            <div class="flex items-center flex-wrap px-2">
              <span
                v-for="item in DateSetting.RangeButton.days1"
                :key="item"
                @click="handleRangeClick(item)"
              >
                <a class="text-[#1890ff] mr-1"> {{ item.label }}</a>
              </span>
            </div>
          </template>
        </a-date-picker>
        至
        <a-form-item-rest>
          <a-date-picker
            class="w-[120px]"
            v-model:value="jcdt.max"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabledDate="disabledEndDate"
            placeholder="结束时间"
            :showToday="false"
          >
            <template #renderExtraFooter>
              <div class="flex items-center flex-wrap px-2">
                <span
                  v-for="item in DateSetting.RangeButton.days1"
                  :key="item"
                  @click="handleRangeClick(item)"
                >
                  <a class="text-[#1890ff] mr-1"> {{ item.label }}</a>
                </span>
              </div>
            </template>
          </a-date-picker>
        </a-form-item-rest>
      </template>
      <template #actions>
        <a-button :loading="exportLoading" @click="exportBtn">导出</a-button>
      </template>
    </BasicSearch>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import dayjs from 'dayjs';
import BasicSearch from '@/components/BasicSearch/index.vue';
import { DateSetting } from '@/utils/enumeration';
import { useTimeScale } from '@/store/composables/useTimeScale';
import { getFishReleaseMonitorSectionList } from '@/api/DataQueryMenuModule';

const emit = defineEmits<{
  (e: 'export-btn'): void;
  (e: 'reset', values: any): void;
  (e: 'search-finish', values: any): void;
}>();

const basicSearchRef = ref<any>();
const btnLoading = ref<boolean>(false);

const props = defineProps<{
  exportLoading?: boolean;
  modalData: any;
}>();
const initSearchData = {
  baseId: props.modalData.baseid ?? 'all',
  rstcd: null,
  stcd: '',
  mway: '1'
};

const searchData = ref<any>({ ...initSearchData });

const {
  jcdt,
  currentTimeScale,
  handleRangeClick,
  disabledEndDate,
  handleSearchFinish,
  handleValuesChange,
  init,
  setDefaultTimeRange
} = useTimeScale({
  defaultTimeScale: initSearchData.timeScale,
  onSearchFinish: values => emit('search-finish', values),
  onReset: () => emit('reset', initSearchData)
});
const crossSectionListLoading = ref<any>(false);
const crossSectionList = ref<any>([]);

const searchList: any = computed(() => [
  //   {
  //     type: 'waterStation',
  //     name: 'rvcd',
  //     label: '流域',
  //     placeholder: '请输入流域名称',
  //     fieldProps: {
  //       allowClear: true
  //     },
  //     options: []
  //   },
  {
    type: 'jidiData',
    name: 'baseId',
    label: '水电基地',
    placeholder: '请输入水电基地名称',
    fieldProps: {
      allowClear: true
    },
    options: []
  },
  {
    type: 'Select',
    name: 'stcd',
    label: '过鱼设施名称',
    width: 200,
    placeholder: '请选择过鱼设施名称',
    fieldProps: {
      allowClear: true
    },
    loading: crossSectionListLoading.value,
    options: crossSectionList.value.map(item => ({
      label: item.stnm,
      value: item.stcd
    }))
  },
  {
    type: 'Radio',
    name: 'mway',
    label: '数据类型',
    width: 140,
    options: [
      {
        label: '人工',
        value: '1'
      },
      {
        label: '自动',
        value: '2'
      }
    ]
  },
  {
    type: 'custom',
    name: 'jcdt',
    label: '时间',
    fieldProps: {
      allowClear: false
    }
  }
]);

const onSearchFinish = (values: any) => {
  handleSearchFinish(values);
};

const exportBtn = () => {
  emit('export-btn');
};
const initCrossSectionList = params => {
  const filters = [];
  if (params) {
    if (params.baseId != '' && params.baseId != 'all') {
      filters.push({
        field: 'baseId',
        operator: 'contains',
        dataType: 'string',
        value: params.baseId
      });
    }
    if (params.rstcd != '' && params.rstcd != null) {
      filters.push({
        field: 'rstcd',
        operator: 'contains',
        dataType: 'string',
        value: params.rstcd
      });
    }
  }
  crossSectionListLoading.value = true;
  getFishReleaseMonitorSectionList({
    filter: {
      logic: 'and',
      filters: filters
    },
    select: ['stcd', 'stnm', 'wtDeviceType', 'dtinType', 'mway']
  }).then(res => {
    if (res.data?.data) {
      crossSectionList.value = res.data?.data;
    }
    crossSectionListLoading.value = false;
  });
};

const onValuesChange = (changedValues: any, allValues: any) => {
  // 当基地或断面变化时，清空过鱼设施选中并重新请求列表
  if ('baseId' in changedValues || 'rstcd' in changedValues) {
    allValues.stcd = null;
    if (basicSearchRef.value?.formData) {
      basicSearchRef.value.formData.stcd = null;
    }
    initCrossSectionList(allValues);
  }

  handleValuesChange(changedValues, allValues);
  searchData.value = { ...searchData.value, ...allValues };
};

const handleResetWrapper = () => {
  // 手动重置内部状态，避免触发两次请求
  currentTimeScale.value = initSearchData.timeScale;
  const now = dayjs();
  if (props.modalData.year) {
    jcdt.value = {
      min: `${props.modalData.year}-01-01 00:00:00`,
      max: `${props.modalData.year}-12-31 23:59:59`
    };
  } else {
    jcdt.value = {
      min: `${now
        .subtract(5, 'year')
        .startOf('year')
        .format('YYYY-MM-DD')} 00:00:00`,
      max: `${now.endOf('year').format('YYYY-MM-DD')} 23:59:59`
    };
  }

  setDefaultTimeRange(initSearchData.timeScale);
  // 触发搜索，使用当前状态而非 initSearchData
  handleSearchFinish({
    ...initSearchData
  });
};

defineExpose({
  btnLoading,
  searchData
});

onMounted(() => {
  init();
  // 设置默认年份：前一年到当前年
  const now = dayjs();
  if (props.modalData.year) {
    jcdt.value = {
      min: `${props.modalData.year}-01-01 00:00:00`,
      max: `${props.modalData.year}-12-31 23:59:59`
    };
  } else {
    jcdt.value = {
      min: `${now.subtract(5, 'year').format('YYYY-MM-DD')} 00:00:00`,
      max: `${now.format('YYYY-MM-DD')} 23:59:59`
    };
  }

  initCrossSectionList();
  // 使用 handleSearchFinish 确保包含 jcdt 等完整参数
  handleSearchFinish({ ...initSearchData });
});
</script>

<style lang="scss"></style>
