<template>
  <PageWrapper fixedHeight contentFullHeight>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" v-auth="'materialProperty:add'" @click="handleCreate" class="ml-4">
          {{ t('新增') }}
        </a-button>
        <a-button
          type="primary"
          v-auth="'materialProperty:import'"
          @click="handleImport"
          class="ml-4"
        >
          {{ t('导入') }}
        </a-button>
        <a-button
          type="primary"
          v-auth="'materialProperty:export'"
          @click="handleExport"
          class="ml-4"
        >
          {{ t('导出') }}
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'state'">
          <a-switch v-model:checked="record.state" :checkedValue="1" :unCheckedValue="0" disabled />
        </template>
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                auth: 'materialProperty:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'materialProperty:delete',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PropertyModal @register="registerModal" @success="reload" />
    <ImportModal
      @register="registerImportModal"
      importUrl="/caseErpMaterial/caseErpMaterialProperty/import"
      @success="reload"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import {
    getPropertylPageList,
    deletePropertyList,
    exportInfo,
    downloadTemplate,
  } from '/@/api/erp/material/property';
  import { ImportModal } from '/@/components/Import';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { downloadByData } from '/@/utils/file/download';
  import PropertyModal from './PropertyModal.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '物料属性',
      dataIndex: 'propertyName',
      resizable: true,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      resizable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      resizable: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      resizable: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      resizable: true,
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'propertyName',
      label: '物料属性',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入物料类别',
      },
    },
    {
      field: 'createDate',
      label: '创建时间',
      component: 'RangePicker',
      colProps: { span: 8 },
      componentProps: {
        format: 'YYYY-MM-DD',
      },
    },
  ];
  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerModal, { openModal }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();

  const customRow = (record) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...getSelectRowKeys()];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        setSelectedRowKeys(selectedRowKeys);
      },
      ondblclick: () => {
        if (hasPermission('materialProperty:edit')) {
          handleEdit(record);
        }
      },
    };
  };
  const [registerTable, { reload, setSelectedRowKeys, getSelectRowKeys }] = useTable({
    title: '物料属性配置',
    api: getPropertylPageList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [['createDate', ['startTime', 'endTime'], 'YYYY-MM-DD', true]],
      showResetButton: false,
    },
    useSearchForm: true,
    showTableSetting: true,
    needDivider: true,
    striped: false,
    actionColumn: {
      width: 88,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      type: 'checkbox',
    },
    customRow,
    tableSetting: {
      size: false,
    },
  });

  const handleCreate = () => {
    openModal(true, {
      isUpdate: false,
    });
  };

  const handleEdit = (record) => {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deletePropertyList(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };
  const handleImport = () => {
    openImportModal(true, {
      title: t('快速导入'),
      api: downloadTemplate,
      templateTitle: '物料属性模板',
    });
  };
  const handleExport = async () => {
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择需要导出的数据',
      });
      return false;
    }
    const res = await exportInfo(getSelectRowKeys());
    downloadByData(
      res.data,
      '物料属性.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };
</script>
<style lang="less" scoped>
  :deep(.vben-page-wrapper-content) {
    margin: 0;
  }

  :deep(.ant-table-wrapper) {
    height: calc(100% - 10px);
  }
</style>
