<template>
  <BasicModal
  :maskClosable="false"
    width="650px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <div style="height: 90vh">
      <BasicForm @register="registerForm">
        <template #organizationId="{ model, field }">
          <BasicTree
            v-if="organizationTreeData.length"
            v-model:value="model[field]"
            :treeData="organizationTreeData"
            :checked-keys="checkGroup"
            :expandedKeys="treeExpandData"
            ref="basicTreeRef"
            checkable
            toolbar
          />
        </template>
        <template #roleSlot="{ model, field }">
          <a-select
            mode="multiple"
            allowClear
            placeholder="请选择角色"
            v-model:value="model[field]"
            :options="roleOptions.map((item) => ({ value: item.value, label: item.label }))"
          >
            <template #dropdownRender="{ menuNode: menu }">
              <v-nodes :vnodes="menu" />
              <a-divider style="margin: 4px 0" />
              <div @click="handleOpenRole" style="padding: 4px 0; cursor: pointer">
                <plus-outlined />
                新增角色
              </div>
            </template>
          </a-select>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
  <RoleDrawer @register="registerRoleDrawer" @success="handleSuccess" />
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './account.data';
  import {
    findCurrentUserRelation,
    SaveOrUpdateUserInfo,
    filterRoleList,
  } from '/@/api/system/system';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { findCurrentUserGroups } from '/@/api/system/group';
  import { RoleOrOrganizationParam } from '/@/api/system/model/systemModel';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { copyTransTreeFun } from '/@/utils/fnUtils';
  import { TOption } from '/@/views/rule/linkedge/config/config.data';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { useDrawer } from '/@/components/Drawer';
  import RoleDrawer from '../role/RoleDrawer.vue';

  export default defineComponent({
    name: 'AccountModal',
    components: {
      BasicModal,
      BasicForm,
      BasicTree,
      PlusOutlined,
      RoleDrawer,
      VNodes: (_, { attrs }) => {
        return attrs.vnodes;
      },
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const roleOptions = ref<TOption[]>([]);
      const isUpdate = ref(true);
      const rowId = ref('');
      const organizationTreeData = ref<TreeItem[]>([]);
      const basicTreeRef = ref();
      const checkGroup = ref<string[]>([]);
      const treeExpandData = ref([]);
      const olderPhoneNumber = ref();
      const phoneNumber = ref();
      const postData = reactive({});
      const singleEditPostPhoneNumber = reactive({
        phoneNumber: '',
      });
      const getRoleList = async () => {
        const res = await filterRoleList();
        console.log(res);
        roleOptions.value = res.map((m) => {
          return {
            label: m.name,
            value: m.id,
          };
        });
      };
      onMounted(async () => {
        await getRoleList();
      });
      const [registerRoleDrawer, { openDrawer }] = useDrawer();

      const handleOpenRole = () => {
        openDrawer(true, {
          isUpdate: false,
        });
      };
      const handleSuccess = async () => {
        await getRoleList();
      };
      const [
        registerForm,
        { setFieldsValue, updateSchema, resetFields, validate, getFieldsValue },
      ] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 18,
        },
      });
      //获取所有父级id
      function findForAllId(data = [], arr = []) {
        for (const item of data) {
          arr.push(item.id);
        }
        return arr;
      }

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log('data', data);
        await resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        const groupListModel = await findCurrentUserGroups();
        if (!unref(organizationTreeData).length) {
          copyTransTreeFun(groupListModel);
          organizationTreeData.value = groupListModel;
          const getAllIds = findForAllId(organizationTreeData.value as any, []);
          //设置要展开的id
          treeExpandData.value = getAllIds;
          phoneNumber.value = '';
        }
        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          const roleParams = new RoleOrOrganizationParam(rowId.value, true, false);

          olderPhoneNumber.value = data.record.phoneNumber;
          singleEditPostPhoneNumber.phoneNumber = data.record.phoneNumber;
          findCurrentUserRelation(roleParams).then((result) => {
            Reflect.set(data.record, 'roleIds', result);
            Reflect.set(data.record, 'password', '******');
            console.log('data.record', data.record);

            setFieldsValue(data.record);
          });
          const organizationParams = new RoleOrOrganizationParam(rowId.value, false, true);
          checkGroup.value = await findCurrentUserRelation(organizationParams);
        }
        await updateSchema([
          {
            field: 'username',
            dynamicDisabled: unref(isUpdate),
          },
          {
            field: 'password',
            ifShow: !unref(isUpdate),
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        setModalProps({ confirmLoading: true });
        try {
          const { createMessage } = useMessage();
          if (unref(isUpdate)) {
            Object.assign(postData, singleEditPostPhoneNumber);
          }
          const values = await validate([
            'id',
            'username',
            'realName',
            'password',
            'roleIds',
            'email',
            'accountExpireTime',
            'enabled',
            'remark',
            'organizationIds',
            olderPhoneNumber.value === getFieldsValue().phoneNumber ? 'phoneNumber' : 'phoneNumber',
          ]);
          values.accountExpireTime =
            typeof values.accountExpireTime != 'undefined' && values.accountExpireTime != null
              ? values.accountExpireTime.format('YYYY-MM-DD HH:mm:ss')
              : null;
          Object.assign(postData, values);
          if (unref(isUpdate)) {
            if (values.email == '') {
              delete postData.email;
            }
          } else {
            if (values.email == '') {
              delete postData.email;
            }
          }
          await SaveOrUpdateUserInfo(postData as any, unref(isUpdate));
          closeModal();
          emit('success');
          createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
        } finally {
          setTimeout(() => {
            setModalProps({ confirmLoading: false });
          }, 300);
        }
      }
      return {
        registerModal,
        registerForm,
        handleSubmit,
        getTitle,
        organizationTreeData,
        checkGroup,
        basicTreeRef,
        treeExpandData,
        roleOptions,
        registerRoleDrawer,
        handleOpenRole,
        handleSuccess,
      };
    },
  });
</script>
<style scoped lang="less">
  :deep(.vben-basic-tree) {
    width: 100% !important;
  }

  :deep(.is-unflod) {
    display: none !important;
  }

  :deep(.is-flod) {
    display: none !important;
  }
</style>
