<script setup lang="tsx">
import { reactive, ref, unref } from 'vue';
import {
  getCsckModelDetailListApi,
  saveCsckModelDetailApi,
  delCsckModelDetailListApi,
  delCsckModelDetailApi,
  queryCsckModelDetailApi,
  exportExcelApi,
} from '@/api/csck/CsckModelDetail';
import { TableData } from '@/api/csck/CsckModelDetail/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, ElDrawer } 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 { Dialog } from '@/components/Dialog';
import CsckModelDetailTarget from '../CsckModelDetailTarget/CsckModelDetailTarget.vue';
import { pick } from 'lodash-es';
import useSystemVersion from '@/hooks/web/useSystemVersion';
import { getWidth } from '@/utils';
// import { getDictOneApi } from '@/api/common';

defineOptions({
  name: 'Modeldetail'
})

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

const ids = ref<string[]>([]);

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

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

const { formItem } = useSystemVersion(searchRef, { style: { width: '300px' } }, { label: '业务系统/系统版本', actionType: 'add' });

const tableColumns = reactive<TableColumn[]>(
  [
    // {
    //   field: 'selection',
    //   type: 'selection',
    //   fixed: true,
    // },
    {
      field: 'systemCode',
      label: '系统编码',
    },
    {
      field: 'systemName',
      label: '系统名称',
      minWidth: 150,
    },
    {
      field: 'systemVersion',
      label: '系统版本号',
    },
    {
      field: 'modelId',
      label: '模型ID',
      minWidth: 250,
    },
    {
      field: 'modelName',
      label: '模型名称',
      minWidth: 250,
    },
    // {
    //   field: 'storeType',
    //   label: '存储方式',
    //   optionApi: async () => {
    //     const res = await getDictOneApi({
    //       paramName: 'DataStoreType_param',
    //       systemCode: 'system',
    //     });
    //     return res;
    //   },
    // },
    // {
    //   field: 'storeFrequency',
    //   label: '存储频度',
    //   optionApi: async () => {
    //     const res = await getDictOneApi({
    //       paramName: 'DataStoreFrequency_param',
    //       systemCode: 'system',
    //     });
    //     return res;
    //   },
    // },
    {
      field: 'action',
      label: t('tableDemo.action'),
      width: 160,
      fixed: 'right',
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'structure')}>
                结构
              </ElLink>
              <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 searchSchema = reactive<FormSchema[]>([
  ...formItem,
  {
    field: 'modelName',
    label: '模型名称',
    component: 'Input',
  },
]);

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

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

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

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

/**单行查询**/
const action = async (row: TableData, type: string) => {
  if (type === 'structure') {
    currentRow.value = pick(row, ['systemCode', 'systemName', 'systemVersion', 'modelId', 'modelName']);
    drawerVisible.value = true;
  } else {
    let detailLoading = ElLoading.service({
      background: 'rgba(0, 0, 0, 0.7)',
    });
    const res = await queryCsckModelDetailApi(row.systemCode, row.systemVersion, row.modelId)
      .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;
      dialogVisible.value = true;
    }
  }
};

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 saveCsckModelDetailApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false;
      });
    if (res) {
      dialogVisible.value = false;
      currentPage.value = 1;
      getList();
    }
  }
};

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delCsckModelDetailApi(row.systemCode, row.systemVersion, row.modelId);
  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) };
  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="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>
        <!-- <Upload :url="importExcelApiUrl" :callback="getList">
          <ElButton type="primary">导入</ElButton>
        </Upload>
        <ElButton type="primary" @click="exportExcel()">导出</ElButton> -->
        <!-- <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delDataBatch()">
          {{ t('tableDemo.del') }}
        </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>

  <el-drawer v-model="drawerVisible" title="明细模型表结构" direction="rtl" size="90%">
    <CsckModelDetailTarget :pkids="currentRow" />
  </el-drawer>
</template>
