<template>
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="90%" :before-close="handleClose" append-to-body>
    <el-form ref="dialogFormRef" :model="form" :rules="rules" label-width="120px" :inline="true">
      <el-row>
        <el-form-item label="产品编号" prop="productCode">
          <el-input v-model="form.productCode" disabled placeholder="请输入产品编号" />
        </el-form-item>
        <el-form-item label="产品状态" prop="salesStatus" label-width="100px">
          <el-select v-model="form.salesStatus" placeholder="产品状态" style="width: 240px" clearable>
            <el-option v-for="dict in filteredSalesStatus" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品销售限额(万元)" prop="salesLimit" label-width="150px">
          <el-input-number v-model="form.salesLimit" :disabled="form.salesStatus === '1'" clearable />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="产品销售起期" prop="salesStartDate">
          <el-date-picker
            v-model="form.salesStartDate"
            :disabled="isSalesStopDateDisabled || form.salesStatus === '1'"
            clearable
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择产品销售起期"
            :disabled-date="pickerAfterDate"
          />
        </el-form-item>
        <el-form-item label="产品销售止期" label-width="120px" prop="salesEndDate">
          <el-date-picker
            v-model="form.salesEndDate"
            :disabled="form.salesStatus === '-1' || isSalesStopDateDisabled"
            clearable
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择产品销售止期"
            :disabled-date="pickerAfterDate"
          />
        </el-form-item>
        <el-form-item label="承保截止时间" prop="signEndDate">
          <el-date-picker
            v-model="form.signEndDate"
            :disabled="form.salesStatus != '1' || isSalesStopDateDisabled"
            clearable
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择承保截止时间"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item v-if="form.salesStatus === '1'" label="产品停售原因:" prop="stopSalesReason">
          <el-input
            v-model="form.stopSalesReason"
            style="width: 260px; line-height: 100px"
            :autosize="{ minRows: 2, maxRows: 7 }"
            type="textarea"
            placeholder="产品停售原因"
            :disabled="isSalesStopDateDisabled"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="是否发送通知邮件" prop="emilNotice">
          <el-switch v-model="form.emailNotice" active-value="0" inactive-value="1" :disabled="isSalesStopDateDisabled"></el-switch>
        </el-form-item>
        <el-form-item label="产品销售是否限制机构" label-width="150px" prop="isInstitution">
          <el-switch v-model="form.isInstitution" :disabled="isSalesStopDateDisabled" @change="cleanInstitution"></el-switch>
        </el-form-item>
      </el-row>
    </el-form>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>产品销售渠道</span>
        </div>
      </template>
      <el-table :data="channelList">
        <el-table-column label="销售渠道" style="width: 20%" align="center" prop="salesChannel">
          <template #default="scope">
            <el-select v-model="scope.row.salesChannel" placeholder="销售渠道" :disabled="form.salesStatus === '1'" clearable>
              <el-option v-for="dict in sales_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="销售起期" style="width: 20%" align="center" prop="salesStartDate">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.salesStartDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择产品销售起期"
              :disabled="form.salesStatus === '1'"
              :disabled-date="pickerAfterDate"
            />
          </template>
        </el-table-column>
        <el-table-column label="销售止期" style="width: 20%" align="center" prop="salesEndDate">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.salesEndDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择产品销售止期"
              :disabled="isSalesStopDateDisabled"
            />
          </template>
        </el-table-column>
        <el-table-column label="承保截止日期" align="center" prop="signEndDate">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.signEndDate"
              clearable
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择承保截止时间"
              :disabled="isSalesStopDateDisabled"
            />
          </template>
        </el-table-column>
        <el-table-column label="销售限额(万元)" style="width: 20%" align="center" prop="salesLimit">
          <template #default="scope">
            <el-input-number v-model="scope.row.salesLimit" :disabled="form.salesStatus === '1'" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['product:apply:changeapplyremove']"
                link
                type="primary"
                icon="Delete"
                :disabled="isSalesStartDateDisabled || isSalesStopDateDisabled"
                @click="handleDeleteChannels(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-button v-hasPermi="['product:apply:changeapplyadd']" type="primary" :disabled="isSalesStopDateDisabled" @click="addChannelListRow"
        >+</el-button
      >
    </el-card>
    <el-card v-if="form.isInstitution">
      <template #header>
        <div class="card-header">
          <span>产品销售机构</span>
        </div>
      </template>
      <el-table :data="institutionList">
        <el-table-column label="销售机构" style="width: 25%" align="center" prop="salesInstitution">
          <template #default="scope">
            <el-select v-model="scope.row.salesInstitution" placeholder="销售机构" :disabled="form.salesStatus === '1'" clearable>
              <el-option v-for="dict in filteredSysManagecom(sys_managecom)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="销售起期" align="center" prop="salesStartDate">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.salesStartDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择产品销售起期"
              :disabled-date="pickerAfterDate"
              :disabled="form.salesStatus === '1'"
            />
          </template>
        </el-table-column>
        <el-table-column label="销售止期" align="center" prop="salesEndDate">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.salesEndDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择产品销售止期"
              :disabled="isSalesStopDateDisabled"
            />
          </template>
        </el-table-column>
        <el-table-column label="承保截止日期" align="center" prop="signEndDate">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.signEndDate"
              clearable
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择承保截止时间"
              :disabled="isSalesStopDateDisabled"
            />
          </template>
        </el-table-column>
        <el-table-column label="销售限额(万元)" style="width: 20%" align="center" prop="salesLimit">
          <template #default="scope">
            <el-input-number v-model="scope.row.salesLimit" :disabled="form.salesStatus === '1'" />
          </template>
        </el-table-column>
        <el-table-column label="销售渠道" align="center" prop="salesChannel">
          <template #header>
            <span>关联销售渠道</span>
          </template>
          <template #default="scope">
            <el-select
              v-model="scope.row.salesChannel"
              placeholder="请选择关联渠道"
              style="width: 100%"
              clearable
              :disabled="!selectedChannelValues.length || form.salesStatus === '1'"
            >
              <el-option
                v-for="channel in channelList"
                :key="channel.salesChannel"
                :label="getChannelLabel(channel.salesChannel)"
                :value="channel.salesChannel"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['product:apply:changeapplyremove']"
                link
                type="primary"
                icon="Delete"
                :disabled="form.salesStatus === '1'"
                @click="handleDeleteInstitutions(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-button v-hasPermi="['product:apply:changeapplyadd']" type="primary" :disabled="isSalesStopDateDisabled" @click="addInstitutionListRow"
        >+
      </el-button>
    </el-card>
    <el-form-item style="margin-top: 20px">
      <el-button
        v-hasPermi="['product:apply:changeapply']"
        type="primary"
        icon="Check"
        :loading="productSalesApplyLoading"
        :disabled="isSalesStopDateDisabled"
        @click="productSalesApply"
      >
        保存
      </el-button>
    </el-form-item>
  </el-dialog>
</template>
<script setup name="apply-detail" lang="ts">
import { infoByApplicationId, productApply, queryByApplicant, searchText, updateApplicationInfo } from '@/api/product/apply';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import lodash from 'lodash';
import { pickerAfterDate } from '@/utils/date';

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 institutionList = ref([]);
//产品销售渠道列表
const channelList = ref([]);

const productSalesApplyLoading = ref(false);
//存储变更前的产品销售信息
const oldInfo = ref<any>({});
//是否为变更
const changeFlag = ref(false);

const dialogFormRef = ref<ElFormInstance>();

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

const props = defineProps({
  detailVisible: Boolean,
  detailProductCode: String,
  isChange: Boolean,
  detailApplyId: String
});
const initFormData = {
  productCode: undefined,
  salesStatus: undefined,
  salesLimit: undefined,
  salesStartDate: undefined,
  salesEndDate: undefined,
  signEndDate: undefined,
  emailNotice: undefined,
  stopSalesReason: undefined,
  applicant: undefined,
  system: undefined,
  productName: undefined
};
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productCode: undefined,
    salesStatus: undefined,
    salesLimit: undefined,
    salesStartDate: undefined,
    salesEndDate: undefined,
    signEndDate: undefined
  },
  form: { ...initFormData },
  rules: {
    salesStartDate: [{ validator: validateSalesStartDate, trigger: 'blur' }],
    salesEndDate: [{ validator: validateEndDate, trigger: 'blur' }],
    signEndDate: [{ validator: validateSignEndDate, trigger: 'blur' }],
    stopSalesReason: [{ validator: validateStopSalesReason, trigger: 'blur' }]
  }
});
const { queryParams, rules, form } = toRefs(data);

const emit = defineEmits(['update:detailVisible']);

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

// 计算过滤后的销售状态选项
const filteredSalesStatus = computed(() => {
  // 如果初始状态是"停售"(1)，只显示"复售"(2)选项
  if (oldInfo.value.salesStatus === '1') {
    return sales_status.value.filter((item) => item.value === '2');
  }
  // 如果初始状态是"待起售"(-1)，过滤掉"复售"(2) 停售选项
  if (oldInfo.value.salesStatus === '-1') {
    return sales_status.value.filter((item) => item.value !== '2' && item.value !== '1');
  }
  // 如果初始状态是"起售"(0)，过滤掉"待起售"(-1)选项
  if (oldInfo.value.salesStatus === '0') {
    return sales_status.value.filter((item) => item.value !== '-1' && item.value !== '2');
  }
  // 其他情况显示所有选项
  return sales_status.value;
});

const isSalesStartDateDisabled = computed(() => {
  return oldInfo.value?.salesStatus === '0';
});

const isSalesStopDateDisabled = computed(() => {
  // 当产品状态从停售(1)改为复售(2)时返回false
  if (oldInfo.value.salesStatus === '1' && form.value.salesStatus === '2') {
    return false;
  }
  return oldInfo.value?.salesStatus === '1';
});

/** 产品销售权限配置申请保存 */
const productSalesApply = async () => {
  // 手动验证表单
  const valid = await new Promise<boolean>((resolve) => {
    dialogFormRef.value?.validate((isValid) => {
      resolve(isValid);
    });
  });
  if (valid && saveValidate()) {
    // 如果 salesStatus 无变化，salesStartDate 有变化给出确认提示
    if (form.value.salesStatus === oldInfo.value.salesStatus && form.value.salesStartDate !== oldInfo.value.salesStartDate) {
      const confirmResult = await proxy?.$modal.confirm('销售状态无变化，确定要变化销售起期？');
      if (!confirmResult) {
        return; // 用户取消操作，直接返回
      }
    }
    productSalesApplyLoading.value = true;
    try {
      let res;
      if (changeFlag.value) {
        res = await updateApplicationInfo(form.value, institutionList.value, channelList.value);
      } else {
        res = await productApply(form.value, institutionList.value, channelList.value);
      }
      if (res.code === 200 && res.data) {
        proxy?.$modal.msgSuccess('产品销售状态变更申请成功');
        dialog.visible = false;
      } else if (res.code === 200 && !res.data) {
        proxy?.$modal.msgError('产品销售状态变更申请失败' + res.msg);
      }
    } catch (e) {
    } finally {
      productSalesApplyLoading.value = false;
    }
  }
};

/** 产品销售权限配置保存前的校验 */
const saveValidate = () => {
  //校验是否存在信息变更
  if (!checkChange()) {
    proxy?.$modal.msgError('产品销售信息无变化');
    return false;
  }
  // 检查 channelList 是否为空
  if (channelList.value.length === 0) {
    proxy?.$modal.msgError('销售渠道不能为空');
    return false;
  }

  // 检查是否有未选择的销售渠道
  const hasEmptyChannel = channelList.value.some((item) => !item.salesChannel);
  if (hasEmptyChannel) {
    proxy?.$modal.msgError('请选择销售渠道');
    return false;
  }

  // 检查是否有重复的销售渠道
  const channelValues = channelList.value.map((item) => item.salesChannel);
  const duplicateChannels = channelValues.filter((item, index) => channelValues.indexOf(item) !== index);
  const hasChannelDuplicates = duplicateChannels.length > 0;

  if (hasChannelDuplicates) {
    // 获取字典中的渠道映射关系
    const channelDict = sales_channel.value || [];

    // 转换渠道code为渠道名称
    const getChannelName = (code) => {
      const found = channelDict.find((item) => item.value === code);
      return found ? found.label : code; // 如果找不到，默认显示code
    };

    // 获取所有重复的渠道名称（去重）
    const uniqueDuplicates = [...new Set(duplicateChannels)].map((code) => getChannelName(code));

    proxy?.$modal.msgError(`销售渠道 ${uniqueDuplicates.join('、')} 重复，请检查`);
    return false;
  }
  //channelList里面的salesStartDate不能在from.salesStartDate之前
  const salesStartDate = form.value.salesStartDate.match(/^\d{4}-\d{2}-\d{2}/)[0];
  for (const channel of channelList.value) {
    if (channel.salesStartDate && channel.salesStartDate < salesStartDate) {
      proxy?.$modal.msgError('销售渠道的销售起期不能在产品销售起期之前');
      return false;
    }
  }
  //机构的销售起期不能早于关联渠道的销售起期
  for (const institution of institutionList.value) {
    if (!institution.salesChannel) continue;

    const relatedChannel = channelList.value.find((channel) => channel.salesChannel === institution.salesChannel);
    if (institution.salesStartDate && !relatedChannel.salesStartDate) {
      proxy?.$modal.msgError('机构的销售起期不为空时，关联渠道的销售起期不能为空');
      return false;
    }

    if (relatedChannel && institution.salesStartDate && relatedChannel.salesStartDate) {
      if (institution.salesStartDate.match(/^\d{4}-\d{2}-\d{2}/)[0] < relatedChannel.salesStartDate.match(/^\d{4}-\d{2}-\d{2}/)[0]) {
        proxy?.$modal.msgError('机构的销售起期不能早于关联渠道的销售起期');
        return false;
      }
    }
  }
  //channelList里面的salesEndDate不能在from.salesEndDate之后
  const salesEndDate = form.value.salesEndDate;
  for (const channel of channelList.value) {
    if (channel.salesEndDate && channel.salesEndDate > salesEndDate) {
      proxy?.$modal.msgError('销售渠道的销售止期不能在产品销售止期之后');
      return false;
    }
    if (channel.salesEndDate && channel.salesEndDate < new Date().toISOString().split('T')[0]) {
      proxy?.$modal.msgError('销售渠道的销售止期不能早于当前日期');
      return false;
    }
  }

  //机构的销售止期不能晚于关联渠道的销售止期
  for (const institution of institutionList.value) {
    if (!institution.salesChannel) continue;

    const relatedChannel = channelList.value.find((channel) => channel.salesChannel === institution.salesChannel);

    if (relatedChannel && institution.salesEndDate && relatedChannel.salesEndDate) {
      if (institution.salesEndDate.match(/^\d{4}-\d{2}-\d{2}/)[0] > relatedChannel.salesEndDate.match(/^\d{4}-\d{2}-\d{2}/)[0]) {
        proxy?.$modal.msgError('机构的销售止期不能晚于关联渠道的销售止期');
        return false;
      }
    }
  }

  //institutionList里面的salesStartDate不能在from.salesStartDate之前
  for (const institution of institutionList.value) {
    if (institution.salesStartDate && institution.salesStartDate < salesStartDate) {
      proxy?.$modal.msgError('机构的销售起期不能在产品销售起期之前');
      return false;
    }
  }
  //institutionList里面的salesEndDate不能在from.salesEndDate之后
  for (const institution of institutionList.value) {
    if (institution.salesEndDate && institution.salesEndDate > salesEndDate) {
      proxy?.$modal.msgError('机构的销售止期不能在产品销售止期之后');
      return false;
    }
    if (institution.salesEndDate && institution.salesEndDate < new Date().toISOString().split('T')[0]) {
      proxy?.$modal.msgError('机构的销售止期不能早于当前日期');
      return false;
    }
  }
  if (form.value.isInstitution) {
    //检查 institutionList 是否为空
    if (institutionList.value.length === 0) {
      proxy?.$modal.msgError('销售机构不能为空');
      return false;
    }

    //检查是否有未选择的销售机构
    const hasEmptyInstitution = institutionList.value.some((item) => !item.salesInstitution);
    if (hasEmptyInstitution) {
      proxy?.$modal.msgError('请选择销售机构');
      return false;
    }
  }

  // 检查渠道销售限额是否超过产品总销售限额
  if (form.value.salesLimit !== undefined && form.value.salesLimit !== null) {
    //检查单个渠道是否超过总限额
    const hasExceededLimit = channelList.value.some((channel) => channel.salesLimit > form.value.salesLimit);
    if (hasExceededLimit) {
      proxy?.$modal.msgError('单个渠道销售限额不能超过产品总销售限额');
      return false;
    }
  }
  //销售限额相关校验
  const productLimit = form.value.salesLimit || 0;
  // 校验1: 产品的销售限额 ≥ 每个渠道的销售限额
  for (const channel of channelList.value) {
    const channelLimit = channel.salesLimit || 0;
    if (channelLimit > productLimit) {
      proxy?.$modal.msgError(`渠道的销售限额不能超过产品总销售限额`);
      return false;
    }
  }

  // 校验2: 所有渠道销售限额总和 ≤ 产品总销售限额
  const totalChannelLimit = channelList.value.reduce((sum, channel) => sum + (channel.salesLimit || 0), 0);
  if (totalChannelLimit > productLimit) {
    proxy?.$modal.msgError(`所有渠道销售限额总和不能超过产品总销售限额`);
    return false;
  }

  const channelInstitutionLimits = {}; // 记录各渠道关联的机构限额总和

  for (const institution of institutionList.value) {
    if (!institution.salesChannel) continue;

    const relatedChannel = channelList.value.find((c) => c.salesChannel === institution.salesChannel);
    if (!relatedChannel) continue;

    const institutionLimit = institution.salesLimit || 0;
    const channelLimit = relatedChannel.salesLimit || 0;

    // 校验3: 单个机构限额 ≤ 关联渠道限额
    if (institutionLimit > channelLimit) {
      proxy?.$modal.msgError(`机构的销售限额不能超过关联渠道的限额`);
      return false;
    }

    // 统计各渠道关联的机构限额总和
    if (!channelInstitutionLimits[institution.salesChannel]) {
      channelInstitutionLimits[institution.salesChannel] = 0;
    }
    channelInstitutionLimits[institution.salesChannel] += institutionLimit;
  }

  // 校验4: 各渠道关联的机构限额总和 ≤ 该渠道限额
  for (const [channelValue, totalInstitutionLimit] of Object.entries(channelInstitutionLimits)) {
    const channel = channelList.value.find((c) => c.salesChannel === channelValue);
    if (channel && totalInstitutionLimit > (channel.salesLimit || 0)) {
      proxy?.$modal.msgError(`渠道关联的所有机构销售限额总和不能超过该渠道限额`);
      return false;
    }
  }

  // 当产品限额不为空时，检查渠道和机构限额
  if (productLimit !== null && productLimit !== undefined && productLimit !== 0) {
    // 检查渠道限额是否为空
    for (const channel of channelList.value) {
      if (channel.salesLimit === null || channel.salesLimit === undefined || channel.salesLimit === 0) {
        proxy?.$modal.msgError(`渠道的销售限额不能为空`);
        return false;
      }
    }

    // 检查机构限额是否为空
    for (const institution of institutionList.value) {
      if (institution.salesLimit === null || institution.salesLimit === undefined || institution.salesLimit === 0) {
        proxy?.$modal.msgError(`机构的销售限额不能为空`);
        return false;
      }
    }
  }

  // 检查机构是否选择了销售渠道
  if (form.value.isInstitution) {
    const hasEmptyChannels = institutionList.value.some((institution) => !institution.salesChannel);
    if (hasEmptyChannels) {
      proxy?.$modal.msgError('请为每个销售机构选择一个销售渠道');
      return false;
    }
  }
  //承保截止时间相关校验
  const productSignEndDate = form.value.signEndDate;
  for (const channel of channelList.value) {
    if (channel.signEndDate && productSignEndDate && channel.signEndDate > productSignEndDate) {
      proxy?.$modal.msgError(`渠道的承保截止时间不能晚于产品承保截止日期`);
      return false;
    }

    if (channel.signEndDate && channel.salesEndDate && channel.signEndDate < channel.salesEndDate) {
      proxy?.$modal.msgError(`渠道的承保截止时间不能早于该渠道销售止期`);
      return false;
    }
  }
  for (const institution of institutionList.value) {
    if (institution.signEndDate && productSignEndDate && institution.signEndDate > productSignEndDate) {
      proxy?.$modal.msgError(`机构的承保截止时间不能晚于产品承保截止日期`);
      return false;
    }

    if (institution.signEndDate && institution.salesEndDate && institution.signEndDate < institution.salesEndDate) {
      proxy?.$modal.msgError(`机构的承保截止时间不能早于该机构销售止期`);
      return false;
    }

    if (institution.salesChannel) {
      const relatedChannel = channelList.value.find((c) => c.salesChannel === institution.salesChannel);
      if (relatedChannel && institution.signEndDate && relatedChannel.signEndDate && institution.signEndDate > relatedChannel.signEndDate) {
        proxy?.$modal.msgError(`机构的承保截止时间不能晚于关联渠道的承保截止时间`);
        return false;
      }
    }
  }
  return true;
};

const checkChange = () => {
  // 使用 _.omit 方法去除 form.value 中的 emailNotice 和 isInstitution 字段
  const formWithoutFields = lodash.omit(form.value, ['emailNotice', 'isInstitution']);
  const hasChanged = !lodash.isEqual(formWithoutFields, oldInfo.value);
  return hasChanged;
};

// 销售起期验证函数
function validateSalesStartDate(rule, value, callback) {
  if (form.value.salesStatus === '0' && !value) {
    callback(new Error('销售状态为起售时，销售起期不能为空'));
  } else {
    callback();
  }
}
// 销售止期验证函数
function validateEndDate(rule, value, callback) {
  if (form.value.salesStartDate && value && value < form.value.salesStartDate) {
    callback(new Error('销售止期不能早于销售起期'));
  }
  if (value && value < new Date().toISOString().split('T')[0]) {
    callback(new Error('销售止期不能早于当前日期'));
  }
  if (form.value.salesStatus === '1' && !value) {
    callback(new Error('销售状态为停售时，销售止期不能为空'));
  } else {
    callback();
  }
}
// 销售承保截止日期验证函数
function validateSignEndDate(rule, value, callback) {
  if (form.value.salesStatus === '1' && !value) {
    callback(new Error('销售状态为停售时，承保截止日期不能为空'));
  } else if (form.value.salesEndDate && value && value < form.value.salesEndDate) {
    callback(new Error('承保截止日期不能在销售止期之前'));
  } else {
    callback();
  }
}

//停售原因校验
function validateStopSalesReason(rule, value, callback) {
  if (form.value.salesStatus === '1' && !value) {
    callback(new Error('销售状态为停售时，产品停售原因不能为空'));
  } else if (value && value.length > 5000) {
    callback(new Error('产品停售原因不能超过5000字'));
  } else {
    callback();
  }
}

/** 增加行 */
const addInstitutionListRow = () => {
  const newRow = {
    salesInstitution: '',
    salesStartDate: '',
    salesEndDate: '',
    signEndDate: '',
    salesLimit: undefined,
    salesChannel: ''
  };
  institutionList.value.push(newRow);
};

/** 增加行 */
const addChannelListRow = () => {
  const newRow = { salesChannel: '', salesStartDate: '', salesEndDate: '', salesLimit: undefined, signEndDate: '' };
  channelList.value.push(newRow);
};

/**
 * 清理销售机构
 */
const cleanInstitution = () => {
  if (!form.value.isInstitution) {
    institutionList.value = [];
  }
};

/** 申请页面 删除可销售机构按钮操作 */
const handleDeleteInstitutions = async (row) => {
  if (oldInfo.value.salesStatus === '0') {
    // 产品状态为起售时，删除相同销售渠道的所有机构
    const channelToDelete = row.salesChannel;
    institutionList.value = institutionList.value.filter((item) => item.salesChannel !== channelToDelete);
  } else {
    // 其他状态下只删除当前行
    const index = institutionList.value.findIndex((item) => item === row);
    if (index !== -1) {
      institutionList.value.splice(index, 1);
    }
  }
};

/** 申请页面 删除可销售渠道按钮操作 */
const handleDeleteChannels = async (row) => {
  const index = channelList.value.findIndex((item) => item === row);
  if (index != -1) {
    channelList.value.splice(index, 1);
  }
};

async function updateDialog() {
  const { detailVisible, detailProductCode, isChange, detailApplyId } = props;
  if (detailVisible) {
    reset();
    if (!isChange) {
      const _productCode = detailProductCode;
      const res = await searchText(_productCode);

      // 初始时保留所有信息
      Object.assign(form.value, res.data);
      channelList.value = res.data.prodChannelControlList || [];
      institutionList.value = res.data.prodInstitutionControlList || [];
      form.value.isInstitution = institutionList.value.length > 0;

      oldInfo.value = res.data;
      dialog.visible = true;
      dialog.title = '产品销售状态变更申请';
    } else {
      // 变更逻辑保持不变
      const _applyId = detailApplyId;
      const res = await infoByApplicationId(_applyId);
      Object.assign(form.value, res.data);
      channelList.value = res.data.channelApplicationList || [];
      institutionList.value = res.data.institutionApplicationList || [];
      form.value.isInstitution = institutionList.value.length > 0;
      changeFlag.value = true;
      dialog.visible = true;
      dialog.title = '产品销售状态变更修改';
    }
  }
}

const handleClose = (done: () => void) => {
  dialog.visible = false;
  emit('update:detailVisible', false);
  done();
};

const filteredSysManagecom = (managecom) => {
  return managecom.filter((dict) => String(dict.value).length === 4);
};

// 获取已选择的销售渠道值列表
const selectedChannelValues = computed(() => {
  return channelList.value.map((item) => item.salesChannel).filter(Boolean);
});

// 根据渠道值获取渠道标签
const getChannelLabel = (value) => {
  const found = sales_channel.value.find((item) => item.value === value);
  return found ? found.label : value;
};

watch(
  () => ({
    detailVisible: props.detailVisible,
    detailProductCode: props.detailProductCode,
    isChange: props.isChange,
    detailApplyId: props.detailApplyId
  }),
  (detailVisible, detailProductCode, isChange, detailApplyId) => {
    updateDialog();
  },
  { deep: true, immediate: true }
);

// 确保 dialog.value.visible 和父组件的 visible 属性同步
watch(
  () => props.detailVisible,
  (newVal) => {
    dialog.visible = newVal;
  }
);

//监听dialog.visible变化传递父组件
watch(dialog.visible, (newVal) => {
  emit('update:detailVisible', newVal);
});

// 在watch中添加对salesStatus的监听
watch(
  () => form.value.salesStatus,
  (newVal, oldVal) => {
    // 只有当从停售(1)改为复售(2)时才清空表单
    if (oldInfo.value.salesStatus === '1' && newVal === '2') {
      //  console.log(form.value);
      const { productCode, salesStatus, productName, system } = form.value;
      form.value = {
        ...initFormData,
        productCode,
        productName,
        system,
        salesStatus: '2', // 保持复售状态
        salesLimit: undefined, // 清空产品限额
        salesStartDate: undefined, // 清空产品销售起期
        salesEndDate: undefined, // 清空产品销售止期
        signEndDate: undefined, // 清空承保截止时间
        isInstitution: false // 重置机构开关
      };
      channelList.value = []; // 清空销售渠道
      institutionList.value = []; // 清空销售机构
    }
  }
);
</script>

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