<template>
  <div>
    <el-tabs v-model="curTab">
      <el-tab-pane :label="id ? '产品要素' : '新增产品'"
                   name="tab1">
        <el-form label-width="100px"
                 label-suffix="："
                 class="max-w-[calc(100vw-540px)] overflow-auto form"
                 status-icon>
          <el-form-item label="保险名称"
                        prop="insuranceName">
            <el-input placeholder="取个有吸引力的产品名，限20字。"
                      maxlength="20"
                      v-model="form.insuranceName"></el-input>
          </el-form-item>
          <el-form-item label="险种分类"
                        prop="insuranceType">
            <el-select v-model="form.insuranceType"
                       placeholder="请选择">
              <el-option v-for="item in config[0]?.recordChildren[1]?.subject?.itemList"
                         :key="item"
                         :label="item.options"
                         :value="item.itemId" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.insuranceType === 310"
                        label="承保年龄">
            <div class="flex items-center">
              <div class="num-inputs">
                <el-input placeholder="最小年龄"
                          v-model.number="form.minimumAge"></el-input>
                <span class="split">-</span>
                <el-input placeholder="最大年龄"
                          v-model.number="form.maximumAge"></el-input>
                <span class="unit">周岁</span>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="保险额度">
            <div class="flex-1">
              <div class="flex">
                <p class="field-name w-[130px] mr-32">保险责任</p>
                <p class="field-name">保额</p>
              </div>
              <div v-for="(item, i) in config[form.insuranceType === 310 ? 0 : 1]?.recordChildren[2]?.recordChildren"
                   :key="i"
                   class="flex items-center mb-2">
                <div class="w-[130px] mr-32">
                  <el-checkbox :key="item.id"
                               v-model="item.check"
                               :label="item.name" />
                </div>
                <div v-if="item.check">
                  <el-input placeholder="请输入"
                            v-model="item.sumInsured">
                    <template #append>万</template>
                  </el-input>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="保费金额"
                        prop="minimumLoan">
            <div>
              <el-input placeholder="请输入"
                        v-model="form.premiumAmount">
                <template #append>万</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="缴纳形式">
            <el-radio :label="312"
                      v-model="form.formOfPayment">趸交</el-radio>
          </el-form-item>
          <el-form-item label="保险期限">
            <div class="flex">
              <el-input class="mr-2"
                        placeholder="请输入"
                        v-model="form.insuranceDeadline"></el-input>
              <el-select v-model="form.insuranceDeadlineUnit"
                         placeholder="请选择"
                         clearable>
                <el-option v-for="item in units"
                           :key="item"
                           :label="item"
                           :value="item" />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="申请材料">
            <el-checkbox-group v-model="form.applicationMaterial">
              <el-checkbox v-for="(item, i) in config[form.insuranceType === 310 ? 0 : 1]?.recordChildren[6]?.subject?.itemList"
                           :key="i"
                           :label="item.itemId">{{ item.options }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="责任免除">
            <el-checkbox-group v-model="form.exemptionFromLiability">
              <el-checkbox v-for="(item, i) in config[0]?.recordChildren[7]?.subject?.itemList"
                           :key="i"
                           :label="item.itemId">{{ item.options }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div class="flex justify-end">
            <div class="submit"
                 @click="submit">完成</div>
          </div>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import { insuranceProductDetails, addInsuranceProducts } from '@/api/insurance';
import { getProcessInformationBasedOnRoles, addOperation } from '@/api/judgment';
import { useRouter, useRoute } from 'vue-router';
import { handleId } from '@/utils/common';
import { getStatus } from '@/store/useProduct';
import Info from './Info.vue';
import Cookies from 'js-cookie';

const emit = defineEmits(['getList']);

const router = useRouter();
const route = useRoute();
const id = computed(() => route.query.id);
const projectId = +Cookies.get('sand-projectId');
const levelId = +Cookies.get('sand-level');
const curTab = ref<string>('tab1');
const config = ref<any[]>([]);
const info = ref<Record<string, any>>(null);
const units: Array<string> = ['年', '个月', '天', '小时'];
const form = reactive({
  checkPointId: levelId,
  projectId,
  insuranceName: '',
  applicationMaterial: [],
  exemptionFromLiability: [],
  formOfPayment: '',
  insuranceCoverageConfigList: [],
  insuranceDeadline: '',
  insuranceDeadlineUnit: '',
  maximumAge: '',
  insuranceType: 310,
  premiumAmount: '',
  minimumAge: '',
});

// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(275);
  config.value = process;
};
// 详情
const getDetail = async () => {
  if (id.value) {
    try {
      const { data } = await insuranceProductDetails(id.value);
      info.value = data;
    } finally {
    }
  }
};
watch(
  () => route.query,
  () => {
    getDetail();
  },
  {
    immediate: true,
  },
);
// 新增判分记录
const addRecord = async (data: Record<string, any>) => {
  const preIds = `1,${Cookies.get('sand-level')},275,${data.insuranceType === 310 ? 276 : 277}`; // 1，关卡id，角色（这个页面是保险产品经理新增产品）
  const rule: Array<Record<string, any>> = [handleId(278, 118, data.insuranceName, preIds + ',278', 3), handleId(279, 119, data.insuranceType, preIds + ',279', 1)];
  data.minimumAge && rule.push(handleId(680, 219, data.minimumAge, preIds + ',678,680', 3));
  data.maximumAge && rule.push(handleId(679, 218, data.maximumAge, preIds + ',678,679', 3));
  // 保险额度
  config.value[form.insuranceType === 310 ? 0 : 1]?.recordChildren[2]?.recordChildren?.map((e) => {
    rule.push(handleId(766, 140, e.check ? 345 : 346, `${preIds},280,${e.id},766`, 1));
    e.check && e.sumInsured && rule.push(handleId(767, 234, e.sumInsured, `${preIds},280,${e.id},767`, 3));
  });
  data.premiumAmount && rule.push(handleId(296, 134, data.premiumAmount, preIds + ',296', 3));
  data.formOfPayment && rule.push(handleId(297, 135, data.formOfPayment, preIds + ',297', 1));

  form.insuranceDeadline && rule.push(handleId(770, 136, form.insuranceDeadline, preIds + ',298,770', 3));
  form.insuranceDeadlineUnit &&
    rule.push(
      handleId(
        771,
        235,
        config.value[form.insuranceType === 310 ? 0 : 1]?.recordChildren[5]?.recordChildren[1]?.subject?.itemList?.find((e) => e.options === form.insuranceDeadlineUnit)?.itemId,
        preIds + ',298,771',
        1,
      ),
    );
  data.applicationMaterial && rule.push(handleId(299, 137, data.applicationMaterial, preIds + ',299', 1));
  data.exemptionFromLiability && rule.push(handleId(301, 139, data.exemptionFromLiability, preIds + ',301', 1));

  await addOperation({
    checkpointId: levelId,
    parentId: preIds,
    lcJudgmentRuleReq: rule,
    projectId,
  });
};
// 提交
const submit = async () => {
  try {
    const param = JSON.parse(JSON.stringify(form));

    if (!param.insuranceName) return ElMessage.error('请输入保险名称');
    param.insuranceDeadline = param.insuranceDeadline + param.insuranceDeadlineUnit;
    config.value[form.insuranceType === 310 ? 0 : 1]?.recordChildren[2]?.recordChildren.map((e) => {
      e.check &&
        e.sumInsured &&
        param.insuranceCoverageConfigList.push({
          insuredLiabilityId: e.id,
          sumInsured: +e.sumInsured,
        });
    });
    if (param.premiumAmount && !isNaN(param.premiumAmount)) param.premiumAmount = Number(param.premiumAmount).toFixed(2);
    param.applicationMaterial = param.applicationMaterial.join();
    param.exemptionFromLiability = param.exemptionFromLiability.join();
    await addInsuranceProducts(param);
    addRecord(param);
    ElMessage.success('提交成功！');
    emit('getList', 1);
  } finally {
  }
};
onMounted(() => {
  getConfig();
});
</script>

<style lang="scss" scoped>
@import url(../../../styles/form.scss);
.audit {
  @apply py-5 px-4 mb-[30px] bg-[#f9fafc] rounded-[10px];
  .line {
    @apply mb-[18px] text-sm leading-[1.6];
  }
  .field {
    @apply text-sm font-semibold;
  }
}
</style>
