<script setup lang="tsx">
import { reactive, ref, unref } from 'vue';
import {
  getCsckCheckRuleListApi,
  saveCsckCheckRuleApi,
  testCsckCheckRuleApi,
  delCsckCheckRuleApi,
  queryCsckCheckRuleApi,
  exportExcelApi,
  importExcelApiUrl,
  getCsckCheckType,
} from '@/api/csck/CsckCheckRule';
import { Upload } from '@/components/Upload';
import { TableData } from '@/api/csck/CsckCheckRule/types';
import { useTable } from '@/hooks/web/useTable';
import { useI18n } from '@/hooks/web/useI18n';
import { Table, TableColumn } from '@/components/Table';
import { ElButton, ElLink, ElLoading, ElPopconfirm, ElMessage } from 'element-plus';
import { Search } from '@/components/Search';
import { FormSchema } from '@/components/Form';
import { ContentWrap } from '@/components/ContentWrap';
import Write from './components/Write.vue';
import Detail from './components/Detail.vue';
import Rule from './components/Rule.vue';
import { Dialog } from '@/components/Dialog';
import { IS_ENABLE_DICT_LIST, IS_ENFORCEMENT_DICT_LIST } from './constants';
import { getWidth, transfDictList } from '@/utils';
import useSystemGroupVersion from '@/hooks/web/useSystemGroupVersion';
import { SYSTEM_GROUP_DICT_LIST } from '../CsckDataCheckResult/constants';
import { hasPermi } from '@/components/Permission';

defineOptions({
  name: 'Checkrule'
})

const dialogTableRuleVisible = ref(false);
const searchRef = ref<any>(null);
const { t } = useI18n();

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState;
    const res = await getCsckCheckRuleListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
    });
    return {
      list: res.body.list,
      total: res.body.total,
    };
  },
  // fetchDelApi: async () => {
  //   const res = await delCsckDataCheckImportListApi(unref(ids));
  //   return !!res;
  // },
});

const { loading, dataList, total, currentPage, pageSize } = tableState;
const { getList, /* getElTableExpose, delList, */ refresh } = tableMethods;

const PermiLen = ['edit', 'test', 'del'].map(item => {
  return hasPermi(item);
});
const actionWidth = 120 + PermiLen.length * 60;

const tableColumns = reactive<TableColumn[]>(
  [
    {
      field: 'selection',
      type: 'selection',
      fixed: true,
    },
    {
      field: 'ruleCode',
      label: '规则编码',
      formatter: (row: Recordable, __: TableColumn) => {
        return row.systemGroupName+'-'+row.ruleCode;
      },
      sortable:true
    },
    {
      field: 'checkRuleName',
      label: '校验规则名称',
    },
    {
      field: 'checkVersion',
      label: '校验版本',
    },
    {
      field: 'ruleMakingOrgan',
      label: '规则编制机构',
      optionApi: async () => {
        const res = await getCsckCheckType({ paramName: 'RuleConfigOrg_param', systemCode: 'system' });
        return transfDictList(res.body.result);
      },
    },
    {
      field: 'comparator',
      label: '比较符',
      optionApi: async () => {
        const res = await getCsckCheckType({ paramName: 'CheckCompareType_param', systemCode: 'system' });
        return transfDictList(res.body.result);
      },
    },
    {
      field: 'faultTolerance',
      label: '容差范围',
    },
    {
      field: 'riskLevel',
      label: '风险等级',
      optionApi: async () => {
        const res = await getCsckCheckType({ paramName: 'RiskType_param', systemCode: 'system' });
        return transfDictList(res.body.result);
      },
    },
    {
      field: 'attentionDegree',
      label: '官方关注度',
      optionApi: async () => {
        const res = await getCsckCheckType({ paramName: 'AttentType_param', systemCode: 'system' });
        return transfDictList(res.body.result);
      },
    },
    {
      field: 'businessType',
      label: '业务类型',
      optionApi: async () => {
        const res = await getCsckCheckType({ paramName: 'BusinessType_param', systemCode: 'system' });
        return transfDictList(res.body.result);
      },
    },
    {
      field: 'frequency',
      label: '执行频度',
      optionApi: async () => {
        const res = await getCsckCheckType({ paramName: 'DataStoreFrequency_param', systemCode: 'system' });
        return transfDictList(res.body.result);
      },
    },
    {
      field: 'isEnable',
      label: '是否启用',
      minWidth: 120,
      formatter: (row: Recordable, __: TableColumn) => {
        const isEnable = IS_ENABLE_DICT_LIST.find(item => item.value === row.isEnable);
        if (isEnable) {
          return isEnable.label;
        }
        return '-';
      },
    },
    {
      field: 'isEnforcement',
      label: '是否法定校验',
      minWidth: 160,
      formatter: (row: Recordable, __: TableColumn) => {
        const isEnforcement = IS_ENFORCEMENT_DICT_LIST.find(item => item.value === row.isEnforcement);
        if (isEnforcement) {
          return isEnforcement.label;
        }
        return '-';
      },
    },
    {
      field: 'ruleDesc',
      label: '规则描述',
    },
    {
      field: 'startDate',
      label: '开始日期',
    },
    {
      field: 'endDate',
      label: '结束日期',
    },
    {
      field: 'action',
      label: t('tableDemo.action'),
      width: actionWidth,
      fixed: 'right',
      slots: {
        default: (data: any) => {
          return (
            <>
              <permission permission="rule">
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'editRule')}>
                配置规则
              </ElLink>
              </permission>
              <permission permission="edit">
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
                {t('tableDemo.edit')}
              </ElLink>
              </permission>
              <permission permission="test">
              <ElLink type="primary" underline={false} onClick={() => testCsckCheckRule(data.row)}>
                测试规则
              </ElLink>
              </permission>
              <permission permission="del">
              <ElPopconfirm
                title={t('common.delTableMsg')}
                width={200}
                v-slots={{
                  reference: () => {
                    return (
                      <>
                        <ElLink type="primary" underline={false}>
                          {t('tableDemo.del')}
                        </ElLink>
                      </>
                    );
                  },
                }}
                onConfirm={() => delData(data.row)}
              ></ElPopconfirm>
              </permission>
            </>
          );
        },
      },
    },
  ].map(item => ({ minWidth: item.label ? getWidth(item.label) : 120, ...item }) as TableColumn),
);

const { formItem } = useSystemGroupVersion(searchRef, { style: { width: '500px' } }, { label: '系统组别/校验版本', actionType: 'add' });

const searchSchema = reactive<FormSchema[]>([  ...formItem
,
  {
    field: 'checkRuleName',
    label: '校验规则名称',
    component: 'Input'
  },

  {
    field: 'systemGroupCode',
    label: '系统组',
    component: 'Select',
    componentProps: {
      options: SYSTEM_GROUP_DICT_LIST,
    },
  },
  {
    field: 'ruleCode',
    label: '规则编码',
    component: 'InputRange',
    formItemProps: {
      rules: [{
        validator: (_, val, callback) => {
        console.log(val);
          if (val) {
            if((val[0] && val[0].length !== 5) || (val[1] && val[1].length !== 5)) {
              callback(new Error('请输入5位规则编码'));
            }
          }
          callback();
        }
      }]
    }
  },
]);

const searchParams = ref({});
const setSearchParams = (data: any) => {
  searchParams.value = data;
  getList();
};

const dialogVisible = ref(false);
const dialogTitle = ref('');

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

const writeRef = ref<ComponentRef<typeof Write>>();
const ruleRef = ref<ComponentRef<typeof Rule>>();

/**单行查询**/
const action = async (row: TableData, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)',
  });
  const res = await queryCsckCheckRuleApi(row.pkid)
    .catch(() => {})
    .finally(() => {
      detailLoading.close();
    });
  detailLoading.close();
  if (res) {
    const data = res.body.result;
    dialogTitle.value = t(type === 'edit' ? 'tableDemo.edit' : 'tableDemo.detail');
    actionType.value = type;
    currentRow.value = data;
    if (type !== 'editRule') {
      dialogVisible.value = true;
    }
    if (type == 'editRule') {
      dialogTableRuleVisible.value = true;
    }
  }
};

/**测试规则**/
const testCsckCheckRule = async (row: TableData) => {
  const res = await testCsckCheckRuleApi(row.pkid)
    .catch(() => {})
    .finally(() => {
    });
  if (res) {
    const result = res.body.result;
    if (result === 'true') {
      ElMessage.success('测试成功!');
      getList();
    } else {
      ElMessage.error('测试失败!');
    }

  }
};

const AddAction = () => {
  dialogTitle.value = t('tableDemo.add');
  currentRow.value = undefined;
  dialogVisible.value = true;
  actionType.value = 'add';
};

const saveLoading = ref(false);

/** 保存 **/
const save = async () => {
  const write = unref(writeRef);
  const formData = await write?.submit();
  if (formData) {
    saveLoading.value = true;
    const res = await saveCsckCheckRuleApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false;
      });
    if (res) {
      dialogVisible.value = false;
      currentPage.value = 1;
      getList();
    }
  }
};

/** 配置规则 **/
const saveRule = async () => {
  const rule = unref(ruleRef);
  const formData = await rule?.submit();
  if (formData) {
    saveLoading.value = true;
    const res = await saveCsckCheckRuleApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false;
        dialogTableRuleVisible.value = false;
      });
    if (res) {
      dialogTableRuleVisible.value = false;
      currentPage.value = 1;
      getList();
    }
  }
};

// const delLoading = ref(false)

/** 批量删除  **/
/** const delDataBatch = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value = elTableExpose?.getSelectionRows().map((v: TableData) => v.pkid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
} **/

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delCsckCheckRuleApi(row.pkid);
  if (res) {
    const { code, errMsg } = res.head;
    if (code === '0') {
      ElMessage.success('删除成功!');
      getList();
    } else {
      ElMessage.error(errMsg || '删除失败!');
    }
  }
};

const disabled = ref(true);

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

/** 导出Excel */
const exportExcel = async () => {
  const data = { ...unref(searchParams),fileName:'检验规则定义' };
  await exportExcelApi(data);
};
</script>

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

    <Table
      :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="add">
          <ElButton type="primary" @click="AddAction">{{ t('tableDemo.add') }}</ElButton>
        </permission>
        <permission permission="import">
          <Upload :url="importExcelApiUrl" :callback="getList">
            <ElButton type="primary">导入</ElButton>
          </Upload>
        </permission>
        <permission permission="export">
          <ElButton type="primary" @click="exportExcel()">导出</ElButton>
        <!-- <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delDataBatch()">
          {{ t('tableDemo.del') }}
        </ElButton> -->
        </permission>

      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" :action-type="actionType" />
    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('dialogDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>

  <Dialog v-model="dialogTableRuleVisible" title="计算规则配置">
    <Rule :dialogTableRuleVisible="dialogTableRuleVisible" v-if="dialogTableRuleVisible" :current-row="currentRow" ref="ruleRef" />
    <template #footer>
      <ElButton type="primary" :loading="saveLoading" @click="saveRule">
        {{ t('dialogDemo.save') }}
      </ElButton>
      <ElButton @click="dialogTableRuleVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
