<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: '商品属性',
          editRow: true,
          editRule: async (text) => {
            if (!text) {
              return '请输入商品属性';
            }
            if (text && text.length > 15) {
              return t('routes.corporation.maxlength');
            }
            return '';
          },
          dataIndex: 'name',
          fixed: 'left',
          width: 100,
        },
        {
          title: '排序',
          dataIndex: 'sortOrder',
          editComponent: 'InputNumber',
          editRule: async (text) => {
            if (text == null || text < 0) {
              return '请输入正确排序';
            }
            return '';
          },
          editRow: true,
          width: 50,
        },
      ];

      const [registerTable, { expandAll, reload, collapseAll }] = useTable({
        title: '商品属性',
        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: `商品属性`,
              component: 'Input',
              colProps: {
                xl: 6,
                xxl: 6,
              },
              componentProps: {
                maxLength: 15,
              },
            },
          ],
        },
        actionColumn: {
          ifShow: !getCheckRole('tourist'),
          width: 160,
          title: '操作',
          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: '警告',
          content: `此操作将对${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: '正在保存...', 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: '数据已保存', key: 'saving' });
            reload();
          } catch (error) {
            msg.error({ content: '保存失败', key: 'saving' });
          }
        } else {
          msg.error({ content: '请填写正确的数据', key: 'saving' });
        }
      }
      function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
        // console.log('editable', record);
        if (!record.editable) {
          return [
            {
              label: '编辑',
              disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              color: 'error',
              disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
              onClick: handleDelete.bind(null, record),
            },
          ];
        }
        return [
          {
            label: '保存',
            onClick: handleSave.bind(null, record, column),
          },
          {
            label: '取消',
            popConfirm: {
              title: '是否取消编辑',
              confirm: handleCancel.bind(null, record, column),
            },
          },
        ];
      }
      return {
        registerTable,
        createActions,
        t,
        registerModal,
        handleSaveAdd,
        handleCreate,
        handleEdit,
        handleDelete,
        expandAll,
        collapseAll,
        getCheckRole,
        reload,
      };
    },
  });
</script>
