<template>
  <div class="task-union-examine" v-loading="loading">
    <el-form
      ref="infoList"
      :model="infoList"
      class="demo-dynamic"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item v-if="isSinglePage" prop="opinion" label="意见">
        <CommonOpinions @change="(val) => (opinion = val)" />
      </el-form-item>
      <el-form-item
        v-if="isHideCurrentOrg == 0"
        :prop="type != 'takeAdvice' ? 'nextOtherOrgObj' : 'nextCurrentOrgObj'"
        :label="
          type == 'takeAdvice'
            ? currentOrgName
              ? currentOrgName
              : '本单位'
            : type == 'startDraf'
            ? '呈送单位/对象'
            : type === 'taskReview'
            ? '复核人'
            : type === 'twoOfficesDispatch'
            ? '报送单位'
            : '联合单位'
        "
      >
        <SelectUser
          :nextUser="
            type != 'takeAdvice'
              ? infoList.nextOtherOrgObj
              : infoList.nextCurrentOrgObj
          "
          :multiple="newMultiple"
          :selectorTags="4"
          :showTooltip="showTooltip"
          :mix="currentMix"
          :isUnionSeal="type == 'unionSeal'"
          :selectUserList="unionSealData || []"
          @change="
            changeSelectUser(
              $event,
              type != 'takeAdvice' ? 'nextOtherOrgObj' : 'nextCurrentOrgObj'
            )
          "
          :types="
            type == 'takeAdvice'
              ? currentOrgTabs.length > 0
                ? currentOrgTabs
                : ['department', 'employee']
              : type == 'startDraf'
              ? ['employee', 'enterprise']
              : ['enterprise']
          "
          :params="
            type == 'startDraf' || type == 'unionExamine' ? otherParams : params
          "
          :tabs="currentOrgTabsParam"
          :disabled="disabled"
          :onlyName="onlyName"
        />
      </el-form-item>
      <el-form-item
        prop="nextOtherOrgObj"
        v-if="isHideOtherOrg == 0 && type == 'takeAdvice'"
        :label="otherOrgName ? otherOrgName : '外单位'"
      >
        <SelectUser
          :nextUser="infoList.nextOtherOrgObj"
          :where="{ filid: 'all', roleid: selectorParams.roleid }"
          :showTooltip="showTooltip"
          :multiple="newMultiple"
          @change="changeSelectUser($event, 'nextOtherOrgObj')"
          :mix="otherMix"
          :selectorTags="4"
          :disableds="otherOrgDisabledObjId"
          :types="
            foreignOrgTabs.length > 0
              ? foreignOrgTabs
              : isChoiceOtherOrgDept == 'true'
              ? ['enterprise', 'department']
              : ['enterprise']
          "
          :params="otherParams"
          :tabs="foreignOrgTabsParam"
        />
      </el-form-item>
      <el-form-item
        v-if="enableCustomLimitTimeSetting"
        prop="customLimitTime"
        label="限时办理"
      >
        <!-- style="width: 49%; display: inline-block;" -->
        <es-select
          style="width: 20% !important; display: inline-block"
          v-model="infoList.customLimitTimeText"
          placeholder="请选择"
          @change="handleChangeTime"
          sysCode="bpm_custom_limit_time"
        ></es-select>
        <el-input
          style="width: 20%; display: inline-block"
          v-model="infoList.customLimitTime"
          placeholder="请输入限时办理的天数"
          class="input-with-select custom-limit-time"
        >
        </el-input>
        <span style="margin-left: 5px">天</span>
        <!-- <es-button
          type="primary"
          slot="append"
          @click="
            () => {
              infoList.customLimitTime = '';
              showCustomLimitTimeText = !showCustomLimitTimeText;
            }
          "
          >切换{{ showCustomLimitTimeText ? '选择框' : '文本框' }}</es-button
        > -->
      </el-form-item>
      <!-- :rules="[
          { required: false, message: `请选择通知方式`, trigger: 'blur' }
        ]" -->
      <el-form-item
        prop="noticeType"
        label="通知方式"
        v-show="infoList.noticeList.length != 0 && !hideMessage"
      >
        <el-checkbox-group
          v-model="infoList.noticeType"
          style="display: contents"
        >
          <el-checkbox
            v-for="item of infoList.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="infoList.noticeType.length != 0"
        prop="noticeInfo"
        label="通知消息"
      >
        <es-input
          style="
            border-color: #ccc;
            padding: 5px;
            border-radius: 5px;
            font-size: 13px;
          "
          type="textarea"
          v-model="infoList.noticeInfo"
          :readonly="notificationMessageReadOnly"
        />
        <!-- <span>{{ infoList.noticeInfo }}</span> -->
      </el-form-item>
    </el-form>
    <div style="text-align: right">
      <el-button type="primary" @click="subMit"> 确定 </el-button>
      <el-button @click="quit" > 取消 </el-button>
    </div>
  </div>
</template>

<script>
import CommonOpinions from './CommonOpinions.vue';
import SelectUser from '../selectUser.vue';
import {
  findSysCodes,
  getNotificationMsg,
  toTaskTakeAdvice,
  findCodeValues,
  toTaskStartDraft,
  toTaskReview,
  taskStartDraft,
  toTaskUnionSeal,
  taskReview,
  toTwoOfficesDispatch,
  taskUnionSeal,
  twoOfficesDispatch,
  taskUnionExamine,
  taskTakeAdvice,
  toTaskUnionExamine
} from 'eoss-ui/src/config/api';
import util from 'eoss-ui/src/utils/util.js';
export default {
  name: 'TaskUnionExamine',
  components: {
    [CommonOpinions.name]: CommonOpinions,
    [SelectUser.name]: SelectUser
  },
  props: {
    pendingId: { type: String, default: '' },
    showTooltip: { type: Boolean, default: true },
    type: { type: String, default: '' },
    defaultOpinion: { type: String, default: '' },
    oldOption: { type: String, default: '' },
    disabled: { type: Boolean, default: false },
    simpleTips: { type: Boolean, default: true },
    multiple: { type: Boolean, default: true },
    selectorParams: {
      type: Object,
      default: () => {
        return {};
      }
    },
    hideMessage: { type: Boolean, default: false },
  },
  inheritAttrs: false,
  data() {
    return {
      opinion: '', //办理意见
      readOnlyNotificationType: '',
      notificationMessageReadOnly: false,
      otherMix: false,
      enableCustomLimitTimeSetting: false,
      showCustomLimitTimeText: false,
      currentMix: false,
      infoList: {
        nextOtherOrgObj: [],
        nextCurrentOrgObj: [],
        noticeType: [],
        noticeList: [],
        noticeInfo: '',
        opinion: '',
        customLimitTime: '',
        customLimitTimeText: ''
      },
      onlyName: '',
      unionSealData: [],
      currentOrgTabs: [],
      foreignOrgTabs: [],
      foreignOrgTabsParam: {},
      currentOrgTabsParam: {},
      currentOrgProcessKey: '',
      otherOrgDisabledObjId: [],
      isSubFlow: true,
      choiceDeptId: '',
      choiceOrgId: '',
      isSinglePage: false,
      isChoiceOtherOrgDept: '',
      currentOrgName: '',
      otherOrgName: '',
      newMultiple: true,
      params: { filid: 'all',only_filid:true },
      isHideOtherOrg: '',
      isHideCurrentOrg: 0,
      isOpinionRequired: 0,
      otherParams: { filid: 'all', roleid: '', nofilid: sessionStorage.getItem('orgId') },
      loading: false
    };
  },
  computed: {
    rules() {
      return {
        customLimitTime: [
          {
            required: this.enableCustomLimitTimeSetting,
            message: this.showCustomLimitTimeText
              ? '请输入限时办理天数'
              : '请选择限时办理天数',
            trigger: 'blur'
          },
          {
            required: this.enableCustomLimitTimeSetting,
            validator: this.checkCustomLimitTime,
            trigger: 'change'
          }
        ]
      };
    }
  },
  mounted() {
    this.loading = true;
    this.newMultiple = this.multiple;
    this.otherParams.roleid = this.params.roleid = this.selectorParams.roleid;
    this.opinion = this.oldOption;
    this.getNodeType();
    if (this.type === 'taskReview') return this.getTaskReview();
    this.getInfo();
  },
  methods: {
    handleChangeTime(val) {
      this.infoList.customLimitTime = val;
    },
    validate() {
      let validSate = true;
      this.$refs.infoList.validate((valid) => {
        if (valid) {
          validSate = true;
        } else {
          validSate = false;
        }
      });
      return validSate;
    },
    checkCustomLimitTime(rule, value, callback) {
      if (!Number(value) || value.indexOf('.') != -1 || Number(value) < 0) {
        callback(new Error('请输入正确的天数'));
        this.infoList.customLimitTime = '';
      } else {
        callback();
      }
    },
    isMultiple(val) {
      if (val == 7 || val == 9 || val == 11) {
        this.newMultiple = false;
      }
    },
    subTaskReview() {
      let {
        infoList: { nextOtherOrgObj, noticeType, noticeInfo },
        businessId,
        opinion,
        isSubFlow,
        currentOrgProcessKey,
        pendingId
      } = this;
      let params = {
        url: taskReview,
        data: {
          nextUserId: nextOtherOrgObj.join(','),
          notificationType: noticeType.join(','),
          notificationMsg: noticeInfo,
          opinion,
          isSubFlow,
          businessId,
          currentOrgProcessKey,
          pendingId
        },
        method: 'POST'
      };
      this.loading = true;
      util
        .ajax(params)
        .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);
          }
        });
    },
    getTaskReview() {
      let params = {
        url: toTaskReview,
        params: { pendingId: this.pendingId }
      };
      util
        .ajax(params)
        .then((res) => {
          const { status, message } = res;
          this.loading = false;
          if (status === 'success') {
            const {
              data: { initiatorUser, taskExamine }
            } = res;
            if (taskExamine.opinion) {
              this.opinion = taskExamine.opinion;
            }
            this.infoList.nextOtherOrgObj.push(initiatorUser.userId);
            this.onlyName = initiatorUser.username;
            this.isSubFlow = taskExamine.isSubFlow;
            this.currentOrgProcessKey = taskExamine.currentOrgProcessKey;
            this.getFind();
            this.getMessage();
          } else {
            this.$message.error(message || '系统错误，请联系管理员！');
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    getInfo() {
      let params = {
        url:
          this.type == 'takeAdvice'
            ? toTaskTakeAdvice
            : this.type === 'startDraf'
            ? toTaskStartDraft
            : this.type == 'unionSeal'
            ? toTaskUnionSeal
            : this.type == 'twoOfficesDispatch'
            ? toTwoOfficesDispatch
            : toTaskUnionExamine,
        params: { pendingId: this.pendingId },
        headers: { Accept: 'application/json,text/plain' }
      };
      util
        .ajax(params)
        .then((res) => {
          const { message, status } = res;
          this.loading = false;
          if (status == 'success') {
            const {
              data: {
                choiceDeptId,
                choiceOrgId,
                taskExamine,
                unionDispatchOrgName,
                readOnlyNotificationType,
                notificationMessageReadOnly,
                unionDispatchOrgId,
                otherOrgDisabledObjId,
                orgNames,
                enableCustomLimitTimeSetting,
                defaultCustomLimitDays,
                nodeInfoMap: {
                  nodeExtAttr: {
                    userSelectionType,
                    isHideOtherOrg,
                    isHideCurrentOrg,
                    isOpinionRequired
                  }
                }
              }
            } = res;
            if (otherOrgDisabledObjId) {
              this.otherOrgDisabledObjId = otherOrgDisabledObjId.split(',');
            }
            this.enableCustomLimitTimeSetting = enableCustomLimitTimeSetting;
            if (this.enableCustomLimitTimeSetting && defaultCustomLimitDays) {
              this.infoList.customLimitTime =
                this.infoList.customLimitTimeText = defaultCustomLimitDays + '';
            }
            if (res.data.customizedConfig) {
              if (res.data.customizedConfig.currentOrgSelectorCustomized) {
                this.currentMix =
                  res.data.customizedConfig.currentOrgSelectorSelectMix ==
                  'true';
                this.currentOrgTabs =
                  res.data.customizedConfig.currentOrgSelectorItemList.split(
                    ','
                  );
                let param =
                  res.data.customizedConfig.currentOrgSelectorRangeList.split(
                    ','
                  );
                this.currentOrgTabs.map((x, i) => {
                  this.params[x] = {
                    filid:
                      param[i] == 'my'
                        ? (this.params.filid = JSON.parse(
                            util.getStorage('mainConfig')
                          ).userModel.orgId)
                        : param[i],
                      only_filid:true
                  };
                });
              } else {
                if (this.type == 'takeAdvice') {
                  this.params.filid = JSON.parse(
                    util.getStorage('mainConfig')
                  ).userModel.orgId;
                }
              }

              if (res.data.customizedConfig.foreignOrgSelectorCustomized) {
                this.otherMix =
                  res.data.customizedConfig.foreignOrgSelectorSelectMix ==
                  'true';
                this.foreignOrgTabs =
                  res.data.customizedConfig.foreignOrgSelectorItemList.split(
                    ','
                  );
                let param =
                  res.data.customizedConfig.foreignOrgSelectorRangeList.split(
                    ','
                  );
                this.foreignOrgTabs.map((x, i) => {
                  this.otherParams[x] = {
                    filid: 'all',
                    roleid: this.selectorParams.roleid,
                    nofilid: sessionStorage.getItem('orgId')
                  };
                });
              }
            }
            this.readOnlyNotificationType = readOnlyNotificationType;
            this.notificationMessageReadOnly =
              notificationMessageReadOnly == 'true';
            this.isSinglePage = taskExamine.isSinglePage;
            this.isSubFlow = taskExamine.isSubFlow;
            if (taskExamine.opinion) {
              this.opinion = taskExamine.opinion;
            }
            this.choiceDeptId = choiceDeptId;
            this.choiceOrgId = choiceOrgId;
            if (this.type == 'takeAdvice' || this.type == 'startDraf') {
              this.currentOrgName = res.data.currentOrgName;
              this.otherOrgName = res.data.otherOrgName;
              this.isChoiceOtherOrgDept = res.data.isChoiceOtherOrgDept;
              this.isHideOtherOrg = isHideOtherOrg;
              this.isHideCurrentOrg = isHideCurrentOrg;
            }
            this.isOpinionRequired = isOpinionRequired;
            if (this.type == 'unionSeal') {
              let names = unionDispatchOrgName.split(',');
              let ids = unionDispatchOrgId.split(',');
              names.map((x, i) => {
                if (x) {
                  this.unionSealData.push({
                    showname: x,
                    showid: ids[i]
                  });
                }
              });
              // this.onlyName = unionDispatchOrgName;
              // this.infoList.nextOtherOrgObj.push(unionDispatchOrgId);
            }
            if (this.type == 'twoOfficesDispatch') {
              this.onlyName = orgNames;
              this.infoList.nextOtherOrgObj.push(taskExamine.nextOtherOrgObj);
            }
            this.isMultiple(userSelectionType);
            this.getFind();
            this.getMessage();
          } else {
            this.$message.error(message || '系统错误，请联系管理员！');
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    subMit() {
      // if (
      //   this.infoList.nextOtherOrgObjName == '' ||
      //   this.infoList.nextOtherOrgObjName.length == 0
      // )
      //   return this.$message.warning('请选择联合单位');
      if (this.type === 'taskReview') return this.subTaskReview();
      let {
        infoList: {
          nextCurrentOrgObj,
          nextOtherOrgObj,
          noticeType,
          customLimitTime,
          noticeInfo
        },
        isOpinionRequired,
        opinion,
        type,
        isHideOtherOrg,
        choiceDeptId,
        choiceOrgId,
        isHideCurrentOrg,
        isSubFlow,
        pendingId
      } = this;
      console.log(nextCurrentOrgObj);
      console.log(nextOtherOrgObj);
      if (
        type == 'takeAdvice' &&
        !nextCurrentOrgObj &&
        isHideCurrentOrg == 0 &&
        nextCurrentOrgObj.length == 0 &&
        isHideOtherOrg == 0 &&
        (!nextOtherOrgObj || nextOtherOrgObj.length == 0)
      ) {
        return this.$message.warning('请选择处理对象!');
      } else if (
        isHideCurrentOrg == 0 &&
        (!nextOtherOrgObj || nextOtherOrgObj.length == 0) &&
        (!nextCurrentOrgObj || nextCurrentOrgObj.length == 0)
      ) {
        return this.$message.warning('请选择处理对象!');
      }

      if (isOpinionRequired == 1 && (opinion == '' || opinion == null)) {
        return this.$message.warning('当前步骤必须输入意见!');
      }
      // if (this.type != 'startDraf' && this.type != 'unionSeal' && this.type != 'twoOfficesDispatch')
      //   return this.$message.warning('暂未开放，敬请期待！');
      const param = {
        url:
          this.type === 'startDraf'
            ? taskStartDraft
            : this.type == 'unionSeal'
            ? taskUnionSeal
            : this.type === 'twoOfficesDispatch'
            ? twoOfficesDispatch
            : this.type == 'takeAdvice'
            ? taskTakeAdvice
            : taskUnionExamine,
        data: {
          opinion,
          pendingId,

          nextOtherOrgObj:
            this.type == 'unionSeal'
              ? this.unionSealData.map((x) => x.showid).join(',')
              : Array.isArray(nextOtherOrgObj)
              ? nextOtherOrgObj.join(',')
              : nextOtherOrgObj,
          nextCurrentOrgObj: Array.isArray(nextCurrentOrgObj)
            ? nextCurrentOrgObj.join(',')
            : nextCurrentOrgObj,
          notificationMsg: noticeInfo,
          notificationType: noticeType.join(','),
          choiceDeptId,
          isSubFlow,
          choiceOrgId
        },
        headers: { Accept: 'application/json,text/plain' },
        method: 'POST'
      };
      if (this.enableCustomLimitTimeSetting) {
        param.data.customLimitTime = customLimitTime;
        console.log(this.validate(), 'this.validate()');
        if (!this.validate()) return;
      }
      this.loading = true;
      util
        .ajax(param)
        .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);
          }
        });
    },
    quit(val) {
      if (val === true) return this.$emit('cancel', val);
      this.$emit('cancel');
    },
    changeSelectUser(val, type) {
      const { nextUser, options } = val;
      let newNextUser = [];
      let obj = {};
      options.map((item) => {
        if (obj[item.stype]) {
          obj[item.stype].push(item.id);
        } else {
          obj[item.stype] = [item.id];
        }
        // if (newNextUser) {
        //   newNextUser += `,${item.stype}-${item.id}`;
        // } else {
        //   newNextUser = `${item.stype}-${item.id}`;
        // }
      });
      for (let key in obj) {
        newNextUser.push(`${key}-${obj[key].join(',')}`);
      }

      this.infoList[type] = newNextUser.join('|');
    },
    getNodeType() {
      util
        .ajax({
          url: findCodeValues,
          params: {
            ccCode: 'notification_type',
            userId: util.getStorage('userId'),
            pendingId: this.pendingId
          }
        })
        .then((res) => {
          const { status, data } = res;
          this.loading = false;
          if (status === 'success') {
            this.infoList.noticeList = data;
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    //获取通知信息
    getMessage() {
      let params = {
        pendingId: this.pendingId
      };
      util
        .ajax({ url: getNotificationMsg, params, methods: 'post' })
        .then((res) => {
          if (res.status === 'success') {
            this.infoList.noticeInfo = res.message;
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    getFind() {
      util
        .ajax({
          url: findSysCodes
        })
        .then((res) => {
          const { status, message } = res;
          if (status === 'success') {
            if(this.hideMessage) return;
            this.infoList.noticeType = message.split(',');
            let arr = [];
            this.infoList.noticeList.map((item) => {
              this.infoList.noticeType.map((x) => {
                if (x == item.cciValue) {
                  arr.push(x);
                }
              });
            });
            this.infoList.noticeType = arr;
          } else {
            this.$message.error(message || '系统错误，请联系管理员！');
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    }
  }
};
</script>

<style></style>
