<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" label-width="120px">
            <el-row>
              <el-form-item label="产品名称" prop="productCode">
                <el-select v-model="queryParams.productCode" placeholder="请输入模版编码" style="width: 220px" clearable @change="selectProduct">
                  <template #header>
                    <el-input v-model="likeName" placeholder="可根据产品名称模糊查询" @input="filterByProductName"></el-input>
                  </template>
                  <el-option
                    v-for="dict in filteredList"
                    :key="dict.productCode"
                    :label="dict.productCode + '-' + dict.productName"
                    :value="dict.productCode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="产品状态" prop="salesStatus">
                <el-select v-model="queryParams.salesStatus" placeholder="产品状态" style="width: 220px" clearable>
                  <el-option v-for="dict in sales_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="产品销售限额(万元)" prop="salesLimit">
                <el-input-number v-model="queryParams.salesLimit" clearable />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="产品销售起期" prop="salesStartDate">
                <el-date-picker v-model="queryParams.salesStartDate" clearable type="date" placeholder="请选择产品销售起期" />
              </el-form-item>
              <el-form-item label="产品销售止期" prop="salesEndDate">
                <el-date-picker v-model="queryParams.salesEndDate" clearable type="date" placeholder="请选择产品销售止期" />
              </el-form-item>
              <el-form-item label="承保截止时间" prop="signEndDate">
                <el-date-picker v-model="queryParams.signEndDate" clearable type="date" placeholder="请选择产品销售止期" />
              </el-form-item>
            </el-row>
            <el-form>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button v-hasPermi="['product:apply:export']" type="success" icon="Download" @click="handleExport">下载</el-button>
              <el-button v-hasPermi="['product:apply:loglist']" type="primary" icon="Promotion" @click="viewSalesHistory">产品起停售历史轨迹查询</el-button>
            </el-form>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="productList" border style="width: 100%">
        <el-table-column label="产品编码" align="center" prop="productCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="主附险标记" align="center" prop="subFlag">
          <template #default="scope">
            <dict-tag :options="product_sub_flag" :value="scope.row.subFlag" />
          </template>
        </el-table-column>
        <el-table-column label="归属系统" align="center" prop="system" />
        <el-table-column label="产品销售状态" align="center" prop="salesStatus">
          <template #default="scope">
            <dict-tag :options="sales_status" :value="scope.row.salesStatus" />
          </template>
        </el-table-column>
        <el-table-column label="产品销售起期" align="center" prop="salesStartDate" />
        <el-table-column label="产品销售止期" align="center" prop="salesEndDate" />
        <el-table-column label="承保截止日期" align="center" prop="signEndDate" />
        <el-table-column label="产品销售限额" align="center" prop="salesLimit" />
        <el-table-column align="center" label="操作" width="180">
          <template #default="scope">
            <el-tooltip content="状态变更申请" placement="top">
              <el-button v-hasPermi="['product:apply:changeapply']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
  </div>
  <apply_detail :detailVisible="detailVisible" :detailProductCode="detailProductCode" @update:detailVisible="updateDetailVisible"></apply_detail>
  <apply_log ref="appLogRef"></apply_log>
</template>
<script setup name="apply-product" lang="ts">
import { listProduct, productApply, qeuryAllProduct, searchText } from '@/api/product/apply';
import apply_detail from '@/views/product/apply/apply_detail.vue';
import apply_log from '@/views/product/apply/apply_log.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sales_status } = toRefs<any>(proxy?.useDict('sales_status'));
const { product_sub_flag } = toRefs<any>(proxy?.useDict('product_sub_flag'));
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sales_channel } = toRefs<any>(proxy?.useDict('sales_channel'));

const showSearch = ref(true);
const productList = ref([]);
const likeName = ref('');
//模糊查询列表
const filteredList = ref([]);
//下拉基础列表
const baseproductList = ref([]);
const loading = ref(false);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const detailVisible = ref(false);
const detailProductCode = ref('');
const appLogRef = ref();

const props = defineProps({
  baseProductList: Object
});

watch(
  () => props.baseProductList,
  (val) => {
    baseproductList.value = val;
    filteredList.value = val;
  },
  { deep: true, immediate: true }
);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productCode: undefined,
    salesStatus: undefined,
    salesLimit: undefined,
    salesStartDate: undefined,
    salesEndDate: undefined,
    signEndDate: undefined
  }
});
const { queryParams } = toRefs(data);

//模糊查询
const filterByProductName = () => {
  if (likeName.value) {
    filteredList.value = baseproductList.value.filter(
      (item) => item.productName.includes(likeName.value) || item.productCode.includes(likeName.value)
    );
  } else {
    // 如果 likeName 为空，显示原始列表
    filteredList.value = baseproductList.value;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  // 1. 校验停售日期是否早于起售日期
  if (queryParams.value.salesStartDate && queryParams.value.salesEndDate && queryParams.value.salesEndDate < queryParams.value.salesStartDate) {
    proxy?.$modal.msgError('停售日期不能早于产品起售日期');
    return; // 阻断查询
  }

  // 2. 校验停售日期是否早于当前日期
  if (queryParams.value.salesEndDate && queryParams.value.salesEndDate < new Date()) {
    proxy?.$modal.msgError('停售日期不允许早于当前日期');
    return; // 阻断查询
  }

  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 查询产品列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProduct(queryParams.value);
  productList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 产品选择后处理动作 */
const selectProduct = async (newVal) => {
  queryParams.value.productCode = newVal;
};

/** 状态变更申请 */
const handleUpdate = (row) => {
  detailVisible.value = true;
  detailProductCode.value = row?.productCode;
};

/**
 * 子界面关闭，父组件更新
 */
const updateDetailVisible = (newVal) => {
  detailVisible.value = newVal;
};
/**
 * 弹出产品起停售历史轨迹查询页面
 */
const viewSalesHistory = async () => {
  appLogRef.value.dialog.visible = true;
  // 可以在这里初始化数据
  await appLogRef.value.fetchProductCodes();
};

const handleExport = () => {
  proxy?.download(
    '/product/apply/export',
    {
      ...queryParams.value
    },
    `产品销售状态_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  // quryTemplateList();
});
</script>

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