<template>
  <div class="am-main-view d-flex flex-column">
    <!--审批意见-->
    <div class="d-flex py-2">
      <span class="flex-1-dhcc">审批意见：</span>
      <el-radio-group v-model="buttonIndex" class="am-radio am-flex-8" @change="radioChange(buttonIndex)">
        <div v-for="(button, index) in buttonDatas" :key="index">
          <el-radio :label="index" :id="index">{{ button.btnName }} </el-radio>
        </div>
        <br />
      </el-radio-group>
    </div>
    <!--提交至-->
    <div class="d-flex align-items-center py-2" v-if="isShowUserSelect">
      <span class="flex-1-dhcc">提交至：</span>
      <el-select multiple v-model="userInfo" filterable placeholder="请选择" :disabled="userInfoDisabled" class="am-flex-2" @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 class="am-flex-6"></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 class="d-flex align-items-center py-2" v-if="false">
      <span class="flex-1-dhcc">通知知会人员：</span>
      <div class="d-flex flex-wrap align-items-center am-flex-8">
        <div class="d-flex align-items-center am-selected-user" v-for="item of approvalUser" :key="item.id" @click="removeUser(item)">
          {{ item.label || "" }}
          <i class="el-icon-close" />
        </div>
        <div class="am-add-user" @click="openUserModal = true">
          <i class="el-icon-plus" />
        </div>
      </div>
    </div>
    <!--添加附件-->
    <div class="d-flex  py-2">
      <span class="flex-1-dhcc">添加附件：</span>
      <am-upload-files-row class="am-flex-8 w-0-dhcc" :inst-id="this.instId" :node-id="this.nodeId" @listChange="listChange" ref="uploadFilesRow" />
    </div>
    <!--人员选择弹窗-->
    <el-dialog title="请选择人员" :append-to-body="true" :visible.sync="openUserModal" @closed="onModalClosed" width="80%">
      <approval-select-user :parent="this" :selectedUser="approvalUser" @userChange="userChange" ref="selectUserView" />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import TitleText from "@/views/TitleText.vue";
import E from "wangeditor";
import { Dialog, Dropdown, DropdownItem, DropdownMenu, Option, Radio, RadioGroup, Select } from "element-ui";
import ApprovalSelectUser from "@/components/approval-process/ApprovalSelectUser.vue";
import { Emit, Watch } from "vue-property-decorator";
import UploadFilesRow from "@/views/UploadFilesRow.vue";
import apiService from "@/services/api.service";
import flowProcessApi from "@/constants/api/ebtrust-project/flow-process.api";
import { DataInput, DataOutput } from "@/model";
import { Code } from "@/constants/enum/code.enum";
/**
 * @Description: 审批附件库页面
 * @author LiuBo
 * @date 2021/1/27
 * @time 14:35
 */
@Component({
  name: "ApprovalOpinionInput",
  components: {
    "am-upload-files-row": UploadFilesRow,
    ApprovalSelectUser,
    "title-text": TitleText,
    "el-select": Select,
    "el-radio": Radio,
    "el-radio-group": RadioGroup,
    "el-dropdown": Dropdown,
    "el-dropdown-menu": DropdownMenu,
    "el-dropdown-item": DropdownItem,
    "el-dialog": Dialog,
    "el-option": Option
  }
})
export default class ApprovalOpinionInput extends Vue {
  editor: any; // 富媒体编辑器组件对象
  opinion: any = 0; // 审批意见
  textCount = 0; // 意见总数
  approvalUser = []; // 审批人员
  openUserModal = false; // 打开人员选择弹窗
  @Watch("openUserModal")
  reCheckUser(isOpen: boolean) {
    if (!isOpen) return;
    this.$nextTick(() => {
      (this.$refs.selectUserView as any).reCheckUser(this.approvalUser);
    });
  }
  buttonDatas: any[] = []; // 按钮数组
  buttonData: any = {}; // 选择的按钮数据
  buttonIndex = -1; // 选择的按钮数据
  userOptions: any[] = []; // 当前选项的办理人信息
  userInfo: any = []; // 当前选项的人员信息
  userInfoDisabled = false; // 当前选项的人员信息是否禁用
  isShowUserSelect = true; // 是否显示人员选择框
  instId = ""; // instId
  nodeId = ""; // nodeId
  /**
   * @Description: 初始化富媒体编辑器
   * @author LiuBo
   * @date 2021/1/31
   * @time 10:31
   */
  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 LiuBo
   * @date 2021/2/3
   * @time 14:24
   */
  private getOpinion(): string {
    return this.editor.txt.html();
  }

  /**
   * @Description: 文件数组改变事件
   * @author GuoXuHui
   * @date 2021-04-08
   * @time 14:58
   */
  @Emit("listChange")
  listChange(listData: any[]) {
    return listData;
  }
  /**
   * @Description: 选择常用语句的回调函数
   * @author LiuBo
   * @date 2021/2/3
   * @time 15:16
   */
  onOpinion(opinion: string) {
    this.editor.txt.html(`<p>${opinion}</p>`);
  }
  /**
   * @Description: 移除选中用户
   * @author LiuBo
   * @date 2021/2/3
   * @time 20:48
   */
  removeUser(item: any) {
    const idx = this.approvalUser.findIndex((value: any) => value.id === item.id);
    this.approvalUser.splice(idx, 1);
  }
  /**
   * @Description: 当人员选择框关闭的时候触发
   * @author LiuBo
   * @date 2021/2/4
   * @time 10:51
   */
  onModalClosed() {
    const selectUserView: any = this.$refs.selectUserView;
    selectUserView.filterText = ""; // 清空过滤条件
  }
  mounted(): void {
    this.initEdit();
  }
  beforeDestroy() {
    // 销毁编辑器
    this.editor.destroy();
    this.editor = null;
  }

  /**
   * @Description: 初始化其他数据
   * @author GuoXuHui
   * @date 2021-07-13 COMMU
   * @time 16:21
   */
  initOtherData(taskInfo: any, instId: string, taskId: string, flowState: string) {
    this.instId = instId;
    this.nodeId = taskId;
    switch (flowState) {
      case "COMMU":
        this.commuData();
        break;
      default:
    }
  }
  /**
   * @Description: 征询任务
   * @author GuoXuHui
   * @date 2021-07-13
   * @time 16:25
   */
  commuData() {
    const nextNodes = [];
    nextNodes.push({
      btnName: "协作反馈",
      btnId: "nextcommu"
    });
    this.buttonSwitch(nextNodes);
    this.$nextTick(() => {
      (this.$refs.uploadFilesRow as any).initData(this.instId, this.nodeId);
    });
  }
  /**
   * @Description: 初始化参数并填充
   * @author guoxuhui
   * @date 2021-03-09
   * @time 15:35
   */
  initData(taskInfo: any, instId: string, taskId: string): void {
    this.instId = instId;
    this.nodeId = taskInfo.nodeId;
    this.$nextTick(() => {
      (this.$refs.uploadFilesRow as any).initData(this.instId, this.nodeId);
    });
    // 调用接口传参并返回
    let buttons = JSON.parse(JSON.stringify(taskInfo.buttons));
    buttons = buttons.filter((item: any) => item.btnId !== "commu"); // 删除协办按钮
    if (buttons) {
      // 调用预提交接口
      const flag = !!(
        taskInfo &&
        buttons &&
        buttons.find((item: any) => {
          return item.btnId === "agree";
        })
      );
      if (flag) {
        const dataInput: DataInput<any> = new DataInput<any>({
          data: {
            instId: instId,
            taskId: taskId
          }
        });
        apiService.general(flowProcessApi.approval.selectSubNode, undefined, dataInput).then((dataOutput: DataOutput<any>) => {
          if (dataOutput.code === Code.SUCCESS.code) {
            const data: any[] = dataOutput.data;
            const nextNodes: any[] = [];
            if (data.length > 0) {
              buttons = buttons.filter((item: any) => item.btnId !== "agree"); // 删除提交按钮
            }
            data.forEach(value => {
              nextNodes.push({
                btnName: value.nodeName,
                btnId: "agree",
                nodeId: value.nodeId,
                nodeName: value.nodeName,
                nodeType: value.nodeType,
                users: value.users
              });
            });

            buttons = nextNodes.concat(JSON.parse(JSON.stringify(buttons)));
            this.buttonSwitch(buttons);
          } else {
            this.$message(dataOutput.msg);
          }
        });
      } else {
        // 转换按钮
        this.buttonSwitch(buttons);
      }
    }
  }

  /**
   * @Description: 按钮框点击
   * @author GuoXuHui
   * @date 2021-07-11
   * @time 14:59
   */
  selectUserModal(event: any) {
    if (this.buttonData.btnId === "commu") {
      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-03-10
   * @time 13:54
   */
  buttonSwitch(buttons: any[]) {
    this.buttonDatas = buttons;
  }
  /**
   * @Description: 按钮变更事件
   * @author guoxuhui
   * @date 2021-03-10
   * @time 13:47
   */
  radioChange(idx: any) {
    this.isShowUserSelect = true;
    this.userInfoDisabled = false;
    this.userOptions = [];
    this.buttonData = this.buttonDatas[this.buttonIndex];
    const data = this.buttonData;
    this.userInfo = [];
    if (data.btnId === "agree") {
      if (data.users && data.users.length > 0) {
        this.userOptions = data.users;
        if (data.users.length === 1) {
          data.users.forEach((v: any) => {
            this.userInfo.push(v.id); // 暂时不付默认值
          });
        }
      } else {
        this.isShowUserSelect = false;
      }
    } else if (data.btnId === "commu") {
      this.isShowUserSelect = true;
    } else {
      this.isShowUserSelect = false;
    }
  }
}
</script>

<style scoped lang="scss">
$border: 1px #e4e4e4 solid;
.am-main-view {
  border: $border;
  padding: 1rem;
  & span {
    font-size: 14px;
    color: #333333;
  }
  ::v-deep .w-e-text-container {
    height: 100%;
  }
}
.am-radio {
  ::v-deep .el-radio__label {
    font-size: 13px;
    color: #333333;
  }
}
.am-flex-2 {
  flex: 2;
}
.am-flex-6 {
  flex: 6;
}
.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;
    }
  }
}
/**选中的知会人员样式*/
.am-selected-user {
  position: relative;
  padding: 0.3rem 2rem 0.3rem 0.5rem;
  margin: 0.3rem 0.6rem 0.3rem 0;
  border: 1px #e8e8e8 solid;
  border-radius: 2px;
  font-size: 14px;
  color: #808080;
  & > i {
    position: absolute;
    right: 0.25rem;
    font-size: 18px;
    font-weight: 500;
    &:active {
      opacity: 0.7;
    }
  }
}
.am-add-user {
  display: flex;
  padding: 0.5rem;
  align-items: center;
  justify-content: center;
  border: 1px #2858d6 solid;
  border-radius: 5px;
  &:active {
    background-color: #f5f5f5;
  }
}
::v-deep .el-dialog__wrapper {
  z-index: 9999999 !important;
}
::v-deep .el-dialog__body {
  padding-top: 0.5rem;
  padding-bottom: 1rem;
}
::v-deep .w-e-toolbar {
  padding-right: 20px;
}
</style>
