<template>
  <div class="workflow-select-user">
    <a-card class="workflow-card">
      <template #title>
        <a-typography-title :level="5" style="margin: 0">
          {{ $t("lang.workflowSelectUser.approve") }}
        </a-typography-title>
      </template>

      <a-form :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }" class="workflow-form">
        <div v-if="userTaskDtos.length === 0 && workFlow.workflowType !== 'Auto'">
          <a-form-item :label="$t('lang.workflowSelectUser.approveUser')">
            <div class="user-list">
              <div v-for="applyUser in applyUsers" :key="applyUser.id" class="user-item">
                <div class="user-content">
                  <a-button shape="circle" class="remove-btn" danger @click="removeApplyUser(applyUser)">
                    <delete-outlined />
                  </a-button>
                  <AuthImage :auth-src="getImgSrc(applyUser.imageName)" class="user-avatar" />
                  <a-typography-text strong>{{ applyUser.name }}</a-typography-text>
                </div>
              </div>
              <div class="add-box" @click="addApplyUser()">
                <a-button shape="circle" size="large" class="add-btn">
                  <plus-outlined />
                </a-button>
              </div>
            </div>
          </a-form-item>
        </div>

        <div v-for="userTaskDto in userTaskDtos" :key="userTaskDto.id">
          <a-form-item :label="userTaskDto.name">
            <div class="user-list">
              <div v-for="applyUser in userTaskDto.assignees" :key="applyUser.id" class="user-item">
                <div class="user-content">
                  <a-button shape="circle" class="remove-btn" danger @click="removeApplyUser(applyUser, userTaskDto)">
                    <delete-outlined />
                  </a-button>
                  <AuthImage :auth-src="getImgSrc(applyUser.imageName)" class="user-avatar" />
                  <a-typography-text strong>{{ applyUser.name }}</a-typography-text>
                </div>
              </div>
              <div v-if="userTaskDto.multipleInstance || userTaskDto.assignees.length < 1" class="add-box">
                <a-button shape="circle" size="large" class="add-btn" @click="addApplyUser(userTaskDto)">
                  <plus-outlined />
                </a-button>
              </div>
            </div>
          </a-form-item>
        </div>

        <a-form-item :label="$t('lang.workflowSelectUser.copyUser')">
          <div class="user-list">
            <div v-for="copyUser in copyUsers" :key="copyUser.id" class="user-item">
              <div class="user-content">
                <a-button shape="circle" class="remove-btn" danger @click="removeCopyUser(copyUser)">
                  <delete-outlined />
                </a-button>
                <AuthImage :auth-src="getImgSrc(copyUser.imageName)" class="user-avatar" />
                <a-typography-text strong>{{ copyUser.name }}</a-typography-text>
              </div>
            </div>
            <div class="add-box" @click="addCopyUser">
              <a-button shape="circle" size="large" class="add-btn">
                <plus-outlined />
              </a-button>
            </div>
          </div>
        </a-form-item>
      </a-form>
      <a-button type="primary" style="margin:0 0 8px 16px;" @click="apply">
        <save-outlined />
        {{ $t("lang.workflowSelectUser.submit") }}
      </a-button>
    </a-card>

    <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';
import { defineComponent } from 'vue';
import {
  DeleteOutlined,
  PlusOutlined,
  SaveOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';

export default defineComponent({
  components: {
    AuthImage,
    DeleteOutlined,
    PlusOutlined,
    SaveOutlined,
    UserOutlined,
  },

  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.getThumbnailImageSrc(_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>
.workflow-select-user {
  padding: 4px 0;
  background-color: #f8f8f8;
}

.workflow-card {
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.workflow-form {
  margin-top: 16px;
}

.user-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 6px;
}

.user-item {
  position: relative;
  width: 100px;
  text-align: center;
  background: #fff;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.user-item:hover {
  transform: translateY(-4px);
}

.user-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.remove-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  z-index: 1;
  width: 28px;
  height: 28px;
  padding: 0;
}

.user-avatar {
  width: 72px;
  height: 72px;
  border-radius: 50%;
  margin-bottom: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15);
}

.add-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.add-box:hover {
  border-color: #4096ff;
  background-color: #e6f4ff;
}

.add-btn {
  width: 60px;
  height: 60px;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.table-box {
  margin: 16px 0;
}

:deep(.ant-card-body) {
  padding: 0 !important;
}
</style>