<template>
  <div>
    <BasicTable @register="registerTable" ref="basicTableRef">
      <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-if="isShowHandleDelete()"
                class="ml-4"
                title="确定要全部删除吗？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleBatchDelete"
              >
                <a href="#" class="text-red-500">删除</a>
              </a-popconfirm>
              <a-popconfirm
                v-if="hasPermission('AUTH_SYSTEM_DOCTOR:PASSED')"
                class="ml-4"
                title="确定要全部通过审核吗？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleBatchPassed"
              >
                <a href="#" class="text-green-500">审核通过</a>
              </a-popconfirm>
            </template>
            <template v-else>
              <span>未选中任何项目</span>
            </template>
          </template>
        </a-alert>
      </template>
      <template #toolbar>
        <a-button v-auth="'AUTH_SYSTEM_DOCTOR:ADD'" type="primary" @click="handleCreate"> 新增医生</a-button>
        <a-button v-auth="'AUTH_SYSTEM_DOCTOR:IMPORT'" type="primary" @click="handleImport"> 批量导入医生</a-button>
      </template>
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="StatusColorEnum[text]">{{ StatusEnum[text] }}</a-tag>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              //待审核 才能 通过
              {
                label: '通过',
                color: 'success',
                popConfirm: {
                  title: '是否确认通过',
                  confirm: handleVerify.bind(null, record, StatusValEnum.PASSED),
                },
                ifShow: isShowHandlePassed(record.status),
              },
              //待审核 才能 拒绝
              {
                label: '拒绝',
                color: 'error',
                popConfirm: {
                  title: '是否确认拒绝',
                  confirm: handleVerify.bind(null, record, StatusValEnum.REJECT),
                },
                ifShow: isShowHandleReject(record.status),
              },
              //已通过才能禁用
              {
                label: '禁用',
                color: 'error',
                popConfirm: {
                  title: '是否确认禁用',
                  confirm: handleVerify.bind(null, record, StatusValEnum.FORBIDDEN),
                },
                ifShow: isShowHandleForbidden(record.status),
              },
              //禁用后不能再编辑
              {
                tooltip: '编辑',
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                ifShow: isShowHandleEdit(record.status),
              },
              {
                tooltip: '详情',
                icon: 'ant-design:eye-outlined',
                onClick: handleView.bind(null, record),
                ifShow: hasPermission('AUTH_SYSTEM_DOCTOR:QUERY'),
              },
              {
                tooltip: '删除',
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                },
                ifShow: isShowHandleDelete(),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <DoctorDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup name="AUTH_SYSTEM_DOCTOR">
  import {
    isShowHandleEdit,
    isShowHandlePassed,
    isShowHandleForbidden,
    isShowHandleReject,
    isShowHandleDelete,
    getVerifyParams,
  } from './schema';
  import { StatusValEnum } from './enum';
  import { ref } from 'vue';
  import { useGo } from '/@/hooks/web/usePage';
  import { BasicTable, useTable, TableAction, TableActionType } from '/@/components/Table';
  import { isObject } from '/@/utils/is';
  import moment from 'moment';
  import * as DoctorApi from '/@/api/system/doctorApi';
  import { useDrawer } from '/@/components/Drawer';
  import componentSetting from '/@/settings/componentSetting';
  import DoctorDrawer from './drawer.vue';
  import { columns, searchFormSchema } from './schema';
  import { StatusColorEnum, StatusEnum } from './schema';
  import { BatchVerifyParams } from '/@/api/model/doctor';
  import { useUserStore } from '/@/store/modules/user';
  import { useActivatedReload } from '/@/hooks/myhooks/reLoadHook';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  const go = useGo();
  const { formConfig, showTableSetting, bordered, showIndexColumn } = componentSetting.table;
  const basicTableRef = ref<TableActionType>();
  const checkedKeys = ref<Array<string | number>>([]);
  const onSelectChange = (selectedRowKeys: (string | number)[]) => {
    checkedKeys.value = selectedRowKeys;
  };
  const userStore = useUserStore();

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, setLoading }] = useTable({
    title: '医生管理',
    api: (params) => DoctorApi.search(handleParams(params)),
    columns,
    formConfig: {
      labelWidth: formConfig.labelWidth,
      schemas: searchFormSchema,
      showAdvancedButton: false,
    },
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onChange: onSelectChange,
    },
    useSearchForm: true,
    showTableSetting,
    bordered,
    showIndexColumn,
    canResize: false,
    rowKey: (record: any) => record.id,
    actionColumn: {
      width: 210,
      title: '操作',
      dataIndex: 'action',

      fixed: 'right',
    },
  });

  useActivatedReload(reload);

  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;
        }
      }
    });
    // 如果是经销商，只能看到自己的数据
    if (userStore.getIsDistributor) {
      handledParams.distributorId = userStore.getDistributorId;
    }
    return handledParams;
  };

  //todo 医生管理-批量导入医生
  const handleImport = () => {};

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

  const handleVerify = (record: Recordable, status: string) => {
    setLoading(true);
    DoctorApi.batchVerify(getVerifyParams(record, status))
      .then((_) => {
        reload();
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const handleBatchPassed = () => {
    const params: BatchVerifyParams = {
      idList: checkedKeys.value,
      status: StatusValEnum.PASSED,
    };
    setLoading(true);
    DoctorApi.batchVerify(params)
      .then((_) => {
        reload();
      })
      .catch(() => {
        setLoading(false);
      });
  };

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

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

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

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

  const handleView = (record) => {
    go('/main/system/doctor/' + record.id);
  };
</script>
