<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <a-alert type="info" show-icon>
          <template #message>
            <template v-if="checkedKeys.length > 0">
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <a-button type="link" @click="checkedKeys = []" size="small">清空</a-button>
              <a-popconfirm
                v-auth="'AUTH_BATCH_ORDER'"
                class="ml-4"
                title="确定要全部删除吗？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleBatchDelete"
              >
                <a href="#" class="text-red-500">删除</a>
              </a-popconfirm>
            </template>
            <template v-else>
              <span>未选中任何项目</span>
            </template>
          </template>
        </a-alert>
      </template>
      <!-- <template #toolbar>
        <a-button v-auth="'AUTH_BATCH_ORDER:ADD'" type="primary" @click="handleCreate"> 新增</a-button>
      </template> -->
      <template #bodyCell="{ column, record, text }">
        <template v-if="[].includes(column.dataIndex)">
          <img :src="text" class="photo" alt="图片" v-if="!!text" />
        </template>
        <template v-if="column.dataIndex === 'logisticsMode'">
          {{ logisticsLabelEnum[record.logisticsMode] }}
        </template>
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              // {
              //   tooltip: '编辑',
              //   icon: 'clarity:note-edit-line',
              //   onClick: handleEdit.bind(null, record),
              //   ifShow: hasPermission('AUTH_BATCH_ORDER:EDIT'),
              // },

              {
                label: '通过',
                color: 'success',
                popConfirm: {
                  title: '是否确认通过',
                  confirm: handleVerify.bind(null, record, 'PASSED'),
                },
                ifShow: hasPermission('AUTH_BATCH_ORDER:CHECK') && record.status === 'PENDING_REVIEW',
              },
              {
                label: '拒绝',
                color: 'error',
                popConfirm: {
                  title: '是否确认拒绝',
                  confirm: handleVerify.bind(null, record, 'REJECT'),
                },
                ifShow: hasPermission('AUTH_BATCH_ORDER:CHECK') && record.status === 'PENDING_REVIEW',
              },
              {
                tooltip: '详情',
                icon: 'ant-design:eye-outlined',
                onClick: handleView.bind(null, record),
                ifShow: hasPermission('AUTH_BATCH_ORDER:QUERY'),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <BatchOrderDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup name="AUTH_BATCH_ORDER">
  import { ref } from 'vue';
  import { useGo } from '/@/hooks/web/usePage';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { isObject } from '/@/utils/is';
  import moment from 'moment';
  import * as BatchOrderApi from '/@/api/order/batchOrderApi';
  import { useDrawer } from '/@/components/Drawer';
  import componentSetting from '/@/settings/componentSetting';
  import BatchOrderDrawer from './drawer.vue';
  import { columns, searchFormSchema } from './schema';
  import { useUserStore } from '/@/store/modules/user';
  import { logisticsLabelEnum } from '/@/views/order/enum';

  const { hasPermission } = usePermission();
  const go = useGo();
  const userStore = useUserStore();
  const { formConfig, showTableSetting, bordered, showIndexColumn } = componentSetting.table;

  // const isDistributor = userStore.getIsDistributor;

  const checkedKeys = ref<Array<string | number>>([]);
  const onSelectChange = (selectedRowKeys: (string | number)[]) => {
    checkedKeys.value = selectedRowKeys;
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, setLoading }] = useTable({
    title: '批量订单管理',
    api: (params) => BatchOrderApi.search(handleParams(params)),
    columns,
    formConfig: {
      labelWidth: formConfig.labelWidth,
      schemas: searchFormSchema,
      showAdvancedButton: false,
    },
    rowSelection: {
      type: 'checkbox',
      // @ts-ignore
      selectedRowKeys: checkedKeys,
      onChange: onSelectChange,
    },
    useSearchForm: true,
    showTableSetting,
    bordered,
    showIndexColumn,
    canResize: false,
    rowKey: (record: any) => record.id,
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  });

  const handleParams = (params) => {
    const { pageNum, pageSize } = params;
    const handledParams: any = { pageNum, pageSize };
    Object.keys(params).forEach((key) => {
      const schema = searchFormSchema.find((item) => item.field === key);
      const value = params[key];
      if (schema && value !== undefined && value !== '') {
        if (schema.component === 'Input') {
          handledParams[key] = `%${value.trim()}%`;
        } else if (['Select', 'ApiSelect'].includes(schema.component)) {
          handledParams[key] = isObject(value) ? value.value : value;
        } else if (schema.component === 'RangePicker') {
          handledParams[`${key}From`] = moment(value[0]).startOf('d').format('YYYY-MM-DD HH:mm:ss');
          handledParams[`${key}To`] = moment(value[1]).endOf('d').format('YYYY-MM-DD HH:mm:ss');
        } else if (schema.component === 'DatePicker') {
          handledParams[key] = moment(value).format((schema.componentProps as any).format || 'YYYY-MM-DD');
        } else {
          handledParams[key] = value;
        }
      }
    });
    return handledParams;
  };

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

  const handleEdit = (record: Recordable) => {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  };

  const handleDelete = (record: Recordable) => {
    setLoading(true);
    BatchOrderApi.remove(record.id)
      .then((_) => {
        reload();
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const handleBatchDelete = () => {
    setLoading(true);
    BatchOrderApi.batchRemove(checkedKeys.value)
      .then((_) => {
        reload();
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const handleSuccess = () => {
    reload();
  };

  const handleVerify = (record, status) => {
    BatchOrderApi.check({ id: record.id, status }).then(() => {
      reload();
    });
  };

  const handleView = (record) => {
    go('/main/batch-order/detail/' + record.id);
  };
</script>
