<template>
  <div v-if="userSelectDefine.editable">
    <div>{{ userSelectDefine.nodeName }}</div>

    <div v-if="optionalRange === 'ALL'">
      <p
        v-if="check && (userIdsAll == null || userIdsAll.length == 0)"
        class="text-danger"
      >
        必选字段*
      </p>
      <!-- <v-select
        v-model="userIdsAll"
        :reduce="(user) => user.id"
        :options="userListAll"
        label="text"
        :multiple="multiSelect"
        @search="listInGroupCompanyByCondition"
      /> -->
      <a-select
        v-model:value="userIdsAll"
        style="width: 100%"
        show-search
        :options="userListAll"
        :filter-option="false"
        :not-found-content="fetching ? undefined : null"
        :field-names="{ label: 'text', value: 'id' }"
        @search="handleChange"
      >
        <template v-if="fetching" #notFoundContent>
          <a-spin size="small" />
        </template>
      </a-select>
    </div>
    <div v-else-if="optionalRange === 'USER'">
      <p
        v-if="check && (userIds == null || userIds.length == 0)"
        class="text-danger"
      >
        必选字段*
      </p>
      <v-select
        v-model="userIds"
        :reduce="(optionalUser) => optionalUser.userId"
        :options="optionalUsers"
        label="text"
        :multiple="multiSelect"
      />
    </div>
    <div v-else>
      <p
        v-if="
          check &&
            (userIdsOfUserGroup == null || userIdsOfUserGroup.length == 0)
        "
        class="text-danger"
      >
        必选字段*
      </p>
      <v-select
        v-model="userIdsOfUserGroup"
        :reduce="(user) => user.id"
        :options="userListOfUserGroup"
        label="text"
        :multiple="multiSelect"
      />
    </div>
  </div>
</template>


<script>
import Common from '../common/Common.js';

import UserResource from '../api/base/UserResource.js';
import GroupUserResource from '../api/base/GroupUserResource.js';

import vSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';
import { Notify, Uuid } from 'pc-component-v3';

export default {

  components: {
    vSelect,
  },

  props: {
    
    userSelectDefine: {
      type: Object,
      default : function(){
        return null;
      },
    },
  },

  data: function () {
    return {
      // multiSelect
      multiSelect: true,
      // 选择范围: 全公司(ALL)、指定成员(USER)、用户组(USER_GROUP)
      optionalRange: 'ALL',
      // 可选用户
      optionalUsers: [],
      // 可选用户组
      optionalUserGroups: [],

      // 选择的用户Id集合（指定成员）
      userIds: [],

      // 用户集合（全公司）
      userListAll: [],
      // 选择的用户Id集合（全公司）
      userIdsAll: [],

      // 用户集合（指定用户组）
      userListOfUserGroup: [],
      // 选择的用户Id集合（指定用户组）
      userIdsOfUserGroup: [],

      check: false, // 数据校验
      fetching: false, // 数据校验
    };
  },

  mounted: function () {
    this.initData();
  },

  methods: {
    handleChange: Common.debounce(function (value) {
      this.copyUserList = [];
      this.fetching = true;
      this.listInGroupCompanyByCondition(value);
    },500),
    /**
     * 根据姓名获取用户集合
     */
    listInGroupCompanyByCondition: function (search) {
      let _self = this;
      const searchQueryParam = {
        range: {
          start: 0,
          length: 1000,
        },
        conditional: search,
      };

      //修复审批节点选择人员显示文件编码bug
      var selectList;
      if (
        this.userIdsAll != undefined &&
        this.userListAll != undefined &&
        this.userListAll.length > 0
      ) {
        this.userListAll.forEach(function (value, index) {
          if (value.id == _self.userIdsAll) {
            selectList = value;
          }
        });
      }
      UserResource.listInGroupCompanyByCondition(searchQueryParam).then(
        successData => {
          if (successData != null && successData.resultList != null) {
            successData.resultList.forEach(function (user) {
              user.text = user.name + '(' + user.no + ')' + '(';
              if(user.organizations != null && user.organizations.length > 0){
                let isFirst = true;
                user.organizations.forEach(item => {
                  if(isFirst === true){
                    user.text += item.organizationName;
                    isFirst = false;
                  }else{
                    user.text += (',' +  item.organizationName);
                  }
                });
              }
              user.text += ')';
            });
            this.userListAll = successData.resultList;
          } else {
            this.userListAll = [];
          }
          //修复审批节点选择人员显示文件编码bug
          var result = this.userListAll.some(
            item => item.id === _self.userIdsAll,
          );
          if (selectList != undefined && !result) {
            this.userListAll.push(selectList);
          }
          this.fetching = false;
        },
        errorData => {
          this.fetching = false;
          Common.processException(errorData);
        },
      );
    },

    /**
     * 根据用户组Id集合获取该组内所有用户
     */
    listUserByGroupIds: function () {
      if (
        this.optionalUserGroups == null ||
        this.optionalUserGroups.length == 0
      ) {
        const title = this.userSelectDefine.nodeName + '审批节点异常';
        const content = '未定义用户组。';
        Notify.error(title, content, false);
        return;
      }
      const groupIds = [];
      this.optionalUserGroups.forEach(optionalUserGroup => {
        groupIds.push(optionalUserGroup.groupId);
      });

      GroupUserResource.listUserByGroupIds(groupIds).then(
        successData => {
          if (successData != null) {
            successData.forEach(function (item) {
              item.text = item.name + ',' + item.organizationName;
            });
            this.userListOfUserGroup = successData;
          } else {
            const title = this.userSelectDefine.nodeName + '审批节点异常';
            const content = '根据用户组查询不到用户。';
            this.userListOfUserGroup = [];
            Notify.error(title, content, false);
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },

    initData: function () {
      this.multiSelect = this.userSelectDefine.multiSelect;
      this.optionalRange = this.userSelectDefine.optionalRange;
      this.optionalUsers = this.userSelectDefine.optionalUsers;
      this.optionalUserGroups = this.userSelectDefine.optionalUserGroups;

      if (this.optionalRange === 'ALL') {
        this.listInGroupCompanyByCondition(null, function (status) {});
      } else if (this.optionalRange === 'USER_GROUP') {
        this.listUserByGroupIds();
      }
    },

    getData: function () {
      this.check = true;

      let userSelectDto = {
        nodeId: this.userSelectDefine.nodeId,
        nodeName: this.userSelectDefine.nodeName,
        variableName: this.userSelectDefine.variableName,
      };
      if (this.userSelectDefine.editable) {
        if (this.optionalRange === 'ALL') {
          if (this.userIdsAll == null || this.userIdsAll.length == 0) {
            const message = this.userSelectDefine.nodeName + '节点未选择用户。';
            throw new Error(message);
          }
          if (Array.isArray(this.userIdsAll)) {
            userSelectDto.userIds = this.userIdsAll;
          } else {
            userSelectDto.userIds = [this.userIdsAll];
          }
        } else if (this.optionalRange === 'USER_GROUP') {
          if (
            this.userIdsOfUserGroup == null ||
            this.userIdsOfUserGroup.length == 0
          ) {
            const message = this.userSelectDefine.nodeName + '节点未选择用户。';
            throw new Error(message);
          }
          if (Array.isArray(this.userIdsOfUserGroup)) {
            userSelectDto.userIds = this.userIdsOfUserGroup;
          } else {
            userSelectDto.userIds = [this.userIdsOfUserGroup];
          }
        } else if (this.optionalRange === 'USER') {
          if (this.userIds == null || this.userIds.length == 0) {
            const message = this.userSelectDefine.nodeName + '节点未选择用户。';
            throw new Error(message);
          }
          if (Array.isArray(this.userIds)) {
            userSelectDto.userIds = this.userIds;
          } else {
            userSelectDto.userIds = [this.userIds];
          }
        } else {
          const message =
            this.userSelectDefine.nodeName +
            '节点类型定义异常，不识别的类型' +
            this.optionalRange +
            '。';
          throw new Error(message);
        }
      }
      return userSelectDto;
    },
  },
};
</script>