<template>
  <!-- 个人额度模型 -->
  <el-form label-width="80px"
           class="form"
           status-icon>
    <h6 class="step-name mb-2">{{ formProcess[0]?.name }}</h6>
    <el-form-item label="不超过">
      <el-select v-model="form.firstMode">
        <el-option v-for="item in formProcess[0]?.recordChildren[0]?.subject?.itemList"
                   :key="item"
                   :value="item.options" />
      </el-select>
    </el-form-item>
    <h6 class="step-name mt-4 mb-2">{{ formProcess[1]?.name }}</h6>
    <el-form-item label="不超过">
      <el-select v-model="form.secondMode">
        <el-option v-for="item in formProcess[1]?.recordChildren[0]?.subject?.itemList"
                   :key="item"
                   :value="item.options" />
      </el-select>
    </el-form-item>
    <h6 class="step-name mt-4 mb-2">{{ formProcess[2]?.name }}</h6>
    <el-form-item label="不超过">
      <el-select v-model="form.thirdMode">
        <el-option v-for="item in formProcess[2]?.recordChildren[0]?.subject?.itemList"
                   :key="item"
                   :value="item.options" />
      </el-select>
    </el-form-item>
    <el-form-item label="且"></el-form-item>
    <el-form-item label="不超过">
      <el-select v-model="form.andThird">
        <el-option v-for="item in formProcess[2]?.recordChildren[1]?.subject?.itemList"
                   :key="item"
                   :value="item.options" />
      </el-select>
    </el-form-item>
    <el-form-item label="额度模型">
      <el-table class="c-table"
                :data="form.individualCreditModels"
                :span-method="span"
                border>
        <el-table-column prop="indexName"
                         label="指标名称"
                         min-width="100"
                         align="center">
          <template #default="{ row, $index }">
            <span :class="{'text-[#006bff]': !$index || $index === len}">{{ row?.indexName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述"
                         min-width="150">
          <template #default="{ row, $index }">
            <span :class="{'text-[#006bff]': !$index || $index === len}">{{ row?.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分值"
                         min-width="150">
          <template #default="{ row, $index }">
            <div v-if="$index !== len"
                 class="flex items-center">
              <span v-if="!$index"
                    class="mr-2 whitespace-nowrap">{{ row?.subject?.name }}</span>
              <el-select v-model="row.score">
                <el-option v-for="item in row?.subject?.itemList"
                           :key="item"
                           :value="item.options" />
              </el-select>
            </div>
            <span v-else
                  class="text-[#006bff]">以上分值合计</span>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </el-form>

  <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 { personalCreditModelDetails, personalCreditModelSaveOrUpdate } from '@/api/model';
import { getProcessInformationBasedOnRoles, addOperation } from '@/api/judgment';
import type { TableColumnCtx } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { handleId } from '@/utils/common';
import Cookies from 'js-cookie';

const router = useRouter();
const route = useRoute();
const projectId = +Cookies.get('sand-projectId');
const levelId = +Cookies.get('sand-level');
const form = ref<Record<string, any>>({
  projectId,
  checkpointId: levelId,
  andThird: '',
  firstMode: '',
  secondMode: '',
  thirdMode: '',
  type: 1,
  individualCreditModels: [],
});
const formProcess = ref<Record<string, any>[]>([]);
const info = ref<Record<string, any>[]>([]);
const len = ref<number>(0);
// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(772);
  formProcess.value = process.slice(0, 3);
  const list = process[3]?.recordChildren;
  let cur = info.value.length ? info.value[0] : {};
  const result = [
    {
      modelId: cur?.modelId || '',
      id: cur?.id || '',
      indexName: list[0]?.name,
      description: list[0]?.remark,
      subject: list[0]?.recordChildren[0]?.subject,
      score: cur?.score || '',
    },
  ];
  const length = list.length - 1;
  list?.forEach((e, i) => {
    if (i && i !== length) {
      cur = info.value.length ? info.value[i] : {};
      let temp = {
        indexName: e.name,
        recordChildren: e.recordChildren,
        stRecordId: e.id,
        ruleId: e?.recordChildren[0]?.id || '',
        description: e?.recordChildren[0]?.name || '',
        subject: e?.recordChildren[0]?.subject || [],
        score: '',
      };

      result.push(temp);
      e?.recordChildren.forEach((n, j) => {
        if (j) {
          temp = JSON.parse(JSON.stringify(temp));
          temp.description = n.name;
          temp.subject = n.subject;
          temp.ruleId = n.id;
          result.push(temp);
        }
      });
    }
  });
  cur = info.value.length ? info.value[info.value.length - 1] : {};
  result.push({
    indexName: list[length]?.name,
    description: list[length]?.remark,
    subject: list[length]?.subject,
    score: '',
  });
  len.value = result.length - 1;
  if (info.value.length) {
    result.forEach((e, i) => {
      result[i].score = info.value[i].score;
      result[i].id = info.value[i].id;
      result[i].modelId = info.value[i].modelId;
    });
  }
  form.value.individualCreditModels = result;
};
// 详情
const getDetail = async () => {
  try {
    const { data } = await personalCreditModelDetails(levelId, projectId);
    if (data) {
      form.value = data;
      info.value = data.individualCreditModels;
    }
    getConfig();
  } finally {
  }
};
onMounted(() => {
  getDetail();
});

interface SpanMethodProps {
  row: Record<string, any>;
  column: TableColumnCtx<Record<string, any>>;
  rowIndex: number;
  columnIndex: number;
}
const rowMerge1 = [1, 7, 16, 23, 71, 75, 87, 98];
const rowMerge2 = [5, 30, 59, 61, 63, 79];
const rowMerge3 = [11, 38, 45];
const rowMerge4 = [20, 27, 50, 53, 56, 65, 68, 81, 84, 102, 105, 108];
const rowMerge5 = [0, 43, 44, 111];
// 表格合并
const span = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (rowMerge1.includes(rowIndex)) {
      return {
        rowspan: 4,
        colspan: 1,
      };
    } else if (rowMerge2.includes(rowIndex)) {
      return {
        rowspan: 2,
        colspan: 1,
      };
    } else if (rowMerge3.includes(rowIndex)) {
      return {
        rowspan: 5,
        colspan: 1,
      };
    } else if (rowMerge4.includes(rowIndex)) {
      return {
        rowspan: 3,
        colspan: 1,
      };
    } else if (rowIndex === 32) {
      return {
        rowspan: 6,
        colspan: 1,
      };
    } else if (rowIndex === 91) {
      return {
        rowspan: 7,
        colspan: 1,
      };
    } else if (rowMerge5.includes(rowIndex)) {
      return {
        rowspan: 1,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
// 提交
const submit = async () => {
  let param = JSON.parse(JSON.stringify(form.value));
  param?.individualCreditModels.forEach((e, i) => {
    delete e.recordChildren;
    delete e.subject;
  });
  await personalCreditModelSaveOrUpdate(param);
  addRecord(param);
  getDetail();
  ElMessage.success('提交成功！');
};
const getItemId = (name: string): number | string => {
  if (!name) return '';
  return formProcess.value[0]?.recordChildren[0]?.subject?.itemList.find((e) => e.options === name)?.itemId;
};

// 新增判分记录
const addRecord = async (data: Record<string, any>) => {
  let preIds = `1,${Cookies.get('sand-level')},42,68,756,772`; // 1，关卡id，角色（这个页面是风控经理策略），其他看判分点接口
  const rule: Array<Record<string, any>> = [];
  data.firstMode && rule.push(handleId(777, 236, getItemId(data.firstMode), preIds + ',774,777', 1));
  data.secondMode && rule.push(handleId(777, 236, getItemId(data.secondMode), preIds + ',775,777', 1));
  data.thirdMode && rule.push(handleId(777, 236, getItemId(data.thirdMode), preIds + ',776,777', 1));
  data.andThird && rule.push(handleId(778, 236, getItemId(data.andThird), preIds + ',776,778', 1));

  preIds += `,788`;
  form.value.individualCreditModels[0].score &&
    rule.push(
      handleId(
        790,
        238,
        form.value?.individualCreditModels[0]?.subject?.itemList.find((e) => e.options === form.value.individualCreditModels[0].score)?.itemId,
        preIds + ',789,790',
        1,
      ),
    );
  form.value.individualCreditModels.forEach((e, i) => {
    if (i && i !== len.value && e.subject) {
      e.score && rule.push(handleId(e.ruleId, e.subject.subjectId, e?.subject?.itemList?.find((n) => n.options === e.score)?.itemId, `${preIds},${e.stRecordId},${e.ruleId}`, 1));
    }
  });
  await addOperation({
    checkpointId: levelId,
    parentId: preIds,
    lcJudgmentRuleReq: rule,
    projectId,
  });
};
</script>

<style lang="scss" scoped>
@import url(../../../styles/form.scss);
.c-table {
  :deep(.el-input__inner) {
    @apply px-2;
  }
}
</style>
