<template>
  <div
    v-loading="loading"
    class="task-read"
    element-loading-text="加载中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255,255, 0.8)"
    :style="`height: ${typeCode == 'read'? '100%' : 'unset'};`"
  >
    <el-form
      ref="nextNode"
      :model="nextNode"
      class="demo-dynamic"
      label-width="110px"
    >
      <div
        :style="`max-height: ${
          typeCode ? 'unset' : '290px'
        }; overflow-y: auto; margin-bottom: 10px`"
      >
        <el-form-item
          prop="handleExplain"
          label="当前步骤"
          v-if="type === 'transfer'"
        >
          <el-input readonly v-model="nextNode.nodeName"></el-input>
        </el-form-item>
        <el-form-item
          v-if="type == 'transfer' && transferInfo.isSinglePage"
          prop="handleExplain"
          label="意见"
        >
          <el-input
            v-model="nextNode.handleExplain"
            placeholder="请填写意见"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="nextUser"
          :label="
            type === 'transfer'
              ? '转办对象'
              : configInfo.isCdjxjTaskHandle == 'true'
              ? '接收人'
              : '办理用户'
          "
        >
          <SelectUser
            :nextUser="nextNode.nextUser"
            :options="userOptions"
            :multiple="type != 'transfer' ? multiple : false"
            :mix="type != 'transfer'"
            :selectUserList="selectUserList"
            :showTooltip="showTooltip"
            :disableds="readDisableds"
            :types="
              selectorTabs
                ? selectorTabs
                : type == 'transfer'
                ? ['employee', 'persongroup']
                : ['employee', 'enterprise', 'department', 'persongroup']
            "
            @change="changeSelectUser($event, 'nextUser')"
            :tabs="tabs"
            :params="selectorParams"
          />
        </el-form-item>

        <el-form-item
          v-if="configInfo.isCdjxjTaskHandle != 'true' && type != 'transfer' && configInfo.groups&& configInfo.groups.length != 0"
          prop="cy"
          label="常用群组"
          ><el-checkbox-group v-model="selectCheck">
            <el-checkbox
              @change="handleSelectCheck($event, item)"
              v-for="item in configInfo.groups"
              :label="item.name"
              :key="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-if="configInfo.fyDoresult == 'true'"
          prop="showDoresult"
          label="流程意见"
          ><el-radio v-model="nextNode.showDoresult" label="0">分阅</el-radio>
          <el-radio v-model="nextNode.showDoresult" label="1">不分阅</el-radio>
        </el-form-item>
        <el-form-item
          v-if="configInfo.fyeh == 'true'"
          prop="isInHistory"
          label="分阅记录"
          ><el-radio v-model="nextNode.isInHistory" label="0">记录</el-radio>
          <el-radio v-model="nextNode.isInHistory" label="1">不记录</el-radio>
        </el-form-item>
        <el-form-item
          v-if="configInfo.download"
          prop="isDownload"
          label="打印下载文件"
          ><el-radio v-model="nextNode.isDownload" label="0">允许</el-radio>
          <el-radio v-model="nextNode.isDownload" label="1">不允许</el-radio>
        </el-form-item>
        <el-form-item
          prop="handleExplain"
          :label="configInfo.isCdjxjTaskHandle == 'true' ? '附言' : '办理说明'"
          v-if="type != 'transfer'"
        >
          <el-input
            v-model="nextNode.handleExplain"
            type="textarea"
            :rows="3"

            placeholder="请填写办理说明"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="configInfo.isCdjxjTaskHandle != 'true' && noticeList.length > 0 && !hideMessage"
          prop="noticeType"
          label="通知方式"
        >
          <el-checkbox-group
            v-model="nextNode.noticeType"
            style="display: contents"
          >
            <el-checkbox
              v-for="item of noticeList"
              :key="item.cciValue"
              :label="item.cciValue"
              :disabled="
                readOnlyNotificationType
                  ? readOnlyNotificationType.indexOf(item.cciValue) != -1
                  : false
              "
            >
              {{ item.shortName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-show="
            nextNode.noticeType.length != 0 &&
            configInfo.isCdjxjTaskHandle != 'true'
          "
          prop="nextNode"
          label="通知消息"
        >
          <es-input
            style="
              border-color: #ccc;
              padding: 5px;
              border-radius: 5px;
              font-size: 13px;
            "
            type="textarea"
            v-model="newsNoice"
            :readonly="notificationMessageReadOnly == 'true'"
          />
          <!-- <span>{{ newsInfo }}</span> -->
        </el-form-item>
      </div>
      <el-form-item>
        <div style="text-align: right">
          <el-button type="primary"  @click="submit('nextNode')">
            提交
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  findSysCodes,
  taskReadHtml,
  toStartTaskRead,
  toTaskTransferIndex,
  getNotificationMsg,
  taskTransfer,
  findCodeValues
} from 'eoss-ui/src/config/api';
import util from 'eoss-ui/src/utils/util';
import SelectUser from './selectUser.vue';
export default {
  name: 'StartTaskRead',
  components: {
    [Option.name]: Option,
    [SelectUser.name]: SelectUser
  },
  props: {
    pendingId: { type: String, default: '' },
    simpleTips: { type: Boolean, default: true },
    showTooltip: { type: Boolean, default: true },
    newsInfo: { type: String, default: '' },
    type: { type: String, default: '' },
    option: { type: String, default: '' },
    typeCode: { type: String, default: '' },
    resetAppId: { type: String, default: '' },
    selectorConfig: { type: [Object, undefined], default: undefined },
    param: { type: Object, default: () => {} },
    taskExamine: { type: Object, default: () => {} },
    subParams:{
      type: [Object, undefined],
      default: undefined
    },
    readParams: {
      type: [Object, undefined],
      default: undefined
    },
    
    hideMessage: { type: Boolean, default: false },
  },
  data() {
    return {
      loading: false,
      newsNoice: '',
      readOnlyNotificationType: '',
      notificationMessageReadOnly: false,
      selectorTabs: null,
      selectorParams: null,
      nextNode: {
        nextUser: [],
        userInfo: [],
        noticeType: [],
        handleExplain: '',
        showDoresult: '0',
        isInHistory: '0',
        isDownload: '0'
      },
      mixList: [],
      newSelectUserList: [],
      orgId: '',
      noticeList: [],
      userOptions: [],
      readDisableds:[],
      selectCheck: [],
      selectUserList: [],
      transferInfo: {},
      multiple: true,
      params: { filid: 'all' },
      configInfo: {}
    };
  },
  computed: {
    tabs() {
      let tab = {};
      if (this.type != 'transfer') {
        tab = {
          employee: {
            param: {
              filid: this.orgId,
              name: '本单位用户'
            }
          },
          department: { param: { filid: this.orgId } },
          enterprise: {}
        };
      } else {
        tab = {
          employee: {
            param: {
              filid: this.orgId
            }
          }
        };
      }
      return tab;
    }
  },
  mounted() {
    this.newsNoice = this.newsInfo;
    if (this.readParams || this.typeCode == 'read') {
      this.getMessage();
    }
    this.getFind();
    if (util.getStorage('mainConfig')) {
      this.orgId = JSON.parse(util.getStorage('mainConfig')).userModel.orgId;
    }
    if(this.selectorConfig){
      this.getSelectorConfig()
    }
  },
  methods: {
    getSelectorConfig() {
      this.selectorTabs = this.selectorConfig.type.split(',');
      this.selectorParams = this.selectorConfig.params;
    },
    //获取通知信息
    getMessage() {
      let params = {};
      if (this.typeCode == 'read') {
        params = {
          processDefinitionId: this.param.processDefinitionId,
          businessId: this.param.businessId,
          businessName: this.param.businessName,
          bCode: this.param.bCode,
          bName: this.param.bName,
          appId: this.param.appId
        };
      } else {
        params.appId = this.readParams.appId;
      }
      util
        .ajax({ url: getNotificationMsg, params, methods: 'post' })
        .then((res) => {
          if (res.status === 'success') {
            this.newsNoice = res.message;
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    toTaskTransfer() {
      const { opinion, pendingId, taskExamine } = this;
      let params = {
        url: toTaskTransferIndex,
        params: {
          opinion,
          pendingId,
          isSubFlow: taskExamine.isSubFlow,
          isSinglePage: taskExamine.isSinglePage
        }
      };
      util
        .ajax(params)
        .then((res) => {
          const {
            status,
            message,
            data: { choiceDeptId, choiceOrgId, nodeInfoMap, taskExamine }
          } = res;
          if (status == 'success') {
            this.isMultipleTransfer(
              nodeInfoMap.nodeExtAttr.userSelectionType,
              choiceOrgId,
              choiceDeptId
            );
            this.nextNode.nodeName = taskExamine.nodeName;
            this.transferInfo = taskExamine;
          } else {
            this.$message.error(message || '系统错误，请联系管理员！');
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    isMultipleTransfer(val, choiceOrgId, choiceDeptId, pOrgId) {
      if (val == 2 || val == 4 || val == 6 || val == 16) {
        this.multiple = true;
      } else {
        this.multiple = false;
      }
      if (val == 1 || val == 2 || val == 5) {
        this.params.filid = this.orgId;
        if (choiceOrgId) {
          this.params.filid = choiceOrgId;
        }
      }
      if (val == 5 || val == 6) {
        this.params.filid = this.orgId;
        this.params.deptid = this.orgId;
        if (choiceDeptId) {
          this.params.deptid = choiceDeptId;
        }
        if (choiceOrgId) {
          this.params.filid = choiceOrgId;
        }
      }
      if (val == 15 || val == 16) {
        this.params.filid = this.orgId;
        if (pOrgId) {
          this.params.filid = pOrgId;
        }
      }
    },
    isMultiple() {
      let orgId = this.orgId;
      if (this.configInfo.selectPersonValue == 1) {
        this.multiple = false;
        this.params.filid = orgId;
      } else if (this.configInfo.selectPersonValue == 2) {
        this.multiple = true;
        this.params.filid = orgId;
      } else if (this.configInfo.selectPersonValue == 3) {
        this.multiple = false;
        this.params.filid = 'all';
      } else if (this.configInfo.selectPersonValue == 4) {
        this.multiple = true;
        this.params.filid = 'all';
      } else if (this.configInfo.selectPersonValue == 5) {
        this.multiple = false;
        this.params.filid = '';
      } else if (this.configInfo.selectPersonValue == 6) {
        this.multiple = true;
        this.params.filid = '';
      }
    },
    handleSelectCheck(val, data) {
      let { userIds, userNames } = data;
      if (val) {
        let newUserIds = userIds.split(',');
        let newUserNames = userNames.split(',');
        newUserIds.map((item, index) => {
          this.nextNode.nextUser.push(item);
          this.userOptions.push({ id: item, name: newUserNames[index],stype:data.stype });

          this.selectUserList.push({
            showid: item,
            showname: newUserNames[index],
            stype:data.stype
          });
        });
        // this.selectUserList = this.newSelectUserList
      } else {
        let newUserIds = userIds.split(',');
        for (let i = 0; i < this.nextNode.nextUser.length; i++) {
          for (let j = 0; j < newUserIds.length; j++) {
            if (this.nextNode.nextUser[i] == newUserIds[j]) {
              this.nextNode.nextUser.splice(i, 1);
            }
          }
        }
        for (let z = 0; z < this.userOptions.length; z++) {
          for (let x = 0; x < newUserIds.length; x++) {
            if (this.userOptions[z].id == newUserIds[x]) {
              this.userOptions.splice(z, 1);
              this.selectUserList.splice(z, 1);
            }
          }
        }
        // this.newSelectUserList = this.selectUserList
      }
    },
    toStartTaskRead() {
      let params = {
        url: toStartTaskRead,
        params: {
          pendingId: this.pendingId,
          taskAction: this.type,
          ...this.param
        }
      };
      if (this.typeCode == 'read') {
        delete params.params.pendingId;
        // params.params.appid = this.resetAppId;
      }
      if (this.type != 'taskReadAndEnd') delete params.params.taskAction;
      util
        .ajax(params)
        .then((res) => {
          const { status, data } = res;
          if (status === 'success') {
            this.configInfo = data;
            if(data.alreadyReadUserIds){
              this.readDisableds = data.alreadyReadUserIds.split(',');
            }
            this.isMultiple();
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    changeSelectUser(val, type) {
      const { nextUser, options, mixList } = val;
      this.nextNode[type] = nextUser;
      this.mixList = mixList;
      options.map((item) => {
        this.newSelectUserList.push({
          showname: item.showname,
          showid: item.showid
        });
      });
    },
    getNodeType() {
      util
        .ajax({
          url: findCodeValues,
          params: {
            ccCode: 'fenyue_msg_type',
            userId: util.getStorage('userId'),
            // pendingId:this.pendingId
          }
        })
        .then((res) => {
          const { status, data } = res;
          if (status === 'success') {
            this.noticeList = data;
            let arr = [];
            this.noticeList.map((item) => {
              this.nextNode.noticeType.map((x) => {
                if (x == item.cciValue) {
                  arr.push(x);
                }
              });
            });
            this.nextNode.noticeType = arr;
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    // 转办提交
    subTaskTransfer() {
      const { choiceDeptId, choiceOrgId, bCode, bName } = this.taskExamine;
      const { opinion, pendingId, nextNode, newsNoice, multiple, type } = this;
      let params = {
        url: taskTransfer,
        data: {
          choiceDeptId,
          choiceOrgId,
          bCode,
          bName,
          nextUserId:
            multiple && type != 'transfer'
              ? nextNode.nextUser.join(',')
              : nextNode.nextUser,
          opinion,
          pendingId,
          notificationType: nextNode.noticeType.join(','),
          notificationMsg: newsNoice
        },
        headers: { Accept: 'application/json,text/plain' },
        method: 'post'
      };
      util
        .ajax(params)
        .then((res) => {
          const { message, status } = res;
          if (status === 'success') {
            this.simpleTips && this.$message.success('操作成功');
            this.quit(true);
          } else {
            this.$message.error(message || '系统错误，请联系管理员！');
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    // 提交表单
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.option && this.isOpinionRequired === 1) {
            this.$message.warning('请选择输入审批意见');
            return;
          }
          // let nextUser = [];
          // this.nextNode.nextUser.map(item => {
          //   nextUser.push(item);
          // });
          let noticeType = '';
          noticeType = this.nextNode.noticeType.join(',');
          this.loading = true;
          if (this.type === 'transfer') {
            this.subTaskTransfer();
          } else {
            const {
              appId,
              businessId,
              bCode,
              bName,
              choiceDeptId,
              choiceOrgId,
              businessName,
              processDefinitionId
            } = this.taskExamine;
            let params = {
              ...this.nextNode,
              bCode,
              bName,
              appId,
              businessId: businessId || this.param.businessId,
              choiceDeptId,
              choiceOrgId,
              businessName,
              processDefinitionId,
              currentOrgProcessKey:
                processDefinitionId || this.param.currentOrgProcessKey,
              pendingId: this.pendingId,
              opinion: this.option, // 审批意见
              userId: util.getStorage('userId'),
              nextReadUserId: this.mixList.join('|'),
              notificationType: noticeType,
              notificationMsg: this.newsNoice,
              taskAction: this.type
              // nextNodeId: this.form.nextNodeId
            };
            delete params.nextUser;
            delete params.noticeType;
            const { fyDoresult, fyeh, download, isCdjxjTaskHandle } =
              this.configInfo;
            fyDoresult != 'true' && delete params.showDoresult;
            fyeh != 'true' && delete params.isInHistory;
            !download && delete params.isDownload;
            isCdjxjTaskHandle == 'true' && delete params.noticeType;
            if (this.readParams) {
              params = { ...params, ...this.readParams };
            }
            if(this.subParams){
              params = { ...params, ...this.subParams };
            }
            delete this.configInfo.taskExamine.taskExamineParam;
            util
              .ajax({
                url: taskReadHtml,
                params: { taskAction: this.type },
                headers: {
                  Accept: 'application/json,text/plain'
                },
                method: 'post',
                data: {...params,...this.configInfo.taskExamine}
              })
              .then((res) => {
                const { message, status } = res;
                this.loading = false;
                if (status === 'success') {
                  this.simpleTips && this.$message.success('操作成功');
                  this.quit(true);
                } else {
                  this.$message.error(message || '系统错误，请联系管理员！');
                }
              })
              .catch((err) => {
                this.loading = false;
                if (err.message && err.message !== 'canceled') {
                  this.$message.error(err.message);
                }
              });
          }
        } else {
          return false;
        }
      });
    },
    quit(val) {
      if (val === true) return this.$emit('cancel', this.type);
      this.$emit('cancel');
    },

    getFind() {
      this.loading = true;
      util
        .ajax({
          url: findSysCodes
        })
        .then((res) => {
          const { status, message, data } = res;
          this.loading = false;
          if (status === 'success') {
            if(this.hideMessage) return;
            this.nextNode.noticeType = message.split(',');
            if (data) {
              this.notificationMessageReadOnly =
                data.notificationMessageReadOnly;
              this.readOnlyNotificationType = data.readOnlyNotificationType;
            }
          } else {
            this.$message.error(message || '系统错误，请联系管理员！');
          }
          this.getNodeType();
          if (this.type === 'transfer') {
            this.toTaskTransfer();
          } else if (!this.readParams) {
            this.toStartTaskRead();
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    }
  }
};
</script>
