<template>
  <BasicDrawer
    :title="title"
    :maskClosable="true"
    :confirmLoading="confirmLoading"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    v-model:open="visible"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <BasicForm @register="registerForm" />

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button @click="handleCancel" style="margin-right: 0.8rem">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { getAction, postAction } from '@/api/manage/manage';
  import { formSchema } from '../EnterpriseUserManage.data';
  import { onBeforeMount, ref } from 'vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicDrawer } from '@/components/Drawer';
  import { getTenantId } from '/@/utils/auth';

  const userStore = useUserStore();

  let drawerWidth = ref(700);

  let checkedDepartNameString = ref('');

  let userId = ref('');
  const disableSubmit = ref(false);

  let departIdShow = ref(false);

  const title = ref('操作');
  const visible = ref(false);

  const selectedRole = ref([]);

  const confirmLoading = ref(false);

  const picUrl = ref('');
  const identity = ref('1');

  let siteCode = ref('');
  let dictSiteCode = ref('');
  const url = {
    fileUpload: window._CONFIG['domianURL'] + '/sys/common/upload',
    userId: '/sys/user/generateUserId', // 引入生成添加用户情况下的url
    syncUserByUserName: '/act/process/extActProcess/doSyncUserByUserName', //同步用户到工作流
    queryTenantList: '/sys/tenant/queryList',
  };
  const emit = defineEmits(['ok', 'close', 'success']);

  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const { createMessage } = useMessage();

  onBeforeMount(() => {
    siteCode.value = localStorage.getItem('siteCode') ?? '';
    getTurnInquiryCode();
  });

  function refresh() {
    checkedDepartNameString.value = '';
    userId.value = '';
    departIdShow.value = false;
  }

  function add() {
    picUrl.value = '';
    refresh();
    edit({ activitiSync: '1' });
  }

  function edit(record) {
    resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度

    checkedDepartNameString.value = '';

    if (record.hasOwnProperty('id')) {
      setFieldsValue({
        ...record,
      });
    }
    userId.value = record.id;

    visible.value = true;
  }

  function close() {
    emit('close');
    visible.value = false;
    disableSubmit.value = false;
    selectedRole.value = [];
    checkedDepartNameString.value = '';
    departIdShow.value = false;
    identity.value = '1';
  }

  async function handleSubmit() {
    try {
      let values = await validate();
      confirmLoading.value = true;
      values.userIdentity === 1 && (values.departIds = '');

      let obj;
      values.masterId = userStore.getUserInfo.id;
      values.masterName = userStore.getUserInfo.username;

      if (!values.id) {
        values.siteCode = siteCode.value;
        values.relTenantIds = getTenantId();
        obj = postAction('/enterprise/user/add', values, 120000);
      } else {
        values.masterEmail = userStore.getUserInfo.email;
        values.siteCode = siteCode;
        obj = postAction('/enterprise/user/edit', values, 120000);
      }
      //提交表单
      obj
        .then((res) => {
          if (res.code === 200) {
            createMessage.success(res.message);
            confirmLoading.value = false;
            close();
            emit('ok');
          } else {
            confirmLoading.value = false;
            createMessage.warning(res.message);
          }
        })
        .finally(() => {
          //关闭弹窗
          close();
        });
    } finally {
      confirmLoading.value = false;
    }
  }

  function handleCancel() {
    close();
  }

  // 根据屏幕变化,设置抽屉尺寸
  function resetScreenSize() {
    let screenWidth = document.body.clientWidth;
    if (screenWidth < 500) {
      drawerWidth.value = screenWidth;
    } else {
      drawerWidth.value = 700;
    }
  }

  //获取需要轮流询盘的站点code
  function getTurnInquiryCode() {
    getAction('/adweb/adwebEnquiry/getTurnInquiryCode', {}).then((res) => {
      if (res.code === 200) {
        dictSiteCode.value = res.result[0].value;
      }
    });
  }

  defineExpose({
    add,
    edit,
    disableSubmit,
    title,
  });
</script>

<style scoped>
  .avatar-uploader > .ant-upload {
    width: 104px;
    height: 104px;
  }

  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>
