<script setup lang="tsx">
import { reactive, ref, unref } from 'vue';
import { getCsckDataCheckResultListApi, csckDataRetrievalApi, exportExcelApi, checkAllRuleApi, batchCheckRuleApi, exportAloneExcelApi } from '@/api/csck/CsckDataCheckResult';
import { TableData } from '@/api/csck/CsckDataCheckResult/types';
import { useTable } from '@/hooks/web/useTable';
import { useI18n } from '@/hooks/web/useI18n';
import { Table, TableColumn } from '@/components/Table';
import { ElButton, ElLink, ElMessage, ElDrawer } from 'element-plus';
import { Search } from '@/components/Search';
import { FormSchema } from '@/components/Form';
import { ContentWrap } from '@/components/ContentWrap';
import AllCheck from './components/AllCheck.vue';
import Detail from './components/Detail.vue';
import Comments from './components/Comments.vue';
import { getOrganTree } from '@/api/common';
import { Dialog } from '@/components/Dialog';
import { getWidth } from '@/utils';
import { getDictOneApi } from '@/api/common';
import { CHECK_RESULT_DICT_LIST, SYSTEM_GROUP_DICT_LIST } from './constants';
import { getDateByPrevMonth } from '@/utils/dateUtil';
import { getLoginNameByUserInfo, getLoginOrganCodeByUserInfo } from '@/utils/auth';
import { useRoute } from 'vue-router';
import { useValidator } from '@/hooks/web/useValidator';
import { queryCsckWorkFlowApi,queryCsckWorkFlowBatchApi } from '@/api/csck/CsckWorkFlow';
import { exportCommentsExcelByOrganApi, saveCsckCommentsApi } from '@/api/csck/CsckDataCheckResultComment';
import TABLE_ID_CONST from '@/constants/table/table-id';

const TABLE_ID = TABLE_ID_CONST.BUSINESS.OA.CSCK_DATA_CHECK_RESULT;
defineOptions({
  name: 'Datacheckresult',
});

const { required } = useValidator();

const date = getDateByPrevMonth();
const { t } = useI18n();

const { params } = useRoute();

const systemGroup = params?.id?.includes(':id') ? '' : (params.id as string);

const dataDate = params?.date?.includes(':date') ? '' : (params.date as string);

const organCode = params?.organCode?.includes(':organCode') ? '' : (params.organCode as string);

// 获取当前用户机构号
const loginOrganCode = getLoginOrganCodeByUserInfo();
const session_loginName = getLoginNameByUserInfo();
// 使用正则表达式将数字按千位分组
const { tableRegister, tableState, tableMethods } = useTable({
  fetchInitParamsApi: async () => {
    searchParams.value = {
      dataDate: dataDate ? dataDate : date,
      orgCode: organCode ? [organCode] : [loginOrganCode],
      systemGroupCode: systemGroup,
    };
  },
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState;
    const res = await getCsckDataCheckResultListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
    });
    if (searchParams.value.systemGroupCode) {
      if (searchParams.value.systemGroupCode == 'EAST-1104') {
        setColumn([{ field: 'leftValue', path: 'label', value: '1104(左值)' }, { field: 'rightValue', path: 'label', value: 'EAST(右值)' }])
      }
      if (searchParams.value.systemGroupCode === 'EAST-CQCS') {
        setColumn([{ field: 'leftValue', path: 'label', value: '客户风险(左值)' }, { field: 'rightValue', path: 'label', value: 'EAST(右值)' }])
      }
      if (searchParams.value.systemGroupCode === 'PBOC-PBOCD') {
        setColumn([{ field: 'leftValue', path: 'label', value: '大集中(左值)' }, { field: 'rightValue', path: 'label', value: '金融基础数据(右值)' }])
      }
      if (searchParams.value.systemGroupCode === 'PBOC-1104') {
        setColumn([{ field: 'leftValue', path: 'label', value: '大集中(左值)' }, { field: 'rightValue', path: 'label', value: '1104(右值)' }])
      }
      if (searchParams.value.systemGroupCode === 'PBOC-DIIS') {
        setColumn([{ field: 'leftValue', path: 'label', value: '大集中(左值)' }, { field: 'rightValue', path: 'label', value: '存保系统(右值)' }])
      }
      if (searchParams.value.systemGroupCode === 'PBOCD-DIIS') {
        setColumn([{ field: 'leftValue', path: 'label', value: '金融基础数据(左值)' }, { field: 'rightValue', path: 'label', value: '存保系统(右值)' }])
      }
      if (searchParams.value.systemGroupCode === '1104-CQCS') {
        setColumn([{ field: 'leftValue', path: 'label', value: '1104(左值)' }, { field: 'rightValue', path: 'label', value: '客户风险(右值)' }])
      }
    }
    return {
      list: res.body.list,
      total: res.body.total,
    };
  },
  // immediate: true,
  // fetchDelApi: async () => {
  //   const res = await delCsckDataCheckImportListApi(unref(ids));
  //   return !!res;
  // },
});

const { loading, dataList, total, currentPage, pageSize } = tableState;
const { getList, refresh, setColumn } = tableMethods;
const createUser = getLoginNameByUserInfo();
const tableColumns = reactive<TableColumn[]>(
  [
    {
      field: 'selection',
      type: 'selection',
      fixed: true,
    },
    {
      field: 'dataDate',
      label: '数据日期',
    },
    {
      field: 'orgCode',
      label: '机构号'
    },
    {
      field: 'orgName',
      label: '机构名称',
      width: "250"

    },
    {
      field: 'ruleCode',
      label: '规则编码',
      formatter: (row: Recordable, __: TableColumn) => {
        return row.systemGroupCode+'-'+row.ruleCode;
      },
      sortable:true
    },
    {
      field: 'checkRuleName',
      label: '校验规则名称',
      showHeader: false,
      width: "250"
    },
    {
      field: 'leftValue',
      label: '左值',
      align:'right'
    },
    {
      field: 'rightValue',
      label: '右值',
      align:'right'
    },
    {
      field: 'diffValue',
      label: '差值',
      align:'right',
      hidden:true
    },
    {
      field: 'faultTolerance',
      label: '容差范围',
    },
    {
      field: 'checkResult',
      label: '校验结果'
    },
    {
      field: 'action',
      label: t('tableDemo.action'),
      width: 280,
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElLink type="primary" underline={false} onClick={() => exportAloneExcel(data.row)}>
                导出
              </ElLink>
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
                详情
              </ElLink>
              <ElLink type="primary" underline={false} onClick={() => comments(data.row)}>
                情况说明
              </ElLink>
            </>
          );
        },
      },
      hidden: false,
    },
    {
      field: 'sourceRuleDesc',
      label: '左侧规则描述',
    },
    {
      field: 'targetRuleDesc',
      label: '右侧规则描述',
    },
    {
      field: 'riskLevel',
      label: '风险等级',
      optionApi: async () => {
        const res = await getDictOneApi({
          paramName: 'RiskType_param',
          systemCode: 'system',
        });
        return res;
      },
      hidden: false,
    },
    {
      field: 'isEnforcement',
      label: '是否法定校验',
      hidden: false,
    },
    {
      field: 'attentionDegree',
      label: '官方关注度',
      optionApi: async () => {
        const res = await getDictOneApi({
          paramName: 'AttentType_param',
          systemCode: 'system',
        });
        return res;
      },
      hidden: false,
    },
    {
      field: 'ruleMakingOrgan',
      label: '规则编制机构',
      hidden: false,
    },
    {
      field: 'checkVersion',
      label: '校验规则版本',
    }
  ].map(item => ({ minWidth: item.label ? getWidth(item.label) : 120, ...item }) as TableColumn),
);

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'orgCode',
    label: '机构',
    componentProps: {
      checkStrictly: true,
      nodeKey: 'id',
      props: { children: 'childs', label: 'nodeName' },
      filterable: true,
      multiple: true,
      collapseTags: true,
      showCheckbox: true,
      // style: { minWidth: '300px' },
      style: 'width: 100%',
      checkOnClickNode: true,
    },
    component: 'TreeSelect',
    optionApi: async () => {
      const res = await getOrganTree({
        treeid: '1',
        systemCode: 'portal',
        loginOrganCode,
      });
      return res.body.result;
    },
    value: organCode ? [organCode] : [loginOrganCode],
    formItemProps: {
      rules: [required()],
    },
  },
  {
    field: 'dataDate',
    label: '数据日期',
    componentProps: {
      type: 'date',
      valueFormat: 'YYYYMMDD',
    },
    component: 'DatePicker',
    value: dataDate ? dataDate : date,
    formItemProps: {
      rules: [required()],
    },
  },
  {
    field: 'riskLevel',
    label: '风险等级',
    componentProps: {},
    component: 'Select',
    optionApi: async () => {
      const res = await getDictOneApi({
        paramName: 'RiskType_param',
        systemCode: 'system',
      });
      return res;
    },
    hidden: true,
  },
  {
    field: 'checkResult',
    label: '校验结果',
    componentProps: {
      options: CHECK_RESULT_DICT_LIST,
    },
    component: 'Select',
    value: '0',
  },
  {
    field: 'ruleDesc',
    label: '规则描述',
    componentProps: {},
    component: 'Input',
  },
  {
    field: 'ruleCode',
    label: '规则编码',
    component: 'InputRange',
    formItemProps: {
      rules: [
        {
          validator: (_, val, callback) => {
            if (val) {
              if ((val[0] && val[0].length !== 5) || (val[1] && val[1].length !== 5)) callback(new Error('请输入5位规则编码'));
            }
            callback();
          },
        },
      ],
    },
  },
  {
    field: 'systemGroupCode',
    label: '系统组',
    component: 'Select',
    componentProps: {
      options: SYSTEM_GROUP_DICT_LIST,
    },
    value: systemGroup,
    formItemProps: {
      rules: [required()],
    },
  },
]);

const searchParams = ref<Partial<any>>({});
const setSearchParams = async (data: any) => {
  searchParams.value = data;
  await getList();
  if (total.value === 0) {
    disabled.value = true;
    return;
  }
  const res = await queryCsckWorkFlowApi(data);
  if (res.body?.result > 0) {
    disabled.value = true;
    ElMessage.warning('任务已经存在,不能执行数据调取和批量校验功能！');
  } else {
    disabled.value = false;
  }
};

const dialogVisible = ref(false);

const CommentsDialogVisible = ref(false);


const dialogTitle = ref('');

const currentRow = ref();
const actionType = ref('');

const checkAllRef = ref<ComponentRef<typeof AllCheck>>();

const commentsRef = ref<ComponentRef<typeof Comments>>();

/**单行查询**/
const action = async (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'tableDemo.edit' : 'tableDemo.detail');
  actionType.value = type;
  currentRow.value = row;
  dialogVisible.value = true;
};

/**情况说明**/
const comments = async (row: TableData) => {
  currentRow.value = row;
  CommentsDialogVisible.value = true;
};

/** 单行导出 **/
const exportAloneExcel = async (row: TableData) => {
  const { pkid, dataDate, orgCode, checkRuleName,ruleCode,systemGroupCode } = row;
  exportAloneExcelApi({
    pkid: pkid,
    DATA_DATE: dataDate,
    ORGAN_ID: orgCode,
    fileName: systemGroupCode+'-'+ruleCode
  });
};

const saveLoading = ref(false);


const isSubmitting = ref(false);
const isCheckSubmitting = ref(false);
const isDrillSubmitting = ref(false);


/** 保存说明 */
const saveComments = async () => {
  const write = unref(commentsRef);
  const formData = await write?.submit();
  if (formData) {
    saveLoading.value = true;
    const checkRes = await saveCsckCommentsApi({
      organCode: formData.organCode,
      dataDate: formData.dataDate,
      pkid: formData.pkid,
      grade: formData.grade,
      comment: formData.comment,
    })
      .catch(() => {
        saveLoading.value = false;
      })
      .finally(() => {
        saveLoading.value = false;
      });
    if (checkRes) {
      if (+checkRes.head.status === 500) {
        ElMessage.warning(checkRes.head.msg || '保存失败');
      } else {
        write?.getList();
        write?.resetField();
        CommentsDialogVisible.value = false;
        ElMessage.success('保存成功!');
      }
    }
  }
};


/** 全部校验 */
const handleCheckAll = async () => {
  const write = unref(checkAllRef);
  const formData = await write?.submit();
  if (formData) {
    saveLoading.value = false;
    isSubmitting.value=true;
    let res = await queryCsckWorkFlowApi(formData);
    if (res.body?.result.count > 0) {
      ElMessage.warning('系统组已经提交,不能再次进行【全部校验】！');
      dialogAllCheck.value = false;
      isSubmitting.value=false;
      currentPage.value = 1;
      getList();
    }else{
    const checkRes = await checkAllRuleApi({ orgCodes: formData.organCode, dataDate: formData.dataDate, createUser: createUser, systemGroupCode: formData.systemGroupCode })
      .catch(() => {
        saveLoading.value = false;
      })
      .finally(() => {
        saveLoading.value = false;
      });
    if (checkRes) {
      if (+checkRes.head.status === 500) {
        ElMessage.warning(checkRes.head.msg || '全部校验失败');
      } else {
        ElMessage.success('全部校验任务排队成功,请到【作业监控】菜单查看全部校验执行情况!');
        isSubmitting.value=false;
        dialogAllCheck.value = false;
        currentPage.value = 1;
        getList();
      }
    }
  }
}
};
const disabled = ref(true);
const multipleSelection = ref<TableData[]>([]);

const onSelectionChange = (selection: TableData[]) => {
  // disabled.value = selection.length === 0;
  multipleSelection.value = selection;
};

/** 导出Excel */
const exportExcel = async () => {
  const data = { ...unref(searchParams), fileName: '检验結果监控', loginOrganCode: unref(loginOrganCode) };
  exportExcelApi(data);
};

/** 按机构导出情况说明Excel */
const exportCommentsExcel = async () => {
  const data = { ...unref(searchParams), fileName: '按机构导出情况说明', loginOrganCode: unref(loginOrganCode) };
  exportCommentsExcelByOrganApi(data);
};

/**数据调取 */
const dataCount = async () => {
  isDrillSubmitting.value=true;
  let res = await queryCsckWorkFlowBatchApi({dbList: multipleSelection.value.map(item => ({ pkid: item.pkid, orgCode: item.orgCode, dataDate: item.dataDate,systemGroupCode:item.sourceSystemCode+'-'+item.targetSystemCode }))});
  if (res.body?.result.count > 0) {
    ElMessage.warning('系统组已经提交,不能再次进行【数据调取】');
      dialogAllCheck.value = false;
      isDrillSubmitting.value=false;
      currentPage.value = 1;
      getList();
  }
else{
  const res = await csckDataRetrievalApi({
    dbList: multipleSelection.value.map(item => ({ pkid: item.pkid, orgCode: item.orgCode, dataDate: item.dataDate,systemGroupName:item.systemGroupName })),
    createUser: createUser,
  });
  if (res) {
    if (+res.head.status === 500) {
      ElMessage.warning(res.head.msg || '数据调取失败');
    } else {
      ElMessage.success('数据调取任务排队成功,请到【作业监控】菜单查看数据调取执行情况!');
      isDrillSubmitting.value=false;
      getList();
    }
  }
}
};
/** 全部校验 */
const dialogAllCheck = ref(false);
const allCheck = async () => {
  dialogAllCheck.value = true;
};

/** 批量校验 */
const batchCheck = async () => {
  isCheckSubmitting.value=true;
  let res = await queryCsckWorkFlowBatchApi({dbList: multipleSelection.value.map(item => ({ pkid: item.pkid, orgCode: item.orgCode, dataDate: item.dataDate,systemGroupCode:item.sourceSystemCode+'-'+item.targetSystemCode }))});
  if (res.body?.result.count > 0) {
    ElMessage.warning('系统组已经提交,不能再次进行【批量校验】');
      dialogAllCheck.value = false;
      isCheckSubmitting.value=false;
      currentPage.value = 1;
      getList();
  }
  else{
    const res = await batchCheckRuleApi({
    list: multipleSelection.value.map(item => ({
      pkid: item.pkid,
      orgCodes: item.orgCode,
      dataDate: item.dataDate,
      checkRuleName: item.checkRuleName,
      session_loginName: session_loginName,
      systemGroupName: item.systemGroupName,
    })),
  });
  if (res) {
    if (+res.head.status === 500) {
      ElMessage.warning(res.head.msg || '批量校验失败');
    } else {
      ElMessage.success('批量校验任务排队成功,请到【作业监控】菜单查看批量校验执行情况!');
      isCheckSubmitting.value=false;
      getList();
    }
  }
  }
};
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <Table
      :table-id="TABLE_ID" :columns="tableColumns" v-model:pageSize="pageSize" v-model:currentPage="currentPage" default-expand-all
      node-key="pkid" :data="dataList" :border="true" :loading="loading" :pagination="{
        total,
      }" @selection-change="onSelectionChange" @register="tableRegister" @refresh="refresh">
      <template #buttons>
        <permission permission="dataRetrieval">
          <ElButton type="primary" :disabled="disabled || multipleSelection.length === 0 || isDrillSubmitting" @click="dataCount()"> 数据调取
          </ElButton>
        </permission>
        <permission permission="allCheck">
          <ElButton type="primary" @click="allCheck()"> 全部校验 </ElButton>
        </permission>
        <permission permission="batchCheck">
          <ElButton type="primary" :disabled="disabled || multipleSelection.length === 0 || isCheckSubmitting" @click="batchCheck()"> 批量校验
          </ElButton>
        </permission>
        <permission permission="exportExcel">
          <ElButton type="primary" @click="exportExcel()">全部导出</ElButton>
        </permission>
        <permission permission="exportCommentsExcel">
          <ElButton type="primary" @click="exportCommentsExcel()"> 按机构导出说明 </ElButton>
        </permission>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Detail v-if="actionType === 'detail'" :current-row="currentRow" :searchParams="searchParams" />
    <template #footer>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>

  <el-drawer v-model="CommentsDialogVisible" title="情况说明" direction="rtl" size="60%">
    <Comments :current-row="currentRow" ref="commentsRef" />
    <template #footer>
      <ElButton type="primary" :loading="saveLoading" @click="saveComments">{{ t('dialogDemo.save') }}</ElButton>
      <ElButton @click="CommentsDialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </el-drawer>

  <Dialog v-model="dialogAllCheck" title="全部校验">
    <AllCheck v-if="dialogAllCheck" ref="checkAllRef" />
    <template #footer>
      <ElButton type="primary" :disabled="isSubmitting" :loading="saveLoading" @click="handleCheckAll">
        {{ '校验' }}
      </ElButton>
      <ElButton @click="dialogAllCheck = false">{{ '取消' }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
:deep(.el-select .el-select__tags > span) {
  display: inline-flex !important;
}
</style>
