<template>
  <div>
    <div class="panel panel-default">
      <div class="panel-heading">
        {{ $t("lang.workflowSelectUser.approve") }}
      </div>
      <div class="panel-body">
        <div class="row">
          <div class="form-horizontal">
            <div
              v-if="userTaskDtos.length==0 && workFlow.workflowType != 'Auto'"
              class="form-group"
            >
              <label class="col-xs-5 col-sm-4 col-md-3 col-lg-2 control-label img-label">
                {{ $t("lang.workflowSelectUser.approveUser") }}
              </label>
              <div class="col-xs-7 col-sm-8 col-md-9 col-lg-10">
                <div
                  v-for="applyUser in applyUsers"
                  :key="applyUser.id"
                  class="img-box"
                >
                  <div>
                    <span
                      class="glyphicon glyphicon-trash remove-icon"
                      @click="removeApplyUser(applyUser)"
                    />

                    <AuthImage
                      :auth-src="getImgSrc(applyUser.imageName)"
                      class="img-circle"
                    />

                    {{ applyUser.name }}
                  </div>
                </div>
                <div
                  class="add-box"
                  @click="addApplyUser()"
                >
                  <span
                    class="glyphicon glyphicon-plus add-icon"
                    aria-hidden="true"
                  />
                </div>
              </div>
            </div>

            <div
              v-for="userTaskDto in userTaskDtos"
              :key="userTaskDto.id"
              class="form-group"
            >
              <label class="col-xs-5 col-sm-4 col-md-3 col-lg-2 control-label img-label">
                {{ userTaskDto.name }}
              </label>
              <div class="col-xs-7 col-sm-8 col-md-9 col-lg-10">
                <div
                  v-for="applyUser in userTaskDto.assignees"
                  :key="applyUser.id"
                  class="img-box"
                >
                  <div>
                    <span
                      class="glyphicon glyphicon-trash remove-icon"
                      @click="removeApplyUser(applyUser,userTaskDto)"
                    />
                    <AuthImage
                      :auth-src="getImgSrc(applyUser.imageName)"
                      class="img-circle"
                    />
                    {{ applyUser.name }}
                  </div>
                </div>
                <div
                  v-if="userTaskDto.multipleInstance || userTaskDto.assignees.length < 1"
                  class="add-box"
                  @click="addApplyUser(userTaskDto)"
                >
                  <span
                    class="glyphicon glyphicon-plus add-icon"
                    aria-hidden="true"
                  />
                </div>
              </div>
            </div>

            <div
              class="form-group"
              style="margin-top:20px;"
            >
              <label class="col-xs-5 col-sm-4 col-md-3 col-lg-2 control-label img-label">
                {{ $t("lang.workflowSelectUser.copyUser") }}
              </label>
              <div class="col-xs-7 col-sm-8 col-md-9 col-lg-10">
                <div
                  v-for="copyUser in copyUsers"
                  :key="copyUser.id"
                  class="img-box"
                >
                  <div>
                    <span
                      class="glyphicon glyphicon-trash remove-icon"
                      @click="removeCopyUser(copyUser)"
                    />
                    <AuthImage
                      :auth-src="getImgSrc(copyUser.imageName)"
                      class="img-circle"
                    />
                    {{ copyUser.name }}
                  </div>
                </div>
                <div
                  class="add-box"
                  @click="addCopyUser"
                >
                  <span
                    class="glyphicon glyphicon-plus add-icon"
                    aria-hidden="true"
                  />
                </div>
              </div>
            </div>

            <div
              class="form-group"
              style="margin-top:20px;"
            >
              <label class="col-xs-5 col-sm-4 col-md-3 col-lg-2 control-label" />
              <div class="col-xs-7 col-sm-8 col-md-9 col-lg-10">
                <button
                  type="button"
                  class="btn btn-primary"
                  @click="apply"
                >
                  {{ $t("lang.workflowSelectUser.submit") }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Modal
      v-model:show="modal"
      :full="true"
      @ok="searchDialogOk"
      @cancel="searchDialogCancel"
    >
      <InfoWindow
        ref="info"
        :info-window-no="infoWindowNo"
        :where-clause-source="whereClauseSource"
        @data-selected="dataSelected"
      />
      <template #header>
        {{ $t("lang.workflowSelectUser.chooseUser") }}
      </template>
    </Modal>

    <Modal
      v-model:show="modal2"
      :small="true"
    >
      <div class="row box">
        <div class="col-md-12">
          <div class="table-box">
            <table class="table table-condensed table-bordered table-user">
              <thead>
                <tr>
                  <th>{{ $t("lang.workflowSelectUser.userName") }}</th>
                  <th>{{ $t("lang.workflowSelectUser.userNo") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="item in currentUsers"
                  :key="item.id"
                  @click="selectCurrentUser(item)"
                >
                  <td>{{ item.name }}</td>
                  <td>{{ item.no }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <template #header>
        {{ $t("lang.workflowSelectUser.chooseUser") }}
      </template>
    </Modal>
    <Loading v-if="loading" />
  </div>
</template>
<script>

import Common from '../common/Common.js';


import AuthImage from '../widget/AuthImage.vue';

export default {

  components: {
    AuthImage, 
  },

  props: {
    // 工作流定义Id
    processDefinitionId: {
      type: String,
      default: null,
    },
    workFlow: {
      type: Object,
      default : function(){
        return null;
      },
    },
  },
  emits: ['apply'],

  data: function () {
    this.Common = Common;
    return {
      infoWindowNo: '050408',
      className: 'com.leanwo.prodog.base.model.User',
      applyUsers: [],
      copyUsers: [],
      currentUser: '',
      whereClauseSource: {
        customerDataDimensions:[{
          fieldName: 'client.id',
          dataDimensionTypeNo: '202201191757',
          defaultDataDimensionTypeValueNo: '4',
        }],
      },
      userTaskDtos: [],
      selectedUserTaskDto: '',
      currentUsers: [],
      loading: false,
      modal: false,
      modal2: false,
    };
  },

  mounted: function () {
    var _self = this;
    console.log(this.workFlow);

    $.ajax({
      url: Common.getApiURL('WorkflowResource/listUserTask'),
      type: 'post',
      dataType: 'json',
      beforeSend: function (request) {
        Common.addTokenToRequest(request);
      },
      contentType: 'application/json',
      data: _self.processDefinitionId,
      success: function (data) {
        if (data != undefined) {
          _self.userTaskDtos = data;
          _self.userTaskDtos.forEach(function (item) {
            item.assignees = [];
            item.assigneeIds = [];

            if ((item.candidateUserIds != undefined && item.candidateUserIds.length > 0) || (item.candidateGroupIds != undefined && item.candidateGroupIds.length > 0)) {
              _self.getUserByUserTask(item);
            }
          });
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        Common.processException(XMLHttpRequest, textStatus, errorThrown);
      },
    });

  },

  methods: {
    // 选择用户后
    selectCurrentUser: function (data) {
      var _self = this;
      _self.modal2 = false;
      if (_self.currentUser == 'applyUser') {
        for (var i = 0; i < _self.userTaskDtos.length; i++) {
          if (_self.userTaskDtos[i] == _self.selectedUserTaskDto) {
            if (_self.contains(_self.userTaskDtos[i].assigneeIds, data.id)) {
              continue;
            }
            _self.userTaskDtos[i].assignees.push(data);
            _self.userTaskDtos[i].assigneeIds.push(data.id);
          }
        }
        if (!_self.containsId(_self.applyUsers, data)) {
          _self.applyUsers.push(data);
        }
      } else if (_self.currentUser == 'copyUser') {
        if (!_self.containsId(_self.copyUsers, data)) {
          _self.copyUsers.push(data);
        }
      }
    },
    /**
         * 审批
         * @return {void} 
         */
    apply: function () {
      this.$emit('apply');
    },

    /**
         * 初始化数据
         * @return {void} 
         */
    initData: function () {
      var _self = this;
    },

    /**
         * 选择用户后
         * @param  {Object} modelData 用户信息
         * @return {void}           
         */
    dataSelected: function (modelData) {
      var _self = this;
      this.modal = false;
      var userId = modelData.id;
      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('userResource/getUser'),
        type: 'get',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: {
          userId: userId,
        },
        success: function (data) {
          _self.loading=false;
          if (_self.currentUser == 'applyUser') {
            for (var i = 0; i < _self.userTaskDtos.length; i++) {
              if (_self.userTaskDtos[i] == _self.selectedUserTaskDto) {
                if (_self.contains(_self.userTaskDtos[i].assigneeIds, data.id)) {
                  continue;
                }
                _self.userTaskDtos[i].assignees.push(data);
                _self.userTaskDtos[i].assigneeIds.push(data.id);
              }
            }
            if (!_self.containsId(_self.applyUsers, data)) {
              _self.applyUsers.push(data);
            }
          } else if (_self.currentUser == 'copyUser') {
            if (!_self.containsId(_self.copyUsers, data)) {
              _self.copyUsers.push(data);
            }
          }
          _self.className = 'com.leanwo.prodog.base.model.User';
          _self.whereClauseSource = {
            customerDataDimensions:[{
              fieldName: 'client.id',
              dataDimensionTypeNo: '202201191757',
              defaultDataDimensionTypeValueNo: '4',
            }],
          };
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          _self.className = 'com.leanwo.prodog.base.model.User';
          _self.whereClauseSource = {
            customerDataDimensions:[{
              fieldName: 'client.id',
              dataDimensionTypeNo: '202201191757',
              defaultDataDimensionTypeValueNo: '4',
            }],
          };
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });

    },

    /**
         * 获取图片路径
         * @param  {String} imageName 图片名称
         * @return {void}           
         */
    getImgSrc: function (imageName) {
      var _self = this;
      if (imageName == undefined || imageName == '') {
        return '/static/assets/client-base-v4/image/no-image.png';
      }
      return Common.getImageSrc(_self.className, imageName);
    },

    /**
         * 添加审批人
         */
    addApplyUser: function (userTaskDto) {
      var _self = this;
      _self.selectedUserTaskDto = userTaskDto;
      _self.currentUser = 'applyUser';

      if (userTaskDto != undefined && userTaskDto.users != undefined && userTaskDto.users.length > 0) {
        _self.currentUsers = userTaskDto.users;
        _self.modal2 = true;
      } else {
        _self.initData();
        _self.modal = true;
      }
    },

    /**
         * 添加抄送人
         */
    addCopyUser: function () {
      var _self = this;
      _self.currentUser = 'copyUser';
      _self.initData();
      _self.modal = true;
    },

    /**
         * 移除审批人
         * @param  {Object} user 用户
         * @return {void}      
         */
    removeApplyUser: function (user, userTaskDto) {
      var _self = this;
      var index = userTaskDto.assignees.indexOf(user);
      if (index >= 0) {
        userTaskDto.assignees.splice(index, 1);
      }
      var i = _self.userTaskDtos.indexOf(userTaskDto);

      var j = userTaskDto.assigneeIds.indexOf(user.id);
      userTaskDto.assigneeIds.splice(j, 1);

      var k = _self.applyUsers.indexOf(user);
      if (k >= 0) {
        _self.applyUsers.splice(k, 1);
      }

      _self.userTaskDtos[i]=userTaskDto;
    },

    /**
         * 移除抄送人
         * @param  {Object} user 用户
         * @return {void}      
         */
    removeCopyUser: function (user) {
      var _self = this;
      var index = _self.copyUsers.indexOf(user);
      if (index >= 0) {
        _self.copyUsers.splice(index, 1);
      }
    },

    /**
         * 获取审批人和抄送人 供外部调用
         * @return {Object} 用户数据
         */
    getUserData: function () {
      var _self = this;
      var applyUsers = [];
      var copyUsers = [];
      _self.applyUsers.forEach(function (item) {
        applyUsers.push(item.id);
      });
      _self.copyUsers.forEach(function (item) {
        copyUsers.push(item.id);
      });

      var data = {
        applyUsers: applyUsers,
        copyUsers: copyUsers,
        userTaskDtos: _self.userTaskDtos,
      };
      return data;
    },


    /**
         * 搜索框【确定】按钮点击事件
         */
    searchDialogOk: function () {
      var _self = this;
      var selectedModelDatas = _self.$refs.info.getSelectedModelDatas();
      if (selectedModelDatas != undefined || selectedModelDatas.length > 0) {
        // 选中了数据，更新数据
        _self.dataSelected(selectedModelDatas[0]);
      }
    },

    searchDialogCancel: function () {

    },
    contains: function (arr, item) {
      if (arr == undefined || arr.length == 0 || item == undefined) {
        return false;
      }
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] == item) {
          return true;
        }
      }
      return false;
    },
    containsId: function (arr, item) {
      if (arr == undefined || arr.length == 0 || item == undefined) {
        return false;
      }
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].id == item.id) {
          return true;
        }
      }
      return false;
    },
    // 获取用户根据userTask
    getUserByUserTask: function (userTaskDto) {
      var _self = this;
      $.ajax({
        type: 'post',
        url: Common.getApiURL('userResource/getUserByUserTask'),
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(userTaskDto),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data && data.length > 0) {
            userTaskDto['users']=data;
            if (data.length == 1) {
              userTaskDto.assignees.push(data[0]);
              userTaskDto.assigneeIds.push(data[0].id);
            }
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>

<style scoped>
.img-label {
    height: 80px;
    line-height: 80px;
    padding-top: 0px !important;
}

.img-box {
    width: 60px;
    height: 80px;
    float: left;
    text-align: center;
    margin-right: 20px;
}

.img-box div img {
    width: 60px;
    height: 60px;
}

.add-box {
    width: 60px;
    height: 60px;
    float: left;
    border-radius: 30px;
    border: 1px #999 dashed;
    text-align: center;
    margin-top: 20px;
}

.add-box:hover {
    cursor: pointer;
    background-color: #ccc;
}

.add-icon {
    width: 60px;
    height: 60px;
    color: #aaa;
    font-size: 40px;
    line-height: 60px;
    position: relative;
    top: -1px;
}

.remove-icon {
    color: red;
    position: relative;
    top: 10px;
    right: -30px;
    cursor: pointer;
}

.table-box td,
th {
    text-align: center;
}
</style>