<template>
  <div class="task-union-examine" v-loading="loading">
    <el-form
      ref="infoList"
      :model="infoList"
      class=""
      label-width="100px"
      :label-position="labelPosition"
    >
      <el-form-item
        v-if="isHideCurrentOrg == 0"
        prop="nextCurrentOrgObj"
        label="本单位"
      >
        <SelectUser
          :nextUser="infoList.nextCurrentOrgObj"
          :multiple="newMultiple"
          mix
          :showTooltip="showTooltip"
          @change="changeSelectUser($event, 'nextCurrentOrgObj')"
          :types="['employee', 'persongroup']"
          :params="params"
        />
      </el-form-item>
      <el-form-item prop="nextOtherOrgObj" label="外单位">
        <SelectUser
          :nextUser="infoList.nextOtherOrgObj"
          :showTooltip="showTooltip"
          :multiple="newMultiple"
            :where="{ filid: 'other',roleid :selectorParams.roleid }"
          @change="changeSelectUser($event, 'nextOtherOrgObj')"
          mix
          :types="['enterprise', 'filgroup']"
          :params="otherParams"
        />
      </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"
          @change="handleChange"
          :readonly="notificationMessageReadOnly"
        />
        <!-- <span>{{ infoList.noticeInfo }}</span> -->
      </el-form-item>
    </el-form>
    <div v-if="showBtn" 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,
  findCodeValues,
  directStartTaskCircularRead,
  endFlowAndStartTaskCircularRead
} from 'eoss-ui/src/config/api';
import util from 'eoss-ui/src/utils/util.js';
export default {
  name: 'Circulate',
  components: {
    [CommonOpinions.name]: CommonOpinions,
    [SelectUser.name]: SelectUser
  },
  props: {
    pendingId: { type: String, default: '' },
    showTooltip: { type: Boolean, default: true },
    processDefinitionId: { type: String, default: '' },
    businessId: { type: String, default: '' },
    type: { type: String, default: '' },
    defaultOpinion: { type: String, default: '' },
    oldOption: { type: String, default: '' },
    disabled: { type: Boolean, default: false },
    simpleTips: { type: Boolean, default: true },
    showBtn: { type: Boolean, default: true },
    multiple: { type: Boolean, default: true },
    selectorParams:{type:Object,default:()=>{
      return {}
    }},
    labelPosition:{
      type: String,
      default: 'left'
    },
    startFlowPageEmbeddedIntoStartFlowIndex: { type: Boolean, default: false },
    formTitle: {
      type: String,
      default: ''
    },
    hideMessage: { type: Boolean, default: false },
  },
  inheritAttrs: false,
  data() {
    return {
      opinion: '', //办理意见
      readOnlyNotificationType: '',
      notificationMessageReadOnly: false,
      otherMix: false,
      currentMix: false,
      oldMessage: '',
      infoList: {
        nextOtherOrgObj: [],
        nextCurrentOrgObj: [],
        noticeType: [],
        noticeList:[],
        noticeInfo: '',
        opinion: ''
      },
      onlyName: '',
      currentOrgTabs: [],
      foreignOrgTabs: [],
      currentOrgProcessKey: '',
      isChangeMessage: false,
      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', nofilid: 1 },
      loading: false,
      subLoading: null,
      userModel: {}
    };
  },
  watch: {
    selectorParams: {
      handler(val) {
        this.params = val;
        this.params.only_filid = true;
      },
      deep: true,
      immediate: true
    },
    oldOption: {
      handler(val) {
        this.opinion = val;
      },
      deep: true,
      immediate: true
    },
    formTitle: {
      handler(val) {
        if (!this.showBtn && !this.isChangeMessage) {
          this.infoList.noticeInfo = this.oldMessage.replace('{title}', val);
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
     let mainConfig = util.getStorage('mainConfig');
      if (mainConfig) {
        this.userModel = JSON.parse(mainConfig).userModel;
        this.params.filid = this.userModel.orgId;
        this.otherParams.nofilid = this.userModel.orgId
        this.otherParams.roleid = this.params.roleid
      }
    this.loading = true;
    this.newMultiple = this.multiple;
    this.opinion = this.oldOption;
    this.getNodeType();
    // this.getFind();
    this.getMessage();
  },
  methods: {
    handleChange() {
      this.isChangeMessage = true;
    },
    isMultiple(val) {
      if (val == 7 || val == 9 || val == 11) {
        this.newMultiple = false;
      }
    },
    subMit() {
      let {
        infoList: {
          nextCurrentOrgObj,
          nextOtherOrgObj,
          noticeType,
          noticeInfo
        },
        processDefinitionId,
        opinion,
        businessId
      } = this;
      if (
        (!nextCurrentOrgObj || nextCurrentOrgObj.length == 0) &&
        (!nextOtherOrgObj || nextOtherOrgObj.length == 0)
      ) {
        return this.$message.warning('请选择处理对象!');
      }
      const param = {
        url:
          this.showBtn || this.startFlowPageEmbeddedIntoStartFlowIndex
            ? directStartTaskCircularRead
            : endFlowAndStartTaskCircularRead,
        data: {
          opinion,
          businessId,

          processDefinitionId,
          nextOtherOrgObj: Array.isArray(nextOtherOrgObj)
            ? nextOtherOrgObj.join(',')
            : nextOtherOrgObj,
          nextCurrentOrgObj: Array.isArray(nextCurrentOrgObj)
            ? nextCurrentOrgObj.join(',')
            : nextCurrentOrgObj,
          notificationMsg: noticeInfo,
          notificationType: noticeType.join(','),
          userId: JSON.parse(util.getStorage('mainConfig')).userModel.userId
        },
        headers: { Accept: 'application/json,text/plain' },
        method: 'POST'
      };
      if (!this.showBtn && !this.startFlowPageEmbeddedIntoStartFlowIndex) {
        param.data.pendingId = this.pendingId;
        delete param.data.processDefinitionId;
        this.subLoading = util.loading(this.$loading, '加载中...');
      } else if (this.startFlowPageEmbeddedIntoStartFlowIndex) {
        this.subLoading = util.loading(this.$loading, '加载中...');
      } else {
        this.loading = true;
      }
      util
        .ajax(param)
        .then((res) => {
          const { message, status, rCode } = res;
          if (!this.showBtn || this.startFlowPageEmbeddedIntoStartFlowIndex) {
            this.subLoading.close();
          } else {
            this.loading = false;
          }
          if (status == 'success' || rCode == 0) {
            this.simpleTips && this.$message.success('提交成功');
            this.quit(true);
          } else {
            this.$message.error(message || '系统错误，请联系管理员！');
          }
        })
        .catch((err) => {
          if (!this.showBtn || this.startFlowPageEmbeddedIntoStartFlowIndex) {
            this.subLoading.close();
          } else {
            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,
            startCircularRead: true
          }
        })
        .then((res) => {
          const { status, data } = res;
          this.loading = false;
          if (status === 'success') {
            this.infoList.noticeList = data;
            this.getFind();
          }
        })
        .catch((err) => {
          this.loading = false;
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    //获取通知信息
    getMessage() {
      let params = {
        pendingId: this.pendingId,
        processDefinitionId: this.processDefinitionId,
        businessId: this.businessId
      };
      if (!this.showBtn) {
        params.openMode = 'samepage';
      }
      util
        .ajax({ url: getNotificationMsg, params, methods: 'post' })
        .then((res) => {
          if (res.status === 'success') {
            if (!this.showBtn) {
              this.oldMessage = res.message;
              this.infoList.noticeInfo = res.message.replace(
                '{title}',
                this.formTitle
              );
            } else {
              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>
