<template>
  <!-- 个人利率模型 -->
  <el-form label-width="100px"
           class="form"
           status-icon>
    <el-form-item label="利率模型">
      <el-table class="c-table"
                :data="form.individualInterestRateModels"
                :span-method="span"
                border>
        <el-table-column prop="indexName"
                         label="指标名称"
                         min-width="100"
                         align="center">
          <template #default="{ row, $index }">
            <span :class="{'text-[#006bff]': !$index}">{{ row?.indexName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述"
                         min-width="150">
          <template #default="{ row, $index }">
            <span :class="{'text-[#006bff]': !$index}">{{ row?.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分值"
                         min-width="150">
          <template #default="{ row, $index }">
            <el-select v-if="$index !== 12 && $index !== 13"
                       class="w-full"
                       v-model="row.score">
              <el-option v-for="item in row?.subject?.itemList"
                         :key="item"
                         :value="item.options" />
            </el-select>
            <el-input v-else
                      placeholder="请输入"
                      v-model="row.score"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item :label="formProcess[0]?.name">
      <div class="flex-1">
        <p class="mb-1">{{ formProcess[0]?.recordChildren[0]?.name }}</p>
        <el-select v-model="form.finalFloatingRatioEqual"
                   clearable>
          <el-option v-for="item in formProcess[0]?.recordChildren[0]?.subject?.itemList"
                     :key="item"
                     :value="item.options" />
        </el-select>
        <p class="mt-3 mb-1">{{ formProcess[0]?.recordChildren[1]?.name }}</p>
        <el-select v-model="form.finalFloatingRatioLess"
                   clearable>
          <el-option v-for="item in formProcess[0]?.recordChildren[1]?.subject?.itemList"
                     :key="item"
                     :value="item.options" />
        </el-select>
        <p class="mt-3 mb-1">{{ formProcess[0]?.recordChildren[2]?.name }}</p>
        <el-select v-model="form.finalFloatingRatioGreater"
                   clearable>
          <el-option v-for="item in formProcess[0]?.recordChildren[2]?.subject?.itemList"
                     :key="item"
                     :value="item.options" />
        </el-select>
      </div>
    </el-form-item>

    <el-form-item :label="formProcess[1]?.name">
      <div class="flex-1">
        <p class="mb-1">{{ formProcess[1]?.recordChildren[0]?.name }}</p>
        <el-select v-model="form.finalInterestRateEqual">
          <el-option v-for="item in formProcess[1]?.recordChildren[0]?.subject?.itemList"
                     :key="item"
                     :value="item.options" />
        </el-select>
      </div>
    </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 { personalInterestRateDetails, personalInterestRateSaveOrUpdate } 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,
  finalFloatingRatioEqual: '',
  finalFloatingRatioGreater: '',
  finalFloatingRatioLess: '',
  finalInterestRateEqual: '',
  type: 1,
  individualInterestRateModels: [],
});
const formProcess = ref<Record<string, any>[]>([]);
const info = ref<Record<string, any>[]>([]);
const len = ref<number>(0);
// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(935);
  formProcess.value = process.slice(1);
  const list = process[0]?.recordChildren;
  const result = [];
  list?.forEach((e, i) => {
    let temp = {
      indexName: e.name,
      recordChildren: e.recordChildren || [],
      stRecordId: e.id,
      ruleId: e.recordChildren ? e?.recordChildren[0]?.id : '',
      description: e.recordChildren ? e?.recordChildren[0]?.name : e.remark || '--',
      subject: e.recordChildren ? e?.recordChildren[0]?.subject : e.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);
      }
    });
  });
  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.individualInterestRateModels = result;
  console.log('🚀 ~ file: 935.vue:173 ~ getConfig ~ result:', result);
};
// 详情
const getDetail = async () => {
  try {
    const { data } = await personalInterestRateDetails(levelId, projectId);
    if (data) {
      form.value = data;
      info.value = data.individualInterestRateModels;
    }
    getConfig();
  } finally {
  }
};
onMounted(() => {
  getDetail();
});

interface SpanMethodProps {
  row: Record<string, any>;
  column: TableColumnCtx<Record<string, any>>;
  rowIndex: number;
  columnIndex: number;
}
// 表格合并
const span = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (rowIndex === 1) {
      return {
        rowspan: 5,
        colspan: 1,
      };
    } else if (rowIndex === 6 || rowIndex === 9) {
      return {
        rowspan: 3,
        colspan: 1,
      };
    } else if (!rowIndex || rowIndex === 12 || rowIndex === 13) {
      return {
        rowspan: 1,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};

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>) => {
  const preIds = `1,${Cookies.get('sand-level')},42,68,757,935`; // 1，关卡id，角色（这个页面是风控经理策略），其他看判分点接口
  const rule: Array<Record<string, any>> = [];

  const listIds = preIds + ',937';
  form.value.individualInterestRateModels[0].score && rule.push(handleId(939, 273, 647, listIds + ',939', 1));
  form.value.individualInterestRateModels.forEach((e, i) => {
    if (i && i !== 12 && i !== 13 && e.subject) {
      e.score && rule.push(handleId(e.ruleId, e.subject.subjectId, e?.subject?.itemList?.find((n) => n.options === e.score)?.itemId, `${listIds},${e.stRecordId},${e.ruleId}`, 1));
    }
  });
  form.value.individualInterestRateModels[12].score && rule.push(handleId(954, 306, form.value.individualInterestRateModels[12].score, listIds + ',954', 3));
  form.value.individualInterestRateModels[13].score && rule.push(handleId(955, 307, form.value.individualInterestRateModels[13].score, listIds + ',955', 3));

  data.finalFloatingRatioEqual && rule.push(handleId(1024, 279, getItemId(data.finalFloatingRatioEqual), preIds + ',1023,1024', 1));
  data.finalFloatingRatioLess && rule.push(handleId(1025, 279, getItemId(data.finalFloatingRatioLess), preIds + ',1023,1025', 1));
  data.finalFloatingRatioGreater && rule.push(handleId(1026, 279, getItemId(data.finalFloatingRatioGreater), preIds + ',1023,1026', 1));
  data.finalInterestRateEqual &&
    rule.push(
      handleId(1028, 280, formProcess.value[1]?.recordChildren[0]?.subject?.itemList.find((e) => e.options === data.finalInterestRateEqual)?.itemId, preIds + ',1027,1028', 1),
    );

  await addOperation({
    checkpointId: levelId,
    parentId: preIds,
    lcJudgmentRuleReq: rule,
    projectId,
  });
};
// 提交
const submit = async () => {
  const param = JSON.parse(JSON.stringify(form.value));
  param?.individualInterestRateModels.forEach((e, i) => {
    delete e.recordChildren;
    delete e.subject;
  });
  await personalInterestRateSaveOrUpdate(param);
  addRecord(param);
  getDetail();
  ElMessage.success('提交成功！');
};
</script>

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