<script setup lang="tsx">
import { PropType, reactive, ref, unref, watch } from 'vue';
import { getCsckModelDetailTargetListApi, saveCsckModelDetailTargetApi, delCsckModelDetailTargetApi, queryCsckModelDetailTargetApi } from '@/api/csck/CsckModelDetailTarget';
import { TableData } from '@/api/csck/CsckModelDetailTarget/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 { ContentWrap } from '@/components/ContentWrap';
import Write from './components/Write.vue';
import Detail from './components/Detail.vue';
import { Dialog } from '@/components/Dialog';
import { IS_NULL_DICT_LIST, IS_PKID_DICT_LIST } from './constants';
import { getWidth } from '@/utils';
import { getDictOneApi } from '@/api/common';

const { t } = useI18n();

const props = defineProps({
  pkids: {
    type: Object as PropType<any>,
    default: () => null,
  },
});

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState;
    const res = await getCsckModelDetailTargetListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...props.pkids,
    });
    return {
      list: res.body.list,
      total: res.body.total,
    };
  },
});

const { loading, dataList, total, currentPage, pageSize } = tableState;
const { getList, refresh } = tableMethods;

const tableColumns = reactive<TableColumn[]>(
  [
    {
      field: 'selection',
      type: 'selection',
      fixed: true,
    },
    {
      field: 'systemName',
      label: '系统名称',
      minWidth: 150,
    },
    {
      field: 'systemVersion',
      label: '系统版本号',
    },
    {
      field: 'modelId',
      label: '模型ID',
      minWidth: 250,
    },
    {
      field: 'modelName',
      label: '模型名称',
      minWidth: 250,
    },
    {
      field: 'fieldCode',
      label: '字段编码',
    },
    {
      field: 'fieldName',
      label: '字段名称',
      minWidth: 150,
    },
    {
      field: 'dbType',
      label: '数据库类型',
      optionApi: async () => {
        const res = await getDictOneApi({
          paramName: 'DataBaseType_param',
          systemCode: 'system',
        });
        return res;
      },
    },
    {
      field: 'fieldType',
      label: '字段类型',
      optionApi: async () => {
        const res = await getDictOneApi({
          paramName: 'DataType_param',
          systemCode: 'system',
        });
        return res;
      },
    },
    {
      field: 'fieldLength',
      label: '字段长度',
    },
    {
      field: 'fieldPrecision',
      label: '字段精度',
    },
    {
      field: 'isNull',
      label: '是否为空',
      minWidth: 120,
      formatter: (row: Recordable, __: TableColumn) => {
        const isNull = IS_NULL_DICT_LIST.find(item => item.value === row.isNull);
        if (isNull) {
          return isNull.label;
        }
        return '-';
      },
    },
    {
      field: 'isPkid',
      label: '是否主键',
      minWidth: 120,
      formatter: (row: Recordable, __: TableColumn) => {
        const isPkid = IS_PKID_DICT_LIST.find(item => item.value === row.isPkid);
        if (isPkid) {
          return isPkid.label;
        }
        return '-';
      },
    },
    {
      field: 'action',
      label: t('tableDemo.action'),
      width: 120,
      fixed: 'right',
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
                {t('tableDemo.edit')}
              </ElLink>
              <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>
            </>
          );
        },
      },
    },
  ].map(item => ({ minWidth: item.label ? getWidth(item.label) : 120, ...item }) as TableColumn),
);

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

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

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

/**单行查询**/
const action = async (row: TableData, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)',
  });
  const res = await queryCsckModelDetailTargetApi({ systemVersion: row.systemVersion, modelId: row.modelId, fieldCode: row.fieldCode })
    .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 = { /* ...props.pkids,  */ ...data };
    dialogVisible.value = true;
  }
};

const AddAction = () => {
  dialogTitle.value = t('tableDemo.add');
  currentRow.value = props.pkids;
  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 saveCsckModelDetailTargetApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false;
      });
    if (res) {
      dialogVisible.value = false;
      currentPage.value = 1;
      getList();
    }
  }
};

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

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delCsckModelDetailTargetApi({ systemVersion: row.systemVersion, modelId: row.modelId, fieldCode: row.fieldCode });
  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;
};

watch(
  () => props.pkids,
  () => {
    refresh();
  },
  {
    deep: true,
    immediate: true,
  },
);
</script>

<template>
  <ContentWrap>
    <Table
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total,
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
    >
      <template #buttons>
        <ElButton type="primary" @click="AddAction">{{ t('tableDemo.add') }}</ElButton>
      </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>
</template>
