<template>
  <div class="d-flex flex-column px-4 am-body">
    <div class="d-flex flex-column flex-1-dhcc">
      <div class="d-flex align-items-center flex-1-dhcc py-2">
        <span class="flex-1-dhcc">提交至：</span>
        <el-select multiple v-model="userInfo" filterable placeholder="请选择" :disabled="userInfoDisabled" class="am-flex-8 w-0-dhcc" @focus="selectUserModal">
          <el-option v-for="(item, index) in userOptions" :key="index" :label="item.name" :value="item.id">{{ `${item.name}(${item.code})` }}</el-option>
        </el-select>
      </div>
      <div>
        <div class="d-flex py-2">
          <span class="flex-1-dhcc">意见描述：</span>
          <div class="am-edit-view w-0-dhcc">
            <div id="toolbar-container">
              <el-dropdown class="am-title-dropdown" @command="onOpinion">
                <span class="am-title-btn">选择常用语句<i class="el-icon-arrow-down el-icon--right"></i> </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="同意">同意</el-dropdown-item>
                  <el-dropdown-item command="退回">退回</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div id="text-container">
              <span class="am-count">{{ textCount }}/500</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="d-flex align-items-center justify-content-end mt-2">
      <el-button size="mini" class="mr-3" @click="parent.openCommuDialog = false">取消</el-button>
      <el-button size="mini" type="primary" @click="SendCommu">确定</el-button>
    </div>
    <!--人员选择弹窗-->
    <el-dialog title="请选择人员" :append-to-body="true" :visible.sync="openUserModal" width="60%">
      <approval-select-user :parent="this" @userChange="userChange" ref="selectUserView" />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import { Option, Button, Dialog, Select, DropdownItem, DropdownMenu, Dropdown } from "element-ui";
import ApprovalSelectUser from "@/components/approval-process/ApprovalSelectUser.vue";
import E from "wangeditor";
import { DataInput, DataOutput } from "@/model";
import apiService from "@/services/api.service";
import flowProcessApi from "@/constants/api/ebtrust-project/flow-process.api";
import { Code } from "@/constants/enum/code.enum";

@Component({
  name: "CollaborationPopup",
  components: {
    "el-select": Select,
    "el-dialog": Dialog,
    "el-button": Button,
    "el-option": Option,
    "el-dropdown": Dropdown,
    "el-dropdown-menu": DropdownMenu,
    "el-dropdown-item": DropdownItem,
    ApprovalSelectUser
  }
})
export default class CollaborationPopup extends Vue {
  @Prop() parent: any; // 父组件
  userInfo: any = []; // 当前选项的人员信息
  userInfoDisabled = false; // 当前选项的人员信息是否禁用
  buttonIndex = -1; // 选择的按钮数据
  userOptions: any[] = []; // 当前选项的办理人信息
  openUserModal = false; // 打开人员选择弹窗
  editor: any; // 富媒体编辑器组件对象
  opinion: any = 0; // 审批意见
  textCount = 0; // 意见总数
  userIds = ""; // 意见总数
  mounted(): void {
    this.initEdit();
  }
  initEdit() {
    const editor = (this.editor = new E("#toolbar-container", "#text-container")); // 传入两个元素
    // 配置菜单栏，设置不需要的菜单
    editor.config.excludeMenus = ["strikeThrough", "link", "list", "todo", "justify", "quote", "emoticon", "image", "video", "table", "code", "splitLine", "undo", "redo"];
    editor.config.onchange = (newHtml: any) => {
      this.onTextCount();
      // if (newHtml.length > 1000) {
      //   console.log(newHtml);
      // } else {
      //   this.textCount = newHtml.length;
      // }
      // this.textCount = newHtml.length;
    };
    editor.create();
  }
  onTextCount() {
    this.textCount = this.editor?.txt?.html()?.length || 0;
  }
  /**
   * @Description: 按钮框点击
   * @author GuoXuHui
   * @date 2021-07-11
   * @time 14:59
   */
  selectUserModal(event: any) {
    setTimeout(() => {
      this.openUserModal = true;
    }, 200);
  }

  /**
   * @Description: 人员变更
   * @author GuoXuHui
   * @date 2021-07-12
   * @time 15:59
   */
  userChange(data: any[]) {
    this.userOptions = [];
    this.userInfo = [];
    const users: any[] = [];
    data.forEach((value, index, array) => {
      users.push({
        code: value.account,
        id: value.userId,
        name: value.fullname,
        type: "user"
      });
    });
    this.userOptions = users;
    this.userOptions.forEach((v: any) => {
      this.userInfo.push(v.id); // 暂时不付默认值
    });
  }

  /**
   * @Description: 发送协助
   * @author GuoXuHui
   * @date 2021-07-14
   * @time 15:19
   */
  SendCommu() {
    const promise = Promise.resolve();
    promise
      .then(() => this.dataVerify())
      .then(() => this.submitData())
      .catch(data => {
        if (data && data.msg) {
          this.$message(data.msg);
        }
      })
      .finally(() => {});
  }
  private dataVerify() {
    // 数据校验
    return new Promise((resolve, reject) => {
      // 人员信息暂不校验
      const userInfo: any[] = this.userInfo;
      if (!userInfo.length) {
        return reject({ msg: "请选择协作人员" });
      }
      this.opinion = this.editor.txt.html();
      if (!this.opinion) {
        // 请输入审批意见
        return reject({ msg: "请填写意见描述" });
      } else if (this.opinion.trim && !this.opinion.trim()) {
        return reject({ msg: "填写的意见描述不能为空" });
      } else if (this.opinion.length > 500) {
        return reject({ msg: "填写的意见描述不能超出500字" });
      }
      const userOptions = this.userOptions;
      if (userInfo && userInfo.length > 0 && userOptions && userOptions.length > 0) {
        this.userIds = "";
        userInfo.forEach((value: any) => {
          const find = userOptions.find((value1: any) => value1.id === value);
          if (find) {
            this.userIds = this.userIds + find.id;
            this.userIds = this.userIds + ",";
          }
        });
        this.userIds = this.userIds.substring(0, this.userIds.length - 1);
      } else {
        this.userIds = "";
      }
      resolve();
    });
  }
  private popUps() {
    return new Promise((resolve, reject) => {
      return this.$amConfirm(
        "确认是否提交协作？",
        "提示",
        () => {
          return resolve();
        },
        () => {}
      );
    });
  }
  private submitData() {
    return new Promise((resolve, reject) => {
      return this.commuOperation(resolve, reject);
    });
  }
  /**
   * @Description: 协作反馈
   * @author GuoXuHui
   * @date 2021-07-12
   * @time 17:40
   */
  commuOperation(resolve: (value?: any) => void, reject: (reason?: any) => void) {
    const dataInput: DataInput<any> = new DataInput<any>({
      data: {
        instId: this.parent.instId,
        taskId: this.parent.taskId,
        defId: this.parent.taskInfo.defId || this.parent.taskInfo.procDefId,
        opinion: this.opinion,
        userId: this.userIds
      }
    });
    this.$amLoading.open();
    apiService.general(flowProcessApi.approval.communicate, undefined, dataInput).then((dataOutput: DataOutput<any>) => {
      this.$amLoading.close(this);
      if (dataOutput.code === Code.SUCCESS.code) {
        if (dataOutput.data) {
          const parse = JSON.parse(dataOutput.data);
          if (parse.state) {
            this.$message("协作消息已发送，请耐心等待反馈!");
            this.parent.collaborationSent();
            this.parent.openCommuDialog = false;
            resolve();
          } else {
            this.$message(parse.message);
          }
        }
      } else {
        this.$message(dataOutput.msg);
      }
    });
  }
  /**
   * @Description: 选择常用语句的回调函数
   * @author LiuBo
   * @date 2021/2/3
   * @time 15:16
   */
  onOpinion(opinion: string) {
    this.editor.txt.html(`<p>${opinion}</p>`);
  }
}
</script>

<style lang="scss" scoped>
$border: 1px #e4e4e4 solid;
::v-deep .w-e-text-container {
  height: 100%;
}
.am-body {
}
.am-over {
  overflow: auto;
  height: 500px;
  min-width: 200px;
}
.am-userInfo-body {
  width: 200px;
}
.am-title-body {
}
.am-body-1 > div {
  border: 1px #e4e4e4 solid;
}
.am-button-err {
  padding: 3px !important;
  font-size: 5px;
}
.am-flex-8 {
  flex: 8;
}
.am-edit-view {
  border: $border;
  flex: 8;
  #toolbar-container {
    display: flex;
    align-items: center;
    position: relative;
    border-bottom: $border;
    .am-title-dropdown {
      position: absolute;
      right: 1rem;
    }
    .am-title-btn {
      color: #2858d6;
      font-size: 14px;
      cursor: pointer;
      user-select: none;
      &:active {
        opacity: 0.7;
      }
    }
  }
  #text-container {
    position: relative;
    height: 200px;
    overflow-y: auto;
    padding-bottom: 1rem;
    .am-count {
      position: absolute;
      right: 0.5rem;
      bottom: 0.25rem;
      z-index: 20000;
    }
  }
}
</style>
