<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" :inline="true">
            <el-form-item label="业务类别" prop="busType">
              <el-select v-model="queryParams.busType" placeholder="请输入业务类别" clearable>
                <el-option v-for="dict in biz_category" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="业务名称" prop="busName">
              <el-input v-model="queryParams.busName" placeholder="请输入业务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业务描述" prop="busDes">
              <el-input v-model="queryParams.busDes" placeholder="请输入业务描述" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业务渠道" prop="channelCode">
              <el-select v-model="queryParams.channelCode" placeholder="请输入业务渠道" clearable>
                <el-option v-for="dict in financial_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="生效日期" prop="startDate">
              <el-date-picker clearable v-model="queryParams.startDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择生效日期" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="financialConfigList" @selection-change="handleSelectionChange">
        <el-table-column label="规则编码" align="center" prop="ruleCode" width="220">
          <template #default="scope">
            <dict-tag :options="formattedRulesCodeList" :value="scope.row.ruleCode" />
          </template>
        </el-table-column>
        <el-table-column label="业务类别" align="center" prop="busType" width="120">
          <template #default="scope">
            <dict-tag :options="biz_category" :value="scope.row.busType" />
          </template>
        </el-table-column>
        <el-table-column label="业务名称" align="center" prop="busName" width="200" />
        <el-table-column label="业务描述" align="center" prop="busDes" width="500" show-overflow-tooltip />
        <el-table-column label="业务渠道" align="center" prop="channelCode" width="120">
          <template #default="scope">
            <dict-tag :options="financial_channel" :value="scope.row.channelCode" />
          </template>
        </el-table-column>
        <el-table-column label="业务类型(健康险)" align="center" prop="channelType" width="130">
          <template #default="scope">
            <dict-tag :options="channel_type" :value="scope.row.channelType" />
          </template>
        </el-table-column>
        <el-table-column label="团险客户类型" align="center" prop="grpCustomerType" width="150" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="grp_customer_type" :value="scope.row.grpCustomerType" />
          </template>
        </el-table-column>
        <el-table-column label="个人业务客户类型" align="center" prop="indCustomerType" width="150">
          <template #default="scope">
            <dict-tag :options="ind_customer_type" :value="scope.row.indCustomerType" />
          </template>
        </el-table-column>
        <el-table-column label="个人业务营销员类型" align="center" prop="indSalespersonType" width="150">
          <template #default="scope">
            <dict-tag :options="ind_salesperson_type" :value="scope.row.indSalespersonType" />
          </template>
        </el-table-column>
        <el-table-column label="产品类型" align="center" prop="productType" width="120" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="product_type" :value="scope.row.productType" />
          </template>
        </el-table-column>
        <el-table-column label="生效日期" align="center" prop="startDate" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="终止日期" align="center" prop="endDate" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="管控裕度" align="center" prop="controlMargin" width="120" />
        <el-table-column label="联系人邮箱" align="center" prop="contactEmail" width="120" show-overflow-tooltip />
        <el-table-column label="调整原因" align="center" prop="adjustment" width="120" />
        <el-table-column label="版本号" align="center" prop="version" width="120" />
        <el-table-column label="状态" align="center" prop="status" width="120">
          <template #default="scope">
            <dict-tag :options="status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" prop="status">
          <template #default="scope">
            <el-switch
              v-hasPermi="['financial:financialConfigManage:changeStatus']"
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column v-if="false" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="审核通过" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handlePass(scope.row)"
                v-hasPermi="['financial:financialConfigAudit:auditPass']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="审核不通过" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleFail(scope.row)"
                v-hasPermi="['financial:financialConfigAudit:auditFail']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="FinancialConfigAudit" lang="ts">
import { listFinancialConfig, auditPass, auditFail, listRulesCodeMapping, changeRuleStatus } from '@/api/financial/financialConfig';
import { FinancialConfigVO, FinancialConfigQuery, FinancialConfigForm, RulesCodeMappingForm } from '@/api/financial/financialConfig/types';
import { EmailtempVO } from '@/api/msg/emailtemp/types';
import { changeTemplateVersionStatus } from '@/api/msg/emailtemp';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

//字典转换
const {
  financial_bus_type,
  financial_channel,
  biz_category,
  product_type,
  ind_customer_type,
  grp_customer_type,
  status,
  channel_type,
  ind_salesperson_type
} = toRefs<any>(
  proxy?.useDict(
    'financial_bus_type',
    'financial_channel',
    'biz_category',
    'product_type',
    'ind_customer_type',
    'grp_customer_type',
    'status',
    'channel_type',
    'ind_salesperson_type'
  )
);

const financialConfigList = ref<FinancialConfigVO[]>([]);
const rulesCodeMappingList = ref<RulesCodeMappingForm[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const financialConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: FinancialConfigForm = {
  id: undefined,
  serialNumber: undefined,
  busType: undefined,
  bizCategory: undefined,
  busName: undefined,
  busDes: undefined,
  channelCode: undefined,
  channelType: undefined,
  grpCustomerType: undefined,
  indCustomerType: undefined,
  productType: undefined,
  startDate: undefined,
  endDate: undefined,
  controlMargin: undefined,
  contactEmail: undefined,
  adjustment: undefined,
  status: undefined
};
const data = reactive<PageData<FinancialConfigForm, FinancialConfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    serialNumber: undefined,
    busType: undefined,
    bizCategory: undefined,
    busName: undefined,
    busDes: undefined,
    channelCode: undefined,
    channelType: undefined,
    grpCustomerType: undefined,
    indCustomerType: undefined,
    productType: undefined,
    startDate: undefined,
    endDate: undefined,
    controlMargin: undefined,
    contactEmail: undefined,
    adjustment: undefined,
    status: '0',
    auditStatus: undefined,
    params: {}
  },
  rules: {
    busType: [{ required: true, message: '业务类型不能为空', trigger: 'change' }],
    bizCategory: [{ required: true, message: '业务类别不能为空', trigger: 'blur' }],
    busName: [{ required: true, message: '业务名称不能为空', trigger: 'blur' }],
    busDes: [{ required: true, message: '业务描述不能为空', trigger: 'blur' }],
    channelCode: [{ required: true, message: '业务渠道不能为空', trigger: 'blur' }],
    channelType: [{ required: true, message: '业务类型不能为空', trigger: 'change' }],
    grpCustomerType: [{ required: true, message: '团险客户类型不能为空', trigger: 'change' }],
    indCustomerType: [{ required: true, message: '个人业务营销员类型不能为空', trigger: 'change' }],
    productType: [{ required: true, message: '产品类型不能为空', trigger: 'change' }],
    startDate: [{ required: true, message: '生效日期不能为空', trigger: 'blur' }],
    controlMargin: [{ required: true, message: '管控裕度不能为空', trigger: 'blur' }],
    contactEmail: [
      { required: true, message: '联系人邮箱不能为空', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value) {
            const emails = value
              .split(';')
              .map((email: string) => email.trim())
              .filter((email: string) => email);
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

            for (const email of emails) {
              if (email && !emailRegex.test(email)) {
                callback(new Error(`邮箱格式不正确: ${email}，请使用分号分隔多个邮箱`));
                return;
              }
            }

            // 检查是否有重复邮箱
            const uniqueEmails = new Set(emails);
            if (uniqueEmails.size !== emails.length) {
              callback(new Error('存在重复的邮箱地址'));
              return;
            }
          }
          callback();
        },
        trigger: 'blur'
      }
    ],
    adjustment: [{ required: true, message: '调整原因不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询清单配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFinancialConfig(queryParams.value);
  financialConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询规则编码列表 */
const getRuleCodeList = async () => {
  const res = await listRulesCodeMapping();
  console.log(res);
  rulesCodeMappingList.value = res;
};

// 转换规则编码数据格式
const formattedRulesCodeList = computed(() => {
  return rulesCodeMappingList.value.map((item) => ({
    value: item.mappingKey,
    label: item.mappingValue
  }));
});

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  financialConfigFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const handleStatusChange = async (row: FinancialConfigVO) => {
  let text = row.status === '0' ? '启用' : '停用';
  try {
    console.log(row);
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.busName + '"规则吗?');
    await changeRuleStatus(row);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.status = row.status === '0' ? '1' : '0';
  }
};

/** 审核通过 */
const handlePass = async (row?: FinancialConfigVO) => {
  try {
    console.log(row);
    const res = await auditPass(row);
    proxy?.$modal.msgSuccess('操作成功');
    await getList();
  } catch (error) {
    proxy?.$modal.msgError('操作失败');
  }
};
/** 审核不通过 */
const handleFail = async (row?: FinancialConfigVO) => {
  try {
    console.log(row);
    const res = await auditFail(row);
    proxy?.$modal.msgSuccess('操作成功');
    await getList();
  } catch (error) {
    proxy?.$modal.msgError('操作失败');
  }
};

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