<template>
  <!-- 贷后评分 -->
  <el-table class="c-table"
            :data="form"
            :span-method="span"
            :cell-style="{background:'#fff'}"
            border>
    <el-table-column prop="recordName"
                     label="指标"
                     min-width="80"
                     align="center"></el-table-column>
    <el-table-column prop="recordName"
                     label="公式/取值"
                     min-width="200"
                     align="center">
      <template #default="{ row, $index }">
        <div class="flex items-center">
          <template v-if="$index === 1">
            存贷比 =
            <div class="inline-flex flex-col justify-center mx-2">
              <el-select v-if="row.recordChildren"
                         class="w-[140px]"
                         v-model="row.formulaOne">
                <el-option v-for="item in row?.recordChildren[0].subject.itemList"
                           :key="item"
                           :label="item.options"
                           :value="item.itemId" />
              </el-select>
              <p class="h-[1px] my-2 bg-[#cdcdcd]"></p>
              <el-select v-if="row.recordChildren"
                         class="w-[140px]"
                         v-model="row.formulaTwo">
                <el-option v-for="item in row?.recordChildren[1].subject.itemList"
                           :key="item"
                           :label="item.options"
                           :value="item.itemId" />
              </el-select>
            </div>
            x 100%
          </template>
          <template v-if="$index === 6">
            房屋净值 =
            <el-select v-if="row.recordChildren"
                       class="w-[140px] mx-2"
                       v-model="row.formulaOne">
              <el-option v-for="item in row?.recordChildren[0].subject.itemList"
                         :key="item"
                         :label="item.options"
                         :value="item.itemId" />
            </el-select>
            -
            <el-select v-if="row.recordChildren"
                       class="w-[140px] ml-2"
                       v-model="row.formulaTwo">
              <el-option v-for="item in row?.recordChildren[1].subject.itemList"
                         :key="item"
                         :label="item.options"
                         :value="item.itemId" />
            </el-select>
          </template>
          <template v-if="$index === 9">
            近
            <el-input class="w-[80px] mx-2"
                      v-model="row.formulaOne"></el-input>
            <el-select v-if="row.recordChildren"
                       class="w-[140px] mr-2"
                       v-model="row.formulaTwo">
              <el-option v-for="item in row?.recordChildren[1].subject.itemList"
                         :key="item"
                         :label="item.options"
                         :value="item.itemId" />
            </el-select>
            内逾期次数。
          </template>
          <template v-if="$index === 13">
            从
            <el-select v-if="row.recordChildren"
                       class="w-[140px] mx-2"
                       v-model="row.formulaOne">
              <el-option v-for="item in row?.recordChildren[0].subject.itemList"
                         :key="item"
                         :label="item.options"
                         :value="item.itemId" />
            </el-select>
            开始算，还款当天不计算利息。
          </template>
          <template v-if="$index === 17">当前尚未偿还的贷款总额。</template>
          <template v-if="$index === 20">
            平均额度使用率 =
            <div class="inline-flex flex-col justify-center mx-2">
              <el-select v-if="row.recordChildren"
                         class="w-[140px]"
                         v-model="row.formulaOne">
                <el-option v-for="item in row?.recordChildren[0].subject.itemList"
                           :key="item"
                           :label="item.options"
                           :value="item.itemId" />
              </el-select>
              <p class="h-[1px] my-2 bg-[#cdcdcd]"></p>
              <el-select v-if="row.recordChildren"
                         class="w-[140px]"
                         v-model="row.formulaTwo">
                <el-option v-for="item in row?.recordChildren[1].subject.itemList"
                           :key="item"
                           :label="item.options"
                           :value="item.itemId" />
              </el-select>
            </div>
            x 100%
          </template>
          <template v-if="$index === 24">
            最大用信率 =
            <div class="inline-flex flex-col justify-center mx-2">
              <el-select v-if="row.recordChildren"
                         class="w-[140px]"
                         v-model="row.formulaOne">
                <el-option v-for="item in row?.recordChildren[0].subject.itemList"
                           :key="item"
                           :label="item.options"
                           :value="item.itemId" />
              </el-select>
              <p class="h-[1px] my-2 bg-[#cdcdcd]"></p>
              <el-select v-if="row.recordChildren"
                         class="w-[140px]"
                         v-model="row.formulaTwo">
                <el-option v-for="item in row?.recordChildren[1].subject.itemList"
                           :key="item"
                           :label="item.options"
                           :value="item.itemId" />
              </el-select>
            </div>
            x 100%
          </template>
          <template v-if="$index === 28">到目前为止使用额度的次数。</template>
          <template v-if="$index === 32">到目前为止客户可以使用的最大额度。</template>
          <template v-if="$index === 37">客户贷记卡已经逾期的总月数。</template>
          <template v-if="$index === 39">客户在行所有贷款已经逾期的总月数。</template>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="ruleName"
                     label="取值"
                     min-width="100"
                     align="center"></el-table-column>
    <el-table-column label="分数"
                     min-width="80"
                     align="center">
      <template #default="{ row }">
        <el-select v-if="row.subject"
                   v-model="row.score">
          <el-option v-for="item in row.subject.itemList"
                     :key="item"
                     :label="item.options"
                     :value="item.itemId" />
        </el-select>
        <span v-else>600</span>
      </template>
    </el-table-column>
  </el-table>

  <div class="flex justify-end">
    <div class="submit"
         @click="submit">确认完成配置</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { postCreditScoreDetails, postCreditScoreSave } from '@/api/model';
import { getProcessInformationBasedOnRoles, addOperation } from '@/api/judgment';
import type { TableColumnCtx } from 'element-plus';
import { handleId } from '@/utils/common';
import Cookies from 'js-cookie';

const projectId = +Cookies.get('sand-projectId');
const levelId = +Cookies.get('sand-level');
const form = ref<Record<string, any>[]>([]);
const info = ref<Record<string, any>[]>([]);
// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(1031);
  const result = [
    {
      recordName: '基准分',
    },
  ];
  process.map((e, i) => {
    let temp = {
      checkpointId: levelId,
      projectId,
      recordName: e.name,
      recordChildren: e.recordChildren,
      formulaOne: '',
      formulaTwo: '',
      score: '',
      id: '',
      stRecordId: e.id,
      middleId: e.recordChildren[e.recordChildren.length - 1]?.id,
    };
    // 遍历“取值”这个流程
    e.recordChildren[e.recordChildren.length - 1]?.recordChildren?.map((n, j) => {
      temp = JSON.parse(JSON.stringify(temp));
      temp.index = j;
      temp.ruleName = n.name;
      temp.subject = n.subject;
      temp.ruleId = n.id;
      result.push(temp);
    });
  });
  if (info.value.length) {
    result.forEach((e, i) => {
      if (i) {
        e.formulaOne = info.value[i - 1].formulaOne ? +info.value[i - 1].formulaOne : '';
        e.indexId = info.value[i - 1].indexId;
        e.formulaTwo = info.value[i - 1].formulaTwo ? +info.value[i - 1].formulaTwo : '';
        e.score = info.value[i - 1].score ? +info.value[i - 1].score : '';
      }
    });
  }
  form.value = result;
  console.log('🚀 ~ file: 1031.vue:83 ~ getConfig ~ result:', result);
};
// 详情
const getDetail = async () => {
  try {
    const { data } = await postCreditScoreDetails(levelId, projectId);
    info.value = data;
    getConfig();
  } finally {
  }
};

interface SpanMethodProps {
  row: Record<string, any>;
  column: TableColumnCtx<Record<string, any>>;
  rowIndex: number;
  columnIndex: number;
}
const rowMerge1 = [1, 32];
const rowMerge2 = [6, 17];
const rowMerge3 = [9, 13, 20, 24, 28];
const rowMerge4 = [37, 39];
// 表格合并
const span = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  if (!rowIndex) {
    if (!columnIndex) {
      return {
        rowspan: 1,
        colspan: 3,
      };
    } else if (columnIndex === 3) {
      return {
        rowspan: 1,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }

  if (columnIndex < 2) {
    if (rowMerge1.includes(rowIndex)) {
      return {
        rowspan: 5,
        colspan: 1,
      };
    } else if (rowMerge2.includes(rowIndex)) {
      return {
        rowspan: 3,
        colspan: 1,
      };
    } else if (rowMerge3.includes(rowIndex)) {
      return {
        rowspan: 4,
        colspan: 1,
      };
    } else if (rowMerge4.includes(rowIndex)) {
      return {
        rowspan: 2,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
// 新增判分记录
const addRecord = async (data: Record<string, any>) => {
  const preIds = `1,${Cookies.get('sand-level')},42,69,1031`; // 1，关卡id，角色（这个页面是风控经理策略）
  const rule = [];

  data.forEach((e, i) => {
    e.score && rule.push(handleId(e.ruleId, e.subject.subjectId, e.score, `${preIds},${e.stRecordId},${e.middleId},${e.ruleId}`, 1));
    if (i === 1 || i === 6 || i === 20 || i === 24) {
      e.formulaOne && rule.push(handleId(1061, 285, e.formulaOne, `${preIds},${e.stRecordId},1061`, 1));
      e.formulaTwo && rule.push(handleId(1062, 285, e.formulaTwo, `${preIds},${e.stRecordId},1062`, 1));
    }
  });
  data[9].formulaOne && rule.push(handleId(1075, 288, data[9].formulaOne, `${preIds},1074,1075`, 3));
  data[9].formulaTwo && rule.push(handleId(1076, 289, data[9].formulaTwo, `${preIds},1074,1076`, 1));
  data[13].formulaOne && rule.push(handleId(1083, 291, data[13].formulaOne, `${preIds},1082,1083`, 1));

  await addOperation({
    checkpointId: levelId,
    parentId: preIds,
    lcJudgmentRuleReq: rule,
    projectId,
  });
};
// 提交
const submit = async () => {
  let param = JSON.parse(JSON.stringify(form.value));
  const recordParam = JSON.parse(JSON.stringify(param));
  param.map((e) => {
    delete e.recordChildren;
  });
  await postCreditScoreSave({ postCreditScoreList: param });
  addRecord(recordParam);
  getDetail();
  ElMessage.success('提交成功！');
};
onMounted(() => {
  getDetail();
});
</script>

<style lang="scss" scoped>
@import url(../../../styles/form.scss);
</style>
