<template>
  <div class="ssst-dcgk-table">
    <!-- 搜索表单 -->
    <a-form layout="inline" class="search-form">
      <a-form-item label="年份">
        <a-date-picker
          v-model:value="yearValue"
          picker="year"
          format="YYYY"
          :allow-clear="false"
          :show-time="false"
          style="width: 150px"
          @change="handleYearChange"
        />
      </a-form-item>
      <a-form-item label="调查批次">
        <a-select
          v-model:value="dcpcValue"
          placeholder="请选择"
          style="width: 150px"
          :options="dcpcOptions"
        />
      </a-form-item>
      <a-form-item label="调查鱼种类">
        <a-input
          v-model:value="nameValue"
          placeholder="请输入鱼种类"
          allow-clear
          style="width: 200px"
        />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <!-- 表格 -->
    <div class="table-wrapper">
      <BasicTable
        ref="tableRef"
        :columns="columns"
        :scroll-y="500"
        :scroll-x="800"
        :list-url="listUrl"
        :search-params="searchParams"
        :transform-data="customTransform"
      >
        <template #stnm="{ record }">
          <a @click="handleViewDetail(record)" class="text-link">
            {{ record.stnm }}
          </a>
        </template>
        <template #tm="{ record }">
          {{ record.tm ? dayjs(record.tm).format('YYYY-MM-DD') : '-' }}
        </template>
        <template #fid="{ record }">
          <a-button
            type="link"
            style="padding: 4px"
            :disabled="record.fid"
            @click="handleViewAttachment(record.fid)"
          >
            查看附件
          </a-button>
        </template>
      </BasicTable>
    </div>

     <CommonAttachmentModal
      v-model:open="attachmentModalVisible"
      :fid="currentAttachmentFid"
      title="查看附件"
    />
  </div>
</template>

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

const modelStore = useModelStore();
// ==================== Props ====================
const props = defineProps<{
  selectDateTime?: any; // 选中的日期
  stcd?: string; // 断面编码
  all?: boolean; // 是否不限制断面
}>();

// ==================== 搜索状态 ====================
const tableRef = ref();
const yearValue = ref(props.selectDateTime ? dayjs(props.selectDateTime) : dayjs());
const dcpcValue = ref('');
const nameValue = ref('');
const dcpcOptions = ref<Array<{ label: string; value: string }>>([
  { label: '全部', value: '' }
]);

// ==================== 弹框状态 ====================
const attachmentModalVisible = ref(false);
const currentAttachmentFid = ref('');
// ==================== 接口URL ====================
const listUrl = getWeStaticsSecond;

// ==================== 搜索参数 ====================
const searchParams = computed(() => ({
  sort: [
    {
      field: 'tm',
      dir: 'desc'
    }
  ],
  group: [],
  select: [],
  groupResultFlat: false
}));

// ==================== 表格列配置 ====================
const columns = [
  {
    key: 'stnm',
    title: '断面名称',
    dataIndex: 'stnm',
    fixed: 'left' as const,
    width: 200,
    ellipsis: true,
    slots: { customRender: 'stnm' },
    merge: true,
    mergeDeps: ['stnm']
  },
  {
    key: 'tm',
    title: '调查日期',
    dataIndex: 'tm',
    fixed: 'left' as const,
    width: 200,
    ellipsis: true,
    slots: { customRender: 'tm' },
    merge: true,
    mergeDeps: ['stnm']
  },
  {
    key: 'dcpc',
    title: '调查批次',
    dataIndex: 'dcpc',
    width: 200,
    ellipsis: true,
    merge: true,
    mergeDeps: ['stnm']
  },
  {
    key: 'ftpName',
    title: '调查鱼种类',
    dataIndex: 'ftpName',
    width: 200,
    ellipsis: true
  },
  {
    key: 'fcnt',
    title: '调查鱼总数',
    dataIndex: 'fcnt',
    width: 200,
    ellipsis: true
  },
  {
    key: 'fid',
    title: '证明材料',
    dataIndex: 'fid',
    width: 200,
    ellipsis: true,
    slots: { customRender: 'fid' }
  }
];

// ==================== 过滤条件构建 ====================
const getFilter = () => {
  const filters: any[] = [
    {
      field: 'year',
      operator: 'in',
      dataType: 'string',
      value: [dayjs(yearValue.value).format('YYYY')]
    }
  ];

  // 断面筛选
  if (!props.all && props.stcd) {
    filters.push({
      field: 'rstcd',
      operator: 'in',
      dataType: 'string',
      value: props.stcd
    });
  }

  // 调查批次筛选
  if (dcpcValue.value) {
    filters.push({
      field: 'dcpc',
      operator: 'eq',
      dataType: 'string',
      value: dcpcValue.value
    });
  }

  // 鱼种类搜索
  if (nameValue.value) {
    filters.push({
      field: 'ftpName',
      operator: 'contains',
      dataType: 'string',
      value: nameValue.value
    });
  }

  return {
    logic: 'and',
    filters: filters.filter((el: any) => el != null)
  };
};

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

// ==================== 获取调查批次选项 ====================
const getDcpcOptions = async () => {
  try {
    const params = {
      logic: 'and',
      filters: [
        ...(props.all
          ? []
          : [
              {
                field: 'rstcd',
                operator: 'in',
                dataType: 'string',
                value: props.stcd
              }
            ]),
        {
          field: 'year',
          operator: 'in',
          dataType: 'string',
          value: [dayjs(yearValue.value).format('YYYY')]
        }
      ]
    };
    const group = [
      {
        dir: 'des',
        field: 'dcpc'
      }
    ];

    const res = await getWeStaticsSecond( { filter: params, group });

    if (res?.data?.data?.length) {
      const options = res.data.data.map((item: any) => ({
        label: item.dcpc,
        value: item.dcpc
      }));
      dcpcOptions.value = [{ label: '全部', value: '' }, ...options];
    } else {
      dcpcOptions.value = [{ label: '全部', value: '' }];
    }
  } catch (error) {
    console.error('获取调查批次选项失败:', error);
    dcpcOptions.value = [{ label: '全部', value: '' }];
  }
};

// ==================== 搜索与重置 ====================
const handleSearch = () => {
  const filter = getFilter();
  tableRef.value?.getList(filter);
};

const handleReset = () => {
  yearValue.value = props.selectDateTime ? dayjs(props.selectDateTime) : dayjs();
  dcpcValue.value = '';
  nameValue.value = '';
  handleSearch();
};

const handleYearChange = () => {
  dcpcValue.value = '';
  getDcpcOptions();
};

// 查看详情（占位）
const handleViewDetail = (record: any) => {
  modelStore.modalVisible = true;
  modelStore.params = record;
  modelStore.params.sttp = "WE";
  modelStore.title = record.stnm;
};

// 查看附件（占位）
const handleViewAttachment = (fid: string) => {
 currentAttachmentFid.value = fid;
  attachmentModalVisible.value = true;
};

// ==================== 监听 selectDateTime 变化 ====================
watch(
  () => props.selectDateTime,
  (newVal) => {
    if (newVal) {
      yearValue.value = dayjs(newVal);
      getDcpcOptions();
      handleSearch();
    }
  },
  { immediate: false }
);

// ==================== 挂载时执行 ====================
onMounted(() => {
  getDcpcOptions();
  handleSearch();
});
</script>

<style lang="scss" scoped>
.ssst-dcgk-table {
  width: 100%;

  .search-form {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 16px;
  }

  .table-wrapper {
    width: 100%;
  }
}

.text-link {
  color: #2f6b98;

  &:hover {
    color: #40a9ff;
  }
}

.detail-placeholder,
.attachment-placeholder {
  padding: 40px 0;
}
</style>
