<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 v-model="queryParams.startDate" clearable 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">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['financial:financialConfig:add']" type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <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>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改清单配置对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="60%" append-to-body>
      <el-form ref="financialConfigFormRef" :model="form" :rules="rules">
        <el-row>
          <el-form-item label="规则编码" prop="ruleCode">
            <el-select v-model="form.ruleCode" placeholder="请选择规则编码" style="width: 210px" clearable>
              <el-option v-for="item in rulesCodeMappingList" :key="item.mappingKey" :label="item.mappingValue" :value="item.mappingKey" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务类别" prop="busType">
            <el-select v-model="form.busType" placeholder="请输入业务类别" style="width: 210px" clearable>
              <el-option v-for="dict in biz_category" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item label="业务名称" prop="busName">
          <el-input v-model="form.busName" type="textarea" :rows="3" placeholder="请输入业务名称" show-word-limit maxlength="200" />
        </el-form-item>
        <el-form-item label="业务描述" prop="busDes">
          <el-input v-model="form.busDes" type="textarea" :rows="3" placeholder="请输入业务描述" show-word-limit maxlength="500" />
        </el-form-item>
        <el-row>
          <el-form-item label="业务渠道" prop="channelCode">
            <el-select v-model="form.channelCode" placeholder="请输入业务渠道" style="width: 200px" clearable @change="handleChannelChange">
              <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" label-width="70px">
            <el-date-picker
              v-model="form.startDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择生效日期"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="管控裕度" prop="controlMargin" label-width="70px">
            <el-input-number
              v-model="form.controlMargin"
              placeholder="请输入管控裕度"
              :min="0"
              :precision="5"
              controls-position="right"
              style="width: 200px"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <!-- 业务类型 - 显示条件：channelCode 为 H 或其他值 -->
          <el-form-item v-if="form.channelCode === 'H'" label="业务类型" prop="channelType">
            <el-select v-model="form.channelType" placeholder="请输入业务类型" style="left: 10px; width: 200px" clearable>
              <el-option v-for="dict in channel_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <!-- 团体业务客户类型 - 显示条件：channelCode 为 G 或 H -->
          <el-form-item
            v-if="form.channelCode === 'G' || form.channelCode === 'H'"
            label="团体业务客户类型"
            prop="grpCustomerType"
            label-width="150px"
          >
            <el-select v-model="form.grpCustomerType" placeholder="请输入团体业务客户类型" style="width: 200px" clearable multiple>
              <el-option v-for="dict in grp_customer_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <!-- 个人业务客户类型 - 显示条件：channelCode 为其他值（非G非H） -->
          <el-form-item
            v-if="form.channelCode && form.channelCode !== 'G' && form.channelCode !== 'H'"
            label="个人业务客户类型"
            prop="indCustomerType"
            label-width="120px"
          >
            <el-select
              v-model="form.indCustomerType"
              placeholder="请输入个人业务客户类型"
              style="width: 200px"
              clearable
              @change="handleIndCustomerTypeChange"
            >
              <el-option
                v-for="dict in ind_customer_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                :disabled="disabledIndCustomerOptions[dict.value]"
              />
            </el-select>
          </el-form-item>

          <!-- 个人业务营销员类型 - 显示条件：channelCode 为其他值（非G非H） -->
          <el-form-item
            v-if="form.channelCode && form.channelCode !== 'G' && form.channelCode !== 'H'"
            label="个人业务营销员类型"
            prop="indSalespersonType"
            label-width="130px"
          >
            <el-select
              v-model="form.indSalespersonType"
              placeholder="请输入个人业务营销员类型"
              style="width: 200px"
              clearable
              @change="handleIndSalespersonTypeChange"
            >
              <el-option
                v-for="dict in ind_salesperson_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                :disabled="disabledIndCustomerOptions[dict.value]"
              />
            </el-select>
          </el-form-item>

          <!-- 产品类型 - 始终显示 -->
          <el-form-item label="产品类型" prop="productType" v-if="form.channelCode" label-width="90px">
            <el-select
              v-model="form.productType"
              placeholder="请输入产品类型"
              style="width: 200px"
              clearable
              multiple
              @change="handleProductTypeChange"
            >
              <el-option
                v-for="dict in product_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                :disabled="disabledProductOptions[dict.value]"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input
            v-model="form.contactEmail"
            type="textarea"
            :rows="2"
            placeholder="请输入联系邮箱，多个邮箱用分号;分隔，每个邮箱需以@ydthlife.sgcc.com.cn结尾"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="adjustment">
          <el-input v-model="form.adjustment" type="textarea" :rows="3" placeholder="请输入调整原因" show-word-limit maxlength="500" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FinancialConfig" lang="ts">
import {
  listFinancialConfig,
  getFinancialConfig,
  delFinancialConfig,
  addFinancialConfig,
  updateFinancialConfig,
  listRulesCodeMapping
} from '@/api/financial/financialConfig';
import { FinancialConfigVO, FinancialConfigQuery, FinancialConfigForm, RulesCodeMappingForm } from '@/api/financial/financialConfig/types';

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,
  ruleCode: undefined,
  busType: undefined,
  bizCategory: undefined,
  busName: undefined,
  busDes: undefined,
  channelCode: undefined,
  channelType: undefined,
  grpCustomerType: undefined,
  indCustomerType: undefined,
  indSalespersonType: 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: undefined,
    params: {}
  },
  rules: {
    busType: [{ required: true, message: '业务类型不能为空', trigger: 'blur' }],
    ruleCode: [{ required: true, message: '规则编码不能为空', trigger: 'blur' }],
    bizCategory: [{ required: true, message: '业务类别不能为空', trigger: 'blur' }],
    busName: [{ required: true, message: '业务名称不能为空', trigger: 'blur' }],
    busDes: [{ required: true, message: '业务描述不能为空', trigger: 'blur' }],
    channelCode: [{ required: true, message: '业务渠道不能为空', trigger: 'blur' }],
    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@]+@ydthlife\.sgcc\.com\.cn$/i;

            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 resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: FinancialConfigVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加清单配置';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: FinancialConfigVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getFinancialConfig(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改清单配置';
};

/** 提交按钮 */
const submitForm = () => {
  financialConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      // 准备提交的数据，将数组转换为字符串
      const submitData = {
        ...form.value,
        // 将数组字段转换为逗号分隔的字符串
        grpCustomerType: Array.isArray(form.value.grpCustomerType) ? form.value.grpCustomerType.join(',') : form.value.grpCustomerType || '',
        productType: Array.isArray(form.value.productType) ? form.value.productType.join(',') : form.value.productType || ''
      };
      try {
        if (form.value.id) {
          await updateFinancialConfig(submitData);
        } else {
          await addFinancialConfig(submitData);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } catch (error) {
        console.error('提交失败:', error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

// script部分添加
const disabledProductOptions = computed(() => {
  const selected = form.value.productType || [];
  const hasSelected10 = selected.includes('10');

  if (!hasSelected10) return {};

  // 如果选择了10，禁用除10以外的所有选项
  const disabledMap: { [key: string]: boolean } = {};
  product_type.value?.forEach((option: any) => {
    if (option.value !== '10') {
      disabledMap[option.value] = true;
    }
  });
  return disabledMap;
});

const handleProductTypeChange = (selectedValues: string[]) => {
  // 如果选择了10，则清除其他选项
  const hasSelected10 = selectedValues.includes('10');

  if (hasSelected10) {
    // 如果选择了10，只保留10
    form.value.productType = ['10'];
  }
};

const disabledIndCustomerOptions = computed(() => {
  const selected = form.value.indCustomerType || '';
  const hasSelected0 = selected === '0';

  if (!hasSelected0) return {};

  // 如果选择了0，禁用除0以外的所有选项
  const disabledMap: { [key: string]: boolean } = {};
  ind_customer_type.value?.forEach((option: any) => {
    if (option.value !== '0') {
      disabledMap[option.value] = true;
    }
  });
  return disabledMap;
});

// 监听个人业务客户类型变化的方法
const handleIndCustomerTypeChange = (selectedValue: string) => {
  // 如果选择了0，确保值就是0
  if (selectedValue === '0') {
    form.value.indCustomerType = '0';
  }
};

// 监听个人业务客户类型变化的方法
const handleIndSalespersonTypeChange = (selectedValue: string) => {
  // 如果选择了0，确保值就是0
  if (selectedValue === '0') {
    form.value.indSalespersonType = '0';
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: FinancialConfigVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除清单配置编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delFinancialConfig(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'bfs/financialConfig/export',
    {
      ...queryParams.value
    },
    `financialConfig_${new Date().getTime()}.xlsx`
  );
};

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