<!-- 上一个节点选择数据 -->
<template>
  <div>
    <div>
      <div>
        <div>
          <div v-if="userSelectDefineList != null && userSelectDefineList.length > 0">{{ $t('lang.previousNodeSelectUser.selectUser') }}</div>
          <div
            v-for="userSelectDefine in userSelectDefineList"
            :key="userSelectDefine.nodeId"
          >
            <UserSelectDefine
              ref="userSelectDefine"
              :user-select-define="userSelectDefine"
            />
          </div>
        </div>

        <div>
          <div>{{ $t('lang.previousNodeSelectUser.copyUser') }}</div>
          <a-select
            v-model:value="copyUserIds"
            mode="multiple"
            style="width: 100%"
            :options="copyUserList"
            :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>
    </div>
  </div>
</template>

<script>

import Common from '../common/Common.js';
import WorkflowResource from '../api/workflow/WorkflowResource.js';


import UserSelectDefine from './UserSelectDefine.vue';

import vSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';

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

export default {

  components: {
    UserSelectDefine, vSelect,
  },
  props: {
    processInstanceId: {
      type: String,
      default: null,
    },
    taskId: {
      type: String,
      default: null,
    },
    workFlow: {
      type: Object,
      default : function(){
        return null;
      },
    },
    modelData: {
      type: Object,
      default : function(){
        return null;
      },
    },
    approveFormValue: {
      type: Array,
      default : function(){
        return null;
      },
    },
  },

  data: function () {
    this.Common = Common;
    return {
      userSelectDefineList: [],
      copyUsers: [],
      whereClause: 'organization.id IN (:EnvOrganizationIdList)',
      // 抄送人Id
      copyUserIds: [],
      copyUserList: [],
      timer: undefined,
      fetching: false,
    };
  },

  watch: {
    'approveFormValue': function () {
      this.calculatePreviousUserSelect();
    },
    'modelData': {
      handler: function (val, oldVal) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          this.reCalculatePreviousUserSelect();
        }, 1000);
      },
      //深度监听
      deep: true,

    },
  },

  mounted: function () {
    var _self = this;
    this.calculatePreviousUserSelect();
    this.listInGroupCompanyByCondition(null, function () { });
  },

  methods: {

    /**
         * 计算哪些用户选择项可以执行
         */
    calculatePreviousUserSelect: function () {
      let _self = this;

      const userSelectCalculateRequest = {
        taskId: this.taskId,
        workflowId: this.workFlow.id,
        modelData: this.modelData,
        keyValueObjects: this.approveFormValue,
      };

      WorkflowResource.calculatePreviousUserSelect(_self.processInstanceId, userSelectCalculateRequest).then(successData => {
        if (successData == null) {
          _self.userSelectDefineList.splice(0, _self.userSelectDefineList.length);
        } else {
          successData.forEach(function (item) {
            item.editable = true;
          });
          _self.userSelectDefineList = successData;
          _self.reCalculatePreviousUserSelect();
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },

    /**
         * 获取审批人的数据
         */
    getData: function () {
      let param = {
        userSelectDtos: null,
        copyUsers: null,
      };
      let userSelectDtos = [];
      let userSelectDefineList = this.$refs.userSelectDefine;
      if (userSelectDefineList != null && userSelectDefineList.length > 0) {
        for (let i = 0; i < userSelectDefineList.length; i++) {
          let userTaskDto = userSelectDefineList[i].getData();
          userSelectDtos.push(userTaskDto);
        }
        param.userSelectDtos = userSelectDtos;
      }

      if (Array.isArray(this.copyUserIds)) {
        param.copyUsers = this.copyUserIds;
      } else {
        param.copyUsers = [this.copyUserIds];
      }

      return param;
    },
    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,
      };

      console.log('copyUserIds:' + _self.copyUserIds);
      //修复审批节点选择人员显示文件编码bug
      var selectList = [];
      if (this.copyUserIds != undefined
                && this.copyUserList != undefined
                && this.copyUserList.length > 0
                && this.copyUserIds.length > 0) {
        this.copyUserList.forEach(function (value, index) {
          var id = value.id;
          _self.copyUserIds.forEach(function (item) {
            if (item == id) {
              selectList.push(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.copyUserList = successData.resultList;
        } else {
          this.copyUserList = [];
        }
        this.fetching = false;
      }, errorData => {
        this.fetching = false;
        Common.processException(errorData);
      });
    },
    /**
         * 在审批的过程中判断是否下一个节点是否需要选择用户是否显示
         */
    reCalculatePreviousUserSelect: function () {
      let _self = this;

      const userSelectCalculateRequest = {
        taskId: this.taskId,
        workflowId: this.workFlow.id,
        modelData: this.modelData,
        keyValueObjects: this.approveFormValue,
      };

      WorkflowResource.reCalculatePreviousUserSelect(_self.processInstanceId, userSelectCalculateRequest).then(successData => {
        if (successData == null) {
          _self.userSelectDefineList.splice(0, _self.userSelectDefineList.length);
        } else {
          for (var i = 0; i < _self.userSelectDefineList.length; i++) {
            var item = _self.userSelectDefineList[i];
            for (var j = 0; j < successData.length; j++) {
              var succeesItem = successData[j];
              if (item.nodeId == succeesItem.nodeId) {
                _self.userSelectDefineList[i].editable = succeesItem.editable;
                break;
              }
            }
          }
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },

  },
};
</script>

<style scoped>
</style>