<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="类型"
                     min-width="100"
                     align="center">
    </el-table-column>
    <el-table-column prop="rule"
                     label="规则"
                     min-width="150">
    </el-table-column>
    <el-table-column label="拒绝标准"
                     min-width="250">
      <template #default="{ row,$index }">
        <div class="flex items-center">
          <template v-if="!$index">
            <span class="whitespace-nowrap">人脸识别匹配度</span>
            <div class="w-[90px] mx-2">
              <el-select v-model="row.symbol">
                <el-option v-for="item in symbols"
                           :key="item"
                           :label="item"
                           :value="item" />
              </el-select>
            </div>
            <div class="w-[90px] ">
              <el-select v-model="row.num">
                <el-option v-for="item in nums"
                           :key="item"
                           :label="item"
                           :value="item" />
              </el-select>
            </div>
            <span class="whitespace-nowrap ml-2">%。</span>
          </template>
          <div v-else-if="$index === 1 || $index === 2 || $index > 18"
               class="w-[90px] mx-2">
            <el-select v-model="row.had">
              <el-option v-for="item in have"
                         :key="item"
                         :label="item"
                         :value="item" />
            </el-select>
          </div>
          <template v-else-if="$index === 3 || $index === 4">
            <span class="whitespace-nowrap">在网期限：</span>
            <div class="w-[90px] ">
              <el-select v-model="row.num">
                <el-option v-for="item in nums"
                           :key="item"
                           :label="item"
                           :value="item" />
              </el-select>
            </div>
            <span class="mx-2">~</span>
            <div class="w-[90px] ">
              <el-select v-model="row.num1">
                <el-option v-for="item in nums"
                           :key="item"
                           :label="item"
                           :value="item" />
              </el-select>
            </div>
            <div class="w-[90px] mx-2">
              <el-select v-model="row.unit">
                <el-option v-for="item in units"
                           :key="item"
                           :label="item"
                           :value="item" />
              </el-select>
            </div>
          </template>
          <template v-else-if="row.stRecordId === 385">
            <span class="whitespace-nowrap">命中：</span>
            <div class="flex-1">
              <el-select v-if="row.recordChildren"
                         v-model="row.select">
                <el-option v-for="item in row?.recordChildren[0]?.subject?.itemList"
                           :key="item"
                           :value="item.options" />
              </el-select>
            </div>
          </template>
          <template v-else-if="$index > 13 && $index < 19">
            <span class="whitespace-nowrap">关联人数</span>
            <div class="w-[90px] mx-2">
              <el-select v-model="row.symbol">
                <el-option v-for="item in symbols"
                           :key="item"
                           :label="item"
                           :value="item" />
              </el-select>
            </div>
            <div class="w-[90px] ">
              <el-select v-model="row.num">
                <el-option v-for="item in nums"
                           :key="item"
                           :label="item"
                           :value="item" />
              </el-select>
            </div>
            <span class="whitespace-nowrap ml-2">人。</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 { accessStrategyAntiFraudStrategyFind, accessStrategyAntiFraudStrategySave } 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 } 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 symbols: Array<string> = ['>=', '<', '>', '==', '<='];
const nums: Array<number> = [2, 3, 4, 7, 10, 30, 60, 85];
const units: Array<string> = ['年', '月', '天'];
const have: Array<string> = ['否', '是'];
// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(155);
  const result = [];
  process.forEach((e, i) => {
    const cur = info.value.find((n) => n.stRecordId === e.id);
    let num = getNum(cur?.ruleOne);
    let symbol = getSymbol(cur?.ruleOne);
    let temp = {
      name: e.name,
      recordChildren: e.recordChildren,
      subjectId: e.subjectId,
      stRecordId: e.id,
      ruleId: e?.recordChildren[0].id,
      rule: e?.recordChildren[0].name,
      symbol: symbol || '>=',
      num: num || 2,
      num1: '',
      had: '否',
      select: cur?.ruleOne || '',
      unit: '',
    };

    result.push(temp);
    // eslint-disable-next-line no-unused-expressions
    e?.recordChildren.forEach((n, i) => {
      if (i) {
        temp = JSON.parse(JSON.stringify(temp));
        temp.ruleId = n.id;
        temp.rule = n.name;
        if (n.id === 388) {
          temp.had = cur?.ruleTwo || '否';
        } else if (n.id === 389) {
          temp.had = cur?.ruleThree || '否';
        } else if (n.id === 406) {
          temp.had = cur?.ruleSix || '否';
        } else if (n.id === 407) {
          temp.had = cur?.ruleSeven || '否';
        } else if (n.id === 408) {
          temp.had = cur?.ruleEight || '否';
        } else if (n.id === 409) {
          temp.had = cur?.ruleNine || '否';
        } else if (n.id === 410) {
          temp.had = cur?.ruleTen || '否';
        } else if (n.id === 411) {
          temp.had = cur?.ruleEleven || '否';
        } else if (n.id === 412) {
          temp.had = cur?.ruleTwelve || '否';
        } else if (n.id === 413) {
          temp.had = cur?.ruleThirteen || '否';
        } else if (n.id === 414) {
          temp.had = cur?.ruleFourteen || '否';
        } else if (e.id === 385) {
          // 人脸反欺诈
          if (n.id === 393) {
            temp.select = cur?.ruleTwo;
          } else if (n.id === 394) {
            temp.select = cur?.ruleThree;
          } else if (n.id === 395) {
            temp.select = cur?.ruleFour;
          } else if (n.id === 396) {
            temp.select = cur?.ruleFive;
          } else if (n.id === 397) {
            temp.select = cur?.ruleSix;
          } else if (n.id === 398) {
            temp.select = cur?.ruleSeven;
          } else if (n.id === 399) {
            temp.select = cur?.ruleEight;
          } else if (n.id === 400) {
            temp.select = cur?.ruleNine;
          }
        } else if (n.id === 390) {
          const arr = cur?.ruleFour?.split('~') || [];
          temp.num = getNum(arr[0]) || '';
          temp.num1 = getNum(arr[1]) || '';
          temp.unit = getChinese(arr[1]) || '';
        } else if (n.id === 391) {
          const arr = cur?.ruleFive?.split('~') || [];
          temp.num = getNum(arr[0]) || '';
          temp.num1 = getNum(arr[1]) || '';
          temp.unit = getChinese(arr[1]) || '';
        } else if (n.id === 401) {
          temp.symbol = getSymbol(cur?.ruleOne) || '>=';
          temp.num = getNum(cur?.ruleOne) || 2;
        } else if (n.id === 402) {
          temp.symbol = getSymbol(cur?.ruleTwo) || '>=';
          temp.num = getNum(cur?.ruleTwo) || 2;
        } else if (n.id === 403) {
          temp.symbol = getSymbol(cur?.ruleThree) || '>=';
          temp.num = getNum(cur?.ruleThree) || 2;
        } else if (n.id === 404) {
          temp.symbol = getSymbol(cur?.ruleFour) || '>=';
          temp.num = getNum(cur?.ruleFour) || 2;
        } else if (n.id === 405) {
          temp.symbol = getSymbol(cur?.ruleFive) || '>=';
          temp.num = getNum(cur?.ruleFive) || 2;
        }
        result.push(temp);
      }
    });
  });
  form.value = result;
};
// 详情
const getDetail = async () => {
  try {
    const { data } = await accessStrategyAntiFraudStrategyFind(levelId, projectId);
    info.value = data;
    getConfig();
  } finally {
  }
};

watch(
  () => route.query,
  () => {
    route.query.id === '155' && 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: 5,
        colspan: 1,
      };
    } else if (rowIndex === 5) {
      return {
        rowspan: 9,
        colspan: 1,
      };
    } else if (rowIndex === 14) {
      return {
        rowspan: 14,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
// 提交
const submit = async () => {
  let param = [
    {
      id: info.value.find((n) => n.stRecordId === 384)?.id,
      stRecordId: 384,
      checkpointId: levelId,
      projectId,
      ruleOne: form.value[0].symbol + form.value[0].num,
      ruleTwo: form.value[1].had,
      ruleThree: form.value[2].had,
      ruleFour: form.value[3].num + '~' + form.value[3].num1 + form.value[3].unit,
      ruleFive: form.value[4].num + '~' + form.value[4].num1 + form.value[4].unit,
    },
    {
      id: info.value.find((n) => n.stRecordId === 385)?.id,
      stRecordId: 385,
      checkpointId: levelId,
      projectId,
      ruleOne: form.value[5].select,
      ruleTwo: form.value[6].select,
      ruleThree: form.value[7].select,
      ruleFour: form.value[8].select,
      ruleFive: form.value[9].select,
      ruleSix: form.value[10].select,
      ruleSeven: form.value[11].select,
      ruleEight: form.value[12].select,
      ruleNine: form.value[13].select,
    },
    {
      id: info.value.find((n) => n.stRecordId === 386)?.id,
      stRecordId: 386,
      checkpointId: levelId,
      projectId,
      ruleOne: form.value[14].symbol + form.value[14].num,
      ruleTwo: form.value[15].symbol + form.value[15].num,
      ruleThree: form.value[16].symbol + form.value[16].num,
      ruleFour: form.value[17].symbol + form.value[17].num,
      ruleFive: form.value[18].symbol + form.value[18].num,
      ruleSix: form.value[19].had,
      ruleSeven: form.value[20].had,
      ruleEight: form.value[21].had,
      ruleNine: form.value[22].had,
      ruleTen: form.value[23].had,
      ruleEleven: form.value[24].had,
      ruleTwelve: form.value[25].had,
      ruleThirteen: form.value[26].had,
      ruleFourteen: form.value[27].had,
    },
  ];
  await accessStrategyAntiFraudStrategySave({ antiFraudStrategyList: param });
  addRecord(param);
  getDetail();
  ElMessage.success('提交成功！');
};
const getName = (str: string): string | number => {
  const result = form.value[5]?.recordChildren[0]?.subject?.itemList?.find((e) => e.options === str);
  return result?.itemId || '';
};
// 新增判分记录
const addRecord = async (data: Record<string, any>) => {
  const preIds = `1,${Cookies.get('sand-level')},42,67,147,155`; // 1，关卡id，角色（这个页面是风控经理策略）
  const rule: Array<Record<string, any>> = [
    handleId(387, 181, data[0].ruleOne, preIds + ',384,387', 5),
    handleId(388, 140, data[0].ruleTwo === '是' ? 345 : 346, preIds + ',384,388', 1),
    handleId(389, 140, data[0].ruleThree === '是' ? 345 : 346, preIds + ',384,389', 1),
    handleId(390, 187, data[0].ruleFour, preIds + ',384,390', 5),
    handleId(391, 187, data[0].ruleFive, preIds + ',384,391', 5),
  ];
  data[1].ruleOne && rule.push(handleId(392, 188, getName(data[1].ruleOne), preIds + ',385,392', 1));
  data[1].ruleTwo && rule.push(handleId(393, 188, getName(data[1].ruleTwo), preIds + ',385,393', 1));
  data[1].ruleThree && rule.push(handleId(394, 188, getName(data[1].ruleThree), preIds + ',385,394', 1));
  data[1].ruleFour && rule.push(handleId(395, 188, getName(data[1].ruleFour), preIds + ',385,395', 1));
  data[1].ruleFive && rule.push(handleId(396, 188, getName(data[1].ruleFive), preIds + ',385,396', 1));
  data[1].ruleSix && rule.push(handleId(397, 188, getName(data[1].ruleSix), preIds + ',385,397', 1));
  data[1].ruleSeven && rule.push(handleId(398, 188, getName(data[1].ruleSeven), preIds + ',385,398', 1));
  data[1].ruleEight && rule.push(handleId(399, 188, getName(data[1].ruleEight), preIds + ',385,399', 1));
  data[1].ruleNine && rule.push(handleId(400, 188, getName(data[1].ruleNine), preIds + ',385,400', 1));

  rule.push(
    handleId(401, 182, data[2].ruleOne, preIds + ',386,401', 5),
    handleId(402, 183, data[2].ruleTwo, preIds + ',386,402', 5),
    handleId(403, 184, data[2].ruleThree, preIds + ',386,403', 5),
    handleId(404, 185, data[2].ruleFour, preIds + ',386,404', 5),
    handleId(405, 186, data[2].ruleFive, preIds + ',386,405', 5),

    handleId(406, 140, data[2].ruleSix === '是' ? 345 : 346, preIds + ',386,406', 1),
    handleId(407, 140, data[2].ruleSeven === '是' ? 345 : 346, preIds + ',386,407', 1),
    handleId(408, 140, data[2].ruleEight === '是' ? 345 : 346, preIds + ',386,408', 1),
    handleId(409, 140, data[2].ruleNine === '是' ? 345 : 346, preIds + ',386,409', 1),
    handleId(410, 140, data[2].ruleTen === '是' ? 345 : 346, preIds + ',386,410', 1),
    handleId(411, 140, data[2].ruleEleven === '是' ? 345 : 346, preIds + ',386,411', 1),
    handleId(412, 140, data[2].ruleTwelve === '是' ? 345 : 346, preIds + ',386,412', 1),
    handleId(413, 140, data[2].ruleThirteen === '是' ? 345 : 346, preIds + ',386,413', 1),
    handleId(414, 140, data[2].ruleFourteen === '是' ? 345 : 346, preIds + ',386,414', 1),
  );
  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>
