<template>
  <!-- 商采 -->
  <el-table class="c-table"
            :data="form"
            max-height="calc(100vh - 230px)"
            :cell-style="{background:'#fff'}"
            :span-method="span"
            border>
    <el-table-column prop="name"
                     label="数据源"
                     min-width="100"
                     align="center">
    </el-table-column>
    <el-table-column prop="rule"
                     label="规则"
                     min-width="150">
    </el-table-column>
    <el-table-column label="进黑名单条件"
                     width="540">
      <template #default="{ row,$index }">
        <div v-if="$index < 4"
             class="flex items-center">
          <span class="whitespace-nowrap">{{ row.rule }}</span>
          <div class="w-[95px] ">
            <el-select class="mx-2"
                       clearable
                       v-model="row.symbol">
              <el-option v-for="item in symbols"
                         :key="item"
                         :label="item.name"
                         :value="item.name" />
            </el-select>
          </div>
          <el-input class="w-[80px]"
                    placeholder="请输入"
                    v-model="row.num"></el-input>
          <span class="ml-2 whitespace-nowrap">。</span>
        </div>
        <template v-else-if="$index > 3 && $index < 14 || $index === 16 || $index === 17 || $index === 19 || $index === 28">命中{{ row.rule }}</template>
        <!-- 腾讯 -->
        <div v-else-if="$index === 14"
             class="flex items-center">
          <span v-if="row.recordChildren"
                class="whitespace-nowrap">{{ row?.recordChildren[0]?.recordChildren[0]?.name }}</span>
          <div class="w-[95px] ">
            <el-select class="mx-2"
                       clearable
                       v-model="row.symbol">
              <el-option v-for="item in symbols"
                         :key="item"
                         :label="item.name"
                         :value="item.name" />
            </el-select>
          </div>
          <el-input class="w-[80px]"
                    placeholder="请输入"
                    v-model="row.num"></el-input>
          <span class="ml-2 whitespace-nowrap">，且</span>
          <div class="w-[120px] ">
            <el-select class="mx-2"
                       clearable
                       v-model="row.had">
              <el-option v-for="item in house"
                         :key="item"
                         :label="item.name"
                         :value="item.name" />
            </el-select>
          </div>
          <span class="ml-2 whitespace-nowrap">。</span>
        </div>
        <div v-else-if="$index === 15"
             class="flex items-center">
          <el-input class="w-[80px]"
                    placeholder="请输入"
                    v-model="row.num"></el-input>
          <div class="w-[95px] ">
            <el-select class="mx-2"
                       clearable
                       v-model="row.symbol">
              <el-option v-for="item in units"
                         :key="item"
                         :label="item.name"
                         :value="item.name" />
            </el-select>
          </div>
          <span class="ml-2 whitespace-nowrap">内申请次数</span>
          <div class="w-[95px] ">
            <el-select class="mx-2"
                       clearable
                       v-model="row.symbol1">
              <el-option v-for="item in symbols"
                         :key="item"
                         :label="item.name"
                         :value="item.name" />
            </el-select>
          </div>
          <el-input class="w-[80px]"
                    placeholder="请输入"
                    v-model="row.num1"></el-input>
          <span class="ml-2 whitespace-nowrap">，且</span>
          <div class="w-[120px] ">
            <el-select class="mx-2"
                       clearable
                       v-model="row.had">
              <el-option v-for="item in house"
                         :key="item"
                         :label="item.name"
                         :value="item.name" />
            </el-select>
          </div>
          <span class="ml-2 whitespace-nowrap">。</span>
        </div>
        <div v-else-if="$index === 18"
             class="w-[95px] ">
          <el-select v-if="row.recordChildren"
                     clearable
                     v-model="row.symbol">
            <el-option v-for="item in row?.recordChildren[0]?.subject?.itemList"
                       :key="item"
                       :label="item.options"
                       :value="item.options" />
          </el-select>
        </div>
        <div v-else-if="$index > 19 && $index < 28"
             class="flex items-center">
          <el-input class="w-[80px]"
                    placeholder="请输入"
                    v-model="row.num"></el-input>
          <div class="w-[95px] ">
            <el-select class="mx-2"
                       clearable
                       v-model="row.symbol">
              <el-option v-for="item in units"
                         :key="item"
                         :label="item.name"
                         :value="item.name" />
            </el-select>
          </div>
          <span class="ml-2 whitespace-nowrap">{{tdNames[row.ruleId]}}</span>
          <template v-if="row.ruleId === 350">
            <div class="w-[95px] ">
              <el-select class="mx-2"
                         clearable
                         v-model="row.symbol1">
                <el-option v-for="item in symbols"
                           :key="item"
                           :label="item.name"
                           :value="item.name" />
              </el-select>
            </div>
            <el-input class="w-[80px]"
                      placeholder="请输入"
                      v-model="row.num1"></el-input>
            <span class="ml-2 whitespace-nowrap">。</span>
          </template>
        </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, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { accessStrategyBusinessBlacklistFind, accessStrategyBusinessBlacklistSave } from '@/api/model';
import { getProcessInformationBasedOnRoles, addOperation } from '@/api/judgment';
import type { TableColumnCtx } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { handleId, getNum, getSymbol, getChinese, getIds } 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 spanRows = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27];
const symbols: Array<Record<string, any>> = [
  {
    name: '>=',
  },
  {
    name: '<',
  },
  {
    name: '>',
  },
  {
    name: '==',
  },
  {
    name: '<=',
  },
];
const house: Array<Record<string, any>> = [
  {
    // id: 353,
    name: '有商品房',
  },
  {
    // id: 354,
    name: '无商品房',
  },
];
const units: Array<Record<string, any>> = [
  {
    name: '年',
  },
  {
    name: '月',
  },
  {
    name: '天',
  },
];
const tdNames: Record<string, any> = {
  344: '内身份证关联多个申请信息。',
  345: '内申请信息关联多个身份证。',
  346: '内申请人身份证作为联系人身份证出现的次数过多。',
  347: '内设备或身份证或手机号申请次数过多。',
  348: '内申请人在多个平台申请借款。',
  349: '内申请人在多个平台申请借款。',
  350: '内身份证或手机号申请次数',
  351: '内同一个设备或手机号申请被拒次数过多。',
};
// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(152);
  const result = [];
  process.map((e, i) => {
    const cur = info.value.find((n) => n.stRecordId === e.id);
    let num = getNum(cur?.ruleOne);
    let symbol = getSymbol(cur?.ruleOne);
    let had = getChinese(cur?.ruleOne);
    let temp = {
      ...getIds(),
      name: e.name,
      recordChildren: e.recordChildren,
      isRule: 0,
      subjectId: e.subjectId,
      stRecordId: e.id,
      ruleId: e?.recordChildren[0].id,
      rule: e?.recordChildren[0].name,
      symbol: e.id === 322 && cur ? cur?.ruleOne : (e.id === 318 || e.id === 320) && cur ? symbol : !i || i === 2 ? '' : e.id === 322 ? '' : '',
      symbol1: '>=',
      num,
      num1: '',
      had,
    };

    result.push(temp);
    e?.recordChildren.map((n, i) => {
      if (i) {
        temp = JSON.parse(JSON.stringify(temp));
        temp.ruleId = n.id;
        temp.rule = n.name;
        temp.isRule = 1;
        // 新颜
        if (e.id === 318) {
          if (n.id === 325) {
            temp.symbol = getSymbol(cur?.ruleTwo) ?? '>=';
            temp.num = getNum(cur?.ruleTwo);
          } else if (n.id === 326) {
            temp.symbol = getSymbol(cur?.ruleThree) ?? '>=';
            temp.num = getNum(cur?.ruleThree);
          } else if (n.id === 327) {
            temp.symbol = getSymbol(cur?.ruleFour) ?? '>=';
            temp.num = getNum(cur?.ruleFour);
          }
        }
        // 腾讯行业风险
        if (n.id === 339) {
          temp.num = getNum(cur?.ruleTwo);
          const unit = cur?.ruleTwo.match(/[年月日]+/g);
          temp.symbol = unit ? unit[0] : '';

          temp.symbol1 = getSymbol(cur?.ruleTwo) ?? '>=';
          const arr = cur?.ruleTwo?.split(',') ?? [];
          temp.num1 = getNum(arr[1]);

          temp.had = getChinese(arr[2]);
        }
        if (e.id === 322) temp.symbol = '';
        // 腾讯行业风险
        if (n.id === 342) {
          temp.symbol = cur?.ruleOne;
        } else if (n.id === 344) {
          temp.num = getNum(cur?.ruleTwo);
          temp.symbol = getChinese(cur?.ruleTwo);
        } else if (n.id === 345) {
          temp.num = getNum(cur?.ruleThree);
          temp.symbol = getChinese(cur?.ruleThree);
        } else if (n.id === 346) {
          temp.num = getNum(cur?.ruleFour);
          temp.symbol = getChinese(cur?.ruleFour);
        } else if (n.id === 347) {
          temp.num = getNum(cur?.ruleFive);
          temp.symbol = getChinese(cur?.ruleFive);
        } else if (n.id === 348) {
          temp.num = getNum(cur?.ruleSix);
          temp.symbol = getChinese(cur?.ruleSix);
        } else if (n.id === 349) {
          temp.num = getNum(cur?.ruleSeven);
          temp.symbol = getChinese(cur?.ruleSeven);
        } else if (n.id === 350) {
          const arr = cur?.ruleEight?.split(',') ?? [];
          temp.num = getNum(arr[0]);
          temp.symbol = getChinese(cur?.ruleEight);
          temp.symbol1 = getSymbol(cur?.ruleEight);
          temp.num1 = getNum(arr[1]);
        } else if (n.id === 351) {
          temp.num = getNum(cur?.ruleNine);
          temp.symbol = getChinese(cur?.ruleNine);
        }
        result.push(temp);
      }
    });
  });
  form.value = result;
};
// 详情
const getDetail = async () => {
  try {
    const { data } = await accessStrategyBusinessBlacklistFind();
    info.value = data;
    getConfig();
  } finally {
  }
};

watch(
  () => route.query,
  () => {
    route.query.id === '152' && 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 (columnIndex === 0) {
    if (rowIndex === 0) {
      return {
        rowspan: 4,
        colspan: 1,
      };
    } else if (rowIndex === 4) {
      return {
        rowspan: 10,
        colspan: 1,
      };
    } else if (rowIndex === 14 || rowIndex === 16) {
      return {
        rowspan: 2,
        colspan: 1,
      };
    } else if (rowIndex === 18) {
      return {
        rowspan: 10,
        colspan: 1,
      };
    } else if (spanRows.includes(rowIndex)) {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
// 提交
const submit = async () => {
  let param = [
    {
      id: info.value.find((n) => n.stRecordId === 318)?.id,
      stRecordId: 318,
      ...getIds(),
      ruleOne: form.value[0].symbol + form.value[0].num,
      ruleTwo: form.value[1].symbol + form.value[1].num,
      ruleThree: form.value[2].symbol + form.value[2].num,
      ruleFour: form.value[3].symbol + form.value[3].num,
    },
    {
      id: info.value.find((n) => n.stRecordId === 320)?.id,
      stRecordId: 320,
      ...getIds(),
      ruleOne: form.value[14].symbol + form.value[14].num + ',' + form.value[14].had,
      ruleTwo: form.value[15].num + form.value[15].symbol + ',' + form.value[15].symbol1 + form.value[15].num1 + ',' + form.value[15].had,
    },
    {
      id: info.value.find((n) => n.stRecordId === 322)?.id,
      stRecordId: 322,
      ...getIds(),
      ruleOne: form.value[18].symbol,
      ruleTwo: form.value[20].num + form.value[20].symbol,
      ruleThree: form.value[21].num + form.value[21].symbol,
      ruleFour: form.value[22].num + form.value[22].symbol,
      ruleFive: form.value[23].num + form.value[23].symbol,
      ruleSix: form.value[24].num + form.value[24].symbol,
      ruleSeven: form.value[25].num + form.value[25].symbol,
      ruleEight: form.value[26].num + form.value[26].symbol + ',' + form.value[26].symbol1 + form.value[26].num1,
      ruleNine: form.value[27].num + form.value[27].symbol,
    },
  ];
  await accessStrategyBusinessBlacklistSave({ businessBlacklistList: param });
  addRecord(param);
  getDetail();
  ElMessage.success('提交成功！');
};
// 新增判分记录
const addRecord = async (data: Record<string, any>) => {
  const preIds = `1,${Cookies.get('sand-level')},42,67,147,152`; // 1，关卡id，角色（这个页面是风控经理策略）
  const rule = [];
  data[0].ruleOne && rule.push(handleId(324, 150, data[0].ruleOne, preIds + ',318,324', 5));
  data[0].ruleTwo && rule.push(handleId(325, 151, data[0].ruleTwo, preIds + ',318,325', 5));
  data[0].ruleThree && rule.push(handleId(326, 152, data[0].ruleThree, preIds + ',318,326', 5));
  data[0].ruleFour && rule.push(handleId(327, 153, data[0].ruleFour, preIds + ',318,327', 5));

  const line14 = form.value[14].symbol + form.value[14].num;
  line14 && rule.push(handleId(353, 154, line14, preIds + ',320,338,353', 5));

  form.value[14].had && rule.push(handleId(354, 155, form.value[14].had === '有商品房' ? 353 : 354, preIds + ',320,338,354', 1));

  const line15 = form.value[15].num + form.value[15].symbol;
  line15 && rule.push(handleId(355, 156, line15, preIds + ',320,339,355', 5));

  const line151 = form.value[15].symbol1 + form.value[15].num1;
  line151 && rule.push(handleId(356, 157, line151, preIds + ',320,339,356', 5));

  form.value[15].had && rule.push(handleId(357, 155, form.value[15].had === '有商品房' ? 353 : 354, preIds + ',320,339,357', 1));
  data[2].ruleOne && rule.push(handleId(342, 158, data[2].ruleOne === '拒绝' ? 355 : 356, preIds + ',322,342', 1));

  data[2].ruleTwo && rule.push(handleId(344, 159, data[2].ruleTwo, preIds + ',322,344', 5));
  data[2].ruleThree && rule.push(handleId(345, 160, data[2].ruleThree, preIds + ',322,345', 5));
  data[2].ruleFour && rule.push(handleId(346, 161, data[2].ruleFour, preIds + ',322,346', 5));
  data[2].ruleFive && rule.push(handleId(347, 162, data[2].ruleFive, preIds + ',322,347', 5));
  data[2].ruleSix && rule.push(handleId(348, 163, data[2].ruleSix, preIds + ',322,348', 5));
  data[2].ruleSeven && rule.push(handleId(349, 164, data[2].ruleSeven, preIds + ',322,349', 5));

  const line26 = form.value[26].num + form.value[26].symbol;
  line26 && rule.push(handleId(355, 156, line26, preIds + ',322,350,355', 5));

  const line261 = form.value[26].symbol1 + form.value[26].num1;
  line261 && rule.push(handleId(356, 157, line261, preIds + ',322,350,356', 5));

  data[2].ruleNine && rule.push(handleId(351, 165, data[2].ruleNine, preIds + ',322,351', 5));

  await addOperation({
    ...getIds(),
    parentId: preIds,
    lcJudgmentRuleReq: rule,
  });
};
</script>

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