<template>
  <!-- 行内 -->
  <el-table class="c-table"
            :data="form"
            :max-height="height"
            :cell-style="{background:'#fff'}"
            :span-method="span"
            border>
    <el-table-column prop="name"
                     label="五级分类"
                     fixed
                     min-width="150"
                     align="center">
    </el-table-column>
    <el-table-column label="未结清是否进黑名单"
                     min-width="170"
                     align="center">
      <template #default="{ row, $index }">
        <span v-if="$index == 4">不存在未结清情况</span>
        <el-checkbox v-else
                     v-model="row.enterBlacklist"></el-checkbox>
      </template>
    </el-table-column>
    <el-table-column label="进入黑名单规则"
                     width="320"
                     align="center">
      <template #default="{ row }">
        <div class="flex items-center">
          <span class="whitespace-nowrap">{{ row?.recordChildren[1]?.recordChildren[0]?.name }}：认定{{row.name}}</span>
          <div class="w-[90px] ">
            <el-select class="mx-2"
                       v-model="row.enterRuleOne">
              <el-option v-for="item in nums"
                         :key="item"
                         :label="item"
                         :value="item" />
            </el-select>
          </div>
          <span class="whitespace-nowrap">天以上进入黑名单。</span>
        </div>
        <div class="flex items-center mt-2">
          <span class="whitespace-nowrap">{{ row?.recordChildren[1]?.recordChildren[1]?.name }}：认定{{row.name}}</span>
          <div class="w-[90px] ">
            <el-select class="mx-2"
                       v-model="row.enterRuleTwo">
              <el-option v-for="item in nums"
                         :key="item"
                         :label="item"
                         :value="item" />
            </el-select>
          </div>
          <span class="whitespace-nowrap">天以上进入黑名单。</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="结清是否能出黑名单"
                     min-width="170"
                     align="center">
      <template #default="{ row }">
        <el-checkbox v-model="row.outBlacklist"></el-checkbox>
      </template>
    </el-table-column>
    <el-table-column label="结清出黑名单规则"
                     width="380"
                     align="center">
      <template #default="{ row }">
        <div class="flex items-center">
          <span class="whitespace-nowrap">{{ row?.recordChildren[1]?.recordChildren[0]?.name }}：结清后，</span>
          <div class="w-[90px] ">
            <el-select class="mx-2"
                       v-model="row.num">
              <el-option v-for="item in nums"
                         :key="item"
                         :label="item"
                         :value="item" />
            </el-select>
          </div>
          <div class="w-[90px] ">
            <el-select class="mr-2"
                       v-model="row.symbol">
              <el-option v-for="item in units"
                         :key="item"
                         :label="item"
                         :value="item" />
            </el-select>
          </div>
          <span class="whitespace-nowrap">后出黑名单。</span>
        </div>
        <div class="flex items-center mt-2">
          <span class="whitespace-nowrap">{{ row?.recordChildren[1]?.recordChildren[1]?.name }}：结清后，</span>
          <div class="w-[90px] ">
            <el-select class="mx-2"
                       v-model="row.num1">
              <el-option v-for="item in nums"
                         :key="item"
                         :label="item"
                         :value="item" />
            </el-select>
          </div>
          <div class="w-[90px] ">
            <el-select class="mr-2"
                       v-model="row.symbol1">
              <el-option v-for="item in units"
                         :key="item"
                         :label="item"
                         :value="item" />
            </el-select>
          </div>
          <span class="whitespace-nowrap">后出黑名单。</span>
        </div>
      </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, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { accessStrategyInlineBlacklistFind, accessStrategyInlineBlacklistSave } from '@/api/model';
import { getProcessInformationBasedOnRoles, addOperation } from '@/api/judgment';
import type { TableColumnCtx } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { handleId, getNum, getChinese } 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>[]>([]);
const info = ref<Record<string, any>[]>([]);
const height = window.innerHeight - 230;
const nums: Array<number> = [1, 3, 5, 10, 20, 30, 40];
const units: Array<string> = ['年', '个月', '天'];
// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(153);
  const result = [];
  process.map((e) => {
    const cur = info.value.find((n) => n.stRecordId === e.id);
    let temp = {
      checkpointId: levelId,
      projectId,
      name: e.name,
      recordChildren: e.recordChildren,
      enterBlacklist: !!cur?.enterBlacklist,
      outBlacklist: !!cur?.outBlacklist,
      enterRuleOne: cur?.enterRuleOne || 1,
      enterRuleTwo: cur?.enterRuleTwo || 1,
      num: getNum(cur?.outRuleOne) || 1,
      num1: getNum(cur?.outRuleTwo) || 1,
      symbol: getChinese(cur?.outRuleOne) || '年',
      symbol1: getChinese(cur?.outRuleTwo) || '年',
      stRecordId: e.id,
    };
    result.push(temp);
  });
  form.value = result;
};
// 详情
const getDetail = async () => {
  try {
    const { data } = await accessStrategyInlineBlacklistFind(levelId, projectId);
    info.value = data;
    getConfig();
  } finally {
  }
};

watch(
  () => route.query,
  () => {
    getDetail();
  },
  {
    immediate: true,
  },
);

interface SpanMethodProps {
  row: Record<string, any>;
  column: TableColumnCtx<Record<string, any>>;
  rowIndex: number;
  columnIndex: number;
}
// 表格合并
const span = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  if (rowIndex === 4) {
    if (columnIndex === 1) {
      return {
        rowspan: 1,
        colspan: 4,
      };
    } else if (columnIndex > 1) {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
// 提交
const submit = async () => {
  let param = JSON.parse(JSON.stringify(form.value));
  param.map((e, i) => {
    if (info.value.length) e.id = info.value.find((n) => n.stRecordId === e.stRecordId)?.id;
    e.enterBlacklist = +e.enterBlacklist;
    e.outBlacklist = +e.outBlacklist;
    e.outRuleOne = e.num + e.symbol;
    e.outRuleTwo = e.num1 + e.symbol1;
  });
  param.map((e) => {
    delete e.recordChildren;
  });
  await accessStrategyInlineBlacklistSave({ inlineBlacklistList: param });
  addRecord(param);
  getDetail();
  ElMessage.success('提交成功！');
};
// 新增判分记录
const addRecord = async (data: Record<string, any>) => {
  const preIds = `1,${Cookies.get('sand-level')},42,67,147,153`; // 1，关卡id，角色（这个页面是风控经理策略）
  const rule: Array<Record<string, any>> = [];

  data.map((e) => {
    e.enterBlacklist && rule.push(handleId(363, '', '', preIds + ',' + e.stRecordId + ',363', ''));
    rule.push(handleId(367, 166, e.enterRuleOne, preIds + ',' + e.stRecordId + ',367', 5), handleId(368, 167, e.enterRuleTwo, preIds + ',' + e.stRecordId + ',368', 5));
    e.outBlacklist && rule.push(handleId(365, '', '', preIds + ',' + e.stRecordId + ',365', ''));
    rule.push(handleId(367, 166, e.outRuleOne, preIds + ',' + e.stRecordId + ',367', 5), handleId(368, 167, e.outRuleTwo, preIds + ',' + e.stRecordId + ',368', 5));
  });

  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>
