<template>
  <h-modal
    centered
    id="TransferProcess-queryModal"
    v-model:visible="visible"
    :title="t('userManagement.processTransfer.title')"
    width="448px"
    wrap-class-name="full-modal"
    :destroyOnClose="true"
    :maskClosable="false"
    class="TransferProcess-modal"
  >
    <p class="card-title">
      {{ t('userManagement.processTransfer.title') }}
      <h-tooltip placement="right" :title="t('userManagement.processTransfer.titleHelp')">
        <ExclamationCircleOutlined class="exclamation-icon" />
      </h-tooltip>
    </p>
    <p>
      {{ t('userManagement.processTransfer.processTransfer') }}{{ userData[`USER_ALL_NAME`] ?? '' }}
    </p>
    <h-form
      class="hForm"
      ref="formCtrl"
      layout="vertical"
      :model="formState"
      :hideRequiredMark="true"
    >
      <h-form-item
        :label="t('userManagement.processTransfer.processReceiver')"
        name="receiverId"
        :rules="[
          {
            required: true,
            message: t('userManagement.processTransfer.processReceiverMsg'),
          },
        ]"
      >
        <h-b-tree-select
          @change="handleChange"
          v-bind="lazyProps"
          :getPopupContainer="getPopupContainer"
        ></h-b-tree-select>
      </h-form-item>
    </h-form>
    <template #footer>
      <h-button @click="handleCancel" :loading="btnLoading">
        {{ t('platform.common.cancel') }}
      </h-button>
      <h-button
        type="primary"
        :loading="btnLoading"
        html-type="submit"
        style="margin-left: 10px"
        @click="handleOk"
      >
        {{ t('platform.common.ok') }}
      </h-button>
    </template>
  </h-modal>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed } from 'vue';
import { HModal, message } from '@crami/ui';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'TransferProcess',
  components: { HModal },
  emits: ['processTransferSuccess'],
  setup(_, { emit }) {
    const { t } = useI18n();
    let btnLoading = ref(false);
    const visible = ref(false);
    const userData: any = ref('');
    const show = data => {
      visible.value = true;
      userData.value = data;
    };

    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });

    const formState: any = reactive({
      receiverId: '',
    });

    const getPopupContainer = () => {
      return document.body;
    };
    const paraList = {
      companyId: commonParams.value?.companyId,
      lang: commonParams.value?.lang,
      connect: commonParams.value?.connect,
      userId: commonParams.value?.user_id,
    };
    //  懒加载子节点 下拉树 数据
    const lazyProps = reactive({
      disabled: false,
      multiple: false,
      allowClear: true,
      treeCheckable: false,
      labelInValue: true,
      // defaultValue: { label: 'parent 1', value: 'value 1' },
      fieldNames: { value: 'value1' },
      // 获取根节点数据
      treeDataApi: {
        params: {
          companyId: commonParams.value?.companyId,
          connect: commonParams.value?.connect,
          filter: [],
          lang: commonParams.value?.lang,
          loadAll: false,
          loadAllStructure: false,
          paraList: JSON.stringify(paraList),
          params: {},
          userId: commonParams.value?.user_id,
        },
      },
      beforeRequest: () => {
        return {
          treeViewName: userData.value?.treeView,
          objectType: userData.value?.objectType,
        };
      },
      afterRequest: (data: any) => {
        getNewTreeData(data.treeData);
        return {
          ...data,
        };
      },

      // 获取子节点相关
      treeChildrenDataApi: {
        params: {
          companyId: commonParams.value?.companyId,
          connect: commonParams.value?.connect,
          filter: [],
          lang: commonParams.value?.lang,
          loadAll: false,
          loadAllStructure: false,
          paraList: JSON.stringify(paraList),
          params: {},
          userId: commonParams.value?.user_id,
        },
      },
      beforeRequestChildren: () => {
        return {
          treeViewName: userData.value?.treeView,
          objectType: userData.value?.objectType,
        };
      },
      afterRequestChildren: (data: any) => {
        getNewTreeData(data.loadData);
        return {
          ...data,
        };
      },
    });

    // 递归处理数据结构
    const getNewTreeData = treeData => {
      for (let i = 0, leni = treeData.length; i < leni; i++) {
        let item = treeData[i];
        if (item.value3 == userData.value?.objectType) {
          item.disabled = false;
        } else {
          item.disabled = true;
        }
        if (item.children && item.children.length) {
          getNewTreeData(item.children);
        }
      }
    };

    const handleChange = (value: any) => {
      formState.receiverId = value;
    };

    const formCtrl: any = ref('');

    const handleOk = () => {
      if (btnLoading.value) return;
      btnLoading.value = true;
      console.log(formCtrl.value);
      formCtrl.value
        ?.validate()
        .then(async () => {
          const data = await useHttp({
            url: '/api/platform-base-workflow/admin/flow/flowEntry/processTransfer',
            method: 'post',
            params: {
              transferorName: userData.value[`USER_ALL_NAME`],
              transferorId: userData.value[`EID`],
              receiverId: formState.receiverId?.value,
              lang: commonParams.value?.lang,
              connect: commonParams.value?.connect,
              companyId: commonParams.value?.companyId,
            },
          });
          if (data.code == 200 && data.success) {
            message.success(data.msg);
            visible.value = false;
            btnLoading.value = false;
            emit('processTransferSuccess');
            handleCancel();
          } else {
            message.error(data.msg);
            btnLoading.value = false;
          }
        })
        .catch(() => {
          btnLoading.value = false;
        });
    };
    const handleCancel = () => {
      userData.value = {};
      formState.receiverId = '';
    };
    return {
      t,
      btnLoading,
      handleOk,
      handleCancel,
      visible,
      show,
      formState,
      userData,
      lazyProps,
      handleChange,
      getPopupContainer,
      formCtrl,
    };
  },
});
</script>
<style lang="less" scoped>
@import '@/theme/default/variables.less';
.TransferProcess-modal {
  .exclamation-icon {
    font-size: 16px;
    color: @normal-color;
    margin-left: 4px;
    &:hover {
      color: @info-color;
    }
  }
  .card-title {
    font-size: 16px;
    font-weight: bold;
    &::before {
      content: '';
      width: 3px;
      height: 16px;
      background: @modal-formgroup-color;
      margin-right: 2px;
      display: inline-block;
    }
  }
}
</style>
