<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="isMultiple" 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.type === "node" ? `${item.name}` : `${item.name}(${item.code})` }}</el-option>
      </el-select>
      <div class="am-flex-6"></div>
    </div>
    <div class="d-flex py-2" v-if="isShowRejectSelect">
      <span class="flex-1-dhcc">驳回方式：</span>
      <el-radio-group v-model="rejectSelectData" class="am-radio am-flex-8">
        <div v-for="(button, index) in rejectSelectDatas" :key="index">
          <el-radio :label="button.id" :id="button.id">{{ button.name }} </el-radio>
        </div>
        <br />
      </el-radio-group>
    </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">
          <div class="am-title-dropdown">
            <span class="mr-2 am-text-btn" @click="addOpinion">添加常用语句</span>
            <el-dropdown @command="onOpinion">
              <span class="am-title-btn">选择常用语句<i class="el-icon-arrow-down el-icon--right"></i> </span>
              <el-dropdown-menu slot="dropdown">
                <div class="d-flex align-items-center mr-2 justify-content-between" v-for="(op, index) in userOpinion" v-bind:key="index">
                  <el-dropdown-item :command="`<p>${op.opinion}</p>`" class="flex-1-dhcc">
                    {{ op.opinion }}
                  </el-dropdown-item>
                  <el-button type="danger" icon="el-icon-delete" circle class="am-button-err" @click="deleteUserOpinion(op)"></el-button>
                </div>
                <el-dropdown-item command="<p>同意</p>">同意</el-dropdown-item>
                <el-dropdown-item command="<p>退回</p>">退回</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </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 { Button, Dialog, Dropdown, DropdownItem, DropdownMenu, Option, Radio, RadioGroup, Select } from "element-ui";
import ApprovalSelectUser from "@/components/approval-process/ApprovalSelectUser.vue";
import { Emit, Prop, 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";
import { userStore } from "@dhccmobile/etbc-auth-api";
import flowPostscriptInfoApi from "@/constants/api/ebtrust-asset/flow-postscript-info";
/**
 * @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-button": Button,
    "el-option": Option
  }
})
export default class ApprovalOpinionInput extends Vue {
  editor: any; // 富媒体编辑器组件对象
  opinion: any = 0; // 审批意见
  textCount = 0; // 意见总数
  approvalUser = []; // 审批人员
  openUserModal = false;
  private detailsUser: any;
  private userOpinion: any[] = [{ opinion: "123123123", id: "123123123" }];
  //当前登录人详情

  // 打开人员选择弹窗
  @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; // 是否显示人员选择框
  isShowRejectSelect = false; // 是否显示驳回路径选择
  rejectSelectData = "normal"; // 驳回路径默认数据
  rejectSelectDatas = [
    { id: "normal", name: "按照流程图方式驳回  (驳回后重新按流程图审批)" },
    { id: "direct", name: "直来直往   (驳回后重新提交则跳过中间节点直接到当前节点)" }
  ];
  instId = ""; // instId
  nodeId = ""; // nodeId
  isMultiple = true; // 是否多选
  taskInfo: any; // 数据
  @Prop() father: any; // 父对象
  /**
   * @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) {
      // } 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(opinion);
  }
  addOpinion() {
    const text = this.editor.txt.text();
    const strings = text.split("&nbsp;");
    let s1 = strings.join(" ");
    s1 = s1.trim();
    if (s1) {
      if (s1.length > 50) {
        this.$message("添加的常用语字数不能超过50字");
      } else {
        this.addUserOpinion(s1);
      }
    } else {
      this.$message("请在审批意见中填写要添加的常用语");
    }
  }
  deleteUserOpinion(data: any) {
    const dataInput: DataInput<any> = new DataInput<any>({
      data: {
        id: data.id,
        useState: "0"
      }
    });
    this.$amLoading.open();
    apiService.general(flowPostscriptInfoApi.updateById, undefined, dataInput).then((dataOutput: DataOutput<any>) => {
      this.$amLoading.close(this);
      if (dataOutput.code === Code.SUCCESS.code) {
        this.selectUserOpinion();
      } else {
        this.$message("刪除人员常用语失败");
      }
    });
  }
  /**
   * @Description: 新增常用语
   * @author guoxuhui
   * @date 2021-03-12
   * @time 10:40
   */
  private addUserOpinion(opinion: string) {
    const dataInput: DataInput<any> = new DataInput<any>({
      data: {
        userId: this.detailsUser.emplId,
        opinion: opinion
      }
    });
    this.$amLoading.open();
    apiService.general(flowPostscriptInfoApi.add, undefined, dataInput).then((dataOutput: DataOutput<any>) => {
      this.$amLoading.close(this);
      if (dataOutput.code === Code.SUCCESS.code) {
        this.$message("新增成功");
        this.userOpinion = dataOutput.data;
        this.selectUserOpinion();
      } else {
        this.$message("新增人员常用语失败");
      }
    });
  }

  /**
   * @Description: 根据userId查询
   * @author GuoXuHui
   * @date 2021-08-06
   * @time 13:38
   */
  private selectUserOpinion() {
    if (this.detailsUser) {
      const dataInput: DataInput<any> = new DataInput<any>({
        data: {
          userId: this.detailsUser.emplId
        }
      });
      this.$amLoading.open();
      apiService.general(flowPostscriptInfoApi.selectByUserId, undefined, dataInput).then((dataOutput: DataOutput<any>) => {
        this.$amLoading.close(this);
        if (dataOutput.code === Code.SUCCESS.code) {
          this.userOpinion = dataOutput.data;
        } else {
          this.$message("查询人员常用语失败");
        }
      });
    }
  }
  /**
   * @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();
    this.detailsUser = userStore.detailsUser;
  }
  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.selectUserOpinion();
    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: "协作反馈", // 辉哥版本
      btnName: "同意", //
      btnId: "nextcommu"
    });
    this.buttonSwitch(nextNodes);
    this.$nextTick(() => {
      (this.$refs.uploadFilesRow as any).initData(this.instId, this.nodeId);
    });
  }

  /**
   * @Description:
   * @author GuoXuHui
   * @date 2021-08-16
   * @time 11:36
   */
  pathInitData(pathData: any, taskInfo: any, instId: string, taskId: string) {
    let rejectNode: string[] = [];
    let rejectNodes = "";
    if (taskInfo.formValue) {
      const parse = JSON.parse(taskInfo.formValue) || {};
      if (parse.rejectNodes) {
        rejectNodes = parse.rejectNodes;
        rejectNode = parse.rejectNodes.split(",");
      } else {
        return;
      }
    }
    let bpmTaskOpinionList: any[] = pathData.bpmTaskOpinionList;
    bpmTaskOpinionList = bpmTaskOpinionList.filter(value => value.status !== "start_commu" && value.status !== "feedback");
    const isDtl = bpmTaskOpinionList.findIndex(value => value.taskKey === bpmTaskOpinionList[1].taskKey && value.status === "awaiting_check");
    if (isDtl > 1) {
      const taskKey = bpmTaskOpinionList[isDtl - 1].taskKey;
      const find = rejectNode.find(value => value === taskKey);
      if (find) {
        // 是存在的
      } else {
        taskInfo.formValueFlag = true;
        this.initData(taskInfo, instId, taskId);
      }
    } else {
      taskInfo.formValueFlag = true;
      this.initData(taskInfo, instId, taskId);
    }
  }
  /**
   * @Description: 初始化参数并填充
   * @author guoxuhui
   * @date 2021-03-09
   * @time 15:35
   */
  initData(taskInfo: any, instId: string, taskId: string): void {
    this.taskInfo = taskInfo;
    this.isShowRejectSelect = false;
    this.rejectSelectData = "normal"; // 驳回路径默认数据
    let isQuery = true;
    if (taskInfo.formValue && !taskInfo.formValueFlag) {
      const parse = JSON.parse(taskInfo.formValue) || {};
      if (parse.rejectSelect) {
        // this.isShowRejectSelect = true;
        this.rejectSelectData = parse.rejectSelect;
        if (parse.rejectNodes) {
          isQuery = false;
        }
      }
    }
    this.instId = instId;
    this.nodeId = taskInfo.nodeId;
    this.$nextTick(() => {
      this.selectUserOpinion();
      (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 && isQuery) {
        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);
            if ([...buttons].some((item: any) => item.btnId == "agree")) {
              this.buttonIndex = 0;
              this.radioChange(0);
            }
          } 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.isMultiple = true;
    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 if (data.btnId === "rejectPre") {
      this.userInfo = "";
      this.isShowUserSelect = true;
      this.isMultiple = false;
      // 获取审批路径上的节点
      this.selectNodes();
    } else {
      this.isShowUserSelect = false;
    }
  }
  selectNodes() {
    const pathData = this.father?.pathData;
    const bpmTaskOpinionList: any[] = pathData.bpmTaskOpinionList || [];
    const map = new Map();
    const arrays: any[] = []; // 数组用于返回结果
    bpmTaskOpinionList.forEach((value, index, array) => {
      if (value.status === "skip" || value.status === "backToStart" || value.status === "agree" || value.status === "reject") {
        if (this.taskInfo?.nodeId !== value.taskKey) {
          if (map.has(value.taskKey)) {
            // 如果有该key值
            map.set(value.taskKey, true);
          } else {
            map.set(value.taskKey, false); // 如果没有该key值
            arrays.push({
              code: value.taskKey,
              id: value.taskKey,
              name: value.taskName,
              type: "node"
            });
          }
        }
      }
    });
    this.userOptions = arrays;
  }
}
</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;
}
.am-text-btn {
  font-size: 14px;
  color: #2858d6;
  cursor: pointer;
  user-select: none;
  &:active {
    opacity: 0.7;
  }
}
.am-button-err {
  padding: 3px !important;
  font-size: 5px;
  width: 20px;
  height: 20px;
}
</style>
