<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button v-show="!getCheckRole('tourist')" type="primary" @click="handleCreate">
          新增商品属性</a-button
        >
      </template>
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
    </BasicTable>
    <addModal @register="registerModal" @saveadd="handleSaveAdd" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref } from 'vue'; // h
  import {
    BasicTable,
    useTable,
    BasicColumn,
    TableAction,
    EditRecordRow,
    ActionItem,
  } from '/@/components/Table';
  import { attributeListApi, attributeDeleteApi, updateItemApi } from '/@/api/product/category';
  import { cloneDeep } from 'lodash-es';
  // import { Tag } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import addModal from './addModal.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    components: { BasicTable, TableAction, addModal },
    setup() {
      const { createConfirm, createMessage: msg } = useMessage();
      const [registerModal, { openModal }] = useModal();
      const currentEditKeyRef = ref('');
      const userStore = useUserStore();
      const { getCheckRole } = userStore;
      const { t } = useI18n();
      console.log('registerModal', registerModal);
      const columns: BasicColumn[] = [
        {
          title: t('routes.dashboard.productRef'),
          editRow: true,
          editRule: async (text) => {
            if (!text) {
              return t('routes.product.productRefMessge');
            }
            if (text && text.length > 15) {
              return t('routes.corporation.maxlength');
            }
            return '';
          },
          dataIndex: 'name',
          fixed: 'left',
          width: 100,
        },
        {
          title: t('routes.scenes.sortOrder'),
          dataIndex: 'sortOrder',
          editComponent: 'InputNumber',
          editRule: async (text) => {
            if (text == null || text < 0) {
              return t('routes.product.sortOrderTips');
            }
            return '';
          },
          editRow: true,
          width: 50,
        },
      ];

      const [registerTable, { expandAll, reload, collapseAll }] = useTable({
        title: t('routes.dashboard.productRef'),
        api: attributeListApi,
        columns: columns,
        useSearchForm: true,
        showIndexColumn: false,
        // rowSelection: { type: 'checkbox' },
        rowKey: 'id',
        bordered: true,
        showIndexColumn: true,
        fetchSetting: {
          pageField: 'page',
          sizeField: 'limit',
          listField: 'list',
          totalField: 'totalCount',
        },
        formConfig: {
          labelWidth: 66,
          schemas: [
            {
              field: `name`,
              label: t('routes.dashboard.productRef'),
              component: 'Input',
              colProps: {
                xl: 6,
                xxl: 6,
              },
              componentProps: {
                maxLength: 15,
              },
            },
          ],
        },
        actionColumn: {
          ifShow: !getCheckRole('tourist'),
          width: 160,
          title: t('common.operating'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      async function handleCreate() {
        openModal(true);
      }
      function handleEdit(record: EditRecordRow) {
        currentEditKeyRef.value = record.key;
        record.onEdit?.(true);
      }
      function handleDelete(record) {
        createConfirm({
          iconType: 'warning',
          title: t('common.warning'),
          content: t('routes.staff.delMessage', { userName: record.name }),
          onOk: async () => {
            let res = await attributeDeleteApi(record.id);
            console.log('res', res);
            reload();
          },
        });
      }
      function handleCancel(record: EditRecordRow) {
        currentEditKeyRef.value = '';
        record.onEdit?.(false, false);
      }
      async function handleSaveAdd() {
        console.log('handleSaveAdd');
        reload();
      }

      async function handleSave(record: EditRecordRow) {
        // 校验
        msg.loading({ content: t('routes.product.preservation'), duration: 0, key: 'saving' });
        const valid = await record.onValid?.();
        console.log('ref', valid);
        if (valid) {
          try {
            const data = cloneDeep(record.editValueRefs);
            console.log(data);
            //TODO 此处将数据提交给服务器保存
            // ...
            updateItemApi({
              id: record.id,
              ...data,
            });

            // 保存之后提交编辑状态
            const pass = await record.onEdit?.(false, true);
            if (pass) {
              currentEditKeyRef.value = '';
            }
            msg.success({ content: t('routes.product.dataSave'), key: 'saving' });
            reload();
          } catch (error) {
            msg.error({ content: t('routes.product.dataSaveFail'), key: 'saving' });
          }
        } else {
          msg.error({ content: t('routes.product.correctData'), key: 'saving' });
        }
      }
      function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
        // console.log('editable', record);
        if (!record.editable) {
          return [
            {
              label: t('common.edit'),
              disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
              onClick: handleEdit.bind(null, record),
            },
            {
              label: t('common.delText'),
              color: 'error',
              disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
              onClick: handleDelete.bind(null, record),
            },
          ];
        }
        return [
          {
            label: t('common.saveText'),
            onClick: handleSave.bind(null, record, column),
          },
          {
            label: t('common.cancelText'),
            popConfirm: {
              title: t('common.EditorNot'),
              confirm: handleCancel.bind(null, record, column),
            },
          },
        ];
      }
      return {
        registerTable,
        createActions,
        t,
        registerModal,
        handleSaveAdd,
        handleCreate,
        handleEdit,
        handleDelete,
        expandAll,
        collapseAll,
        getCheckRole,
        reload,
      };
    },
  });
</script>
