<template>
  <div>
    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" :close-on-click-modal="false" @opened="afterOpen">
      <table cellspacing="0" cellpadding="0" border="0" class="form-table">
        <tbody>
        <tr>
          <th style="width: 100px;">
            <span class="xh-star">*</span>审批意见：
          </th>
          <td colspan="3">
            <OpinionText :text="text" ref="opinionText" @getOpinion="getOpinion"/>
          </td>
        </tr>
        <tr v-if="action == 'agree' && signatureField && !secretFree">
          <th style="width: 100px;">
            <span class="xh-star">*</span>签章密码：
          </th>
          <td colspan="3">
            <el-input v-model="signaturePassword" show-password></el-input>
          </td>
        </tr>
        <tr>
          <th style="width: 100px;">附件上传：</th>
          <td colspan="3">
            <FileUpload ref="fileUpload"/>
          </td>
        </tr>
        </tbody>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm" size="small">确 定</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import OpinionText from '@/components/common/opinionText.vue';
import FileUpload from '@/components/common/fileUpload.vue';
import flow from '@/api/flow.js';
import { mapState } from 'vuex';
import { Base64 } from 'js-base64';

export default {
	name: 'taskToComplete',
  props: [
		'taskId',
		'leaderId',
		'opinion',
		'action',
		'instId',
		'signatureField', //自动签章字段
		'signatureCover', //自动签章是否覆盖
		'secretFree', //自动签章时是否免密
  ],
  components: {
    OpinionText,
		FileUpload,
  },
  data() {
    return {
      dialogVisible: false,
			dialogTitle: '',
			text: '',
      boData: {},
			opinionField: '',
      appendOpinion: false,
      data: {},
      appendStr: true,
			wrap: '\n',
			initBoAttr: '',
			signaturePassword: '',
      isSignatureCallBack: false,
      signatureLoading: null,
    };
  },
  computed: mapState({
    signatureStatus: state => state.storeProcess.signatureConfig.status,
  }),
  watch: {
    signatureStatus: function (newVal, oldVal) {
      if (newVal != 'start') {
        this.isSignatureCallBack = true;
      }
      if (newVal === 'success' && oldVal === 'ing') {
        this.doConfirm();
      } else if (newVal === 'success' && oldVal === 'fail') {

      }
      if (this.signatureLoading != null) {
        this.signatureLoading.close();
      }
    },
  },
  methods: {
    showDialog(opinionField, boData, appendOpinion, completeData) {
      this.dialogVisible = true;
      if (this.action == "agree" || this.action == "agreeTrans") {
        this.dialogTitle = "审批同意";
      } else if (this.action == "oppose" || this.action == "opposeTrans") {
        this.dialogTitle = "审批反对";
      }
      this.data = completeData;
      this.opinionField = opinionField;
      this.boData = boData;
      this.appendOpinion = appendOpinion;

    },
    afterOpen() {
      if (this.opinionField) {
        let con = document.querySelector("[model-name='data." + this.opinionField + "']");
        if (con && con.__vue__ && con.__vue__.isEditor) {
					this.wrap = '<br>';
        }
      }
      let param = {instId: this.instId, taskId: this.taskId};
      flow.getBpmSaveOpinionByTeam(param).then(resp => {
        if (resp.state && resp.value) {
          this.getOpinion(resp.value);
        } else {
					if (this.action == 'agree' || this.action == 'agreeTrans') {
						this.getOpinion('同意');
					} else if (this.action == 'oppose' || this.action == 'opposeTrans') {
						this.getOpinion('反对');
          }
        }
			});
    },
    //获取意见
    getOpinion(opinion) {
      this.text = opinion;
      let opinioValue = this.$refs.opinionText.getOpinion();
      if (this.opinionField) {
        let currentUser = this.$store.state.user.currentUserDetail.user;
				let moment = require('moment');

        let boData = this.boData;
				let filed = this.opinionField.split('.');
        if (boData[filed[0]][filed[1]] == '<p><br/></p>') {
					boData[filed[0]][filed[1]] = '';
        }
        //是否覆盖审批意见
        if (this.appendOpinion) {
          if (opinioValue) {
						boData[filed[0]][filed[1]] =
							opinioValue +
							this.wrap +
							currentUser.fullname +
							' ' +
							moment().format('YYYY-MM-DD HH:mm:ss');
          }
        } else {
          if (opinioValue) {
						opinioValue +=
							this.wrap +
							currentUser.fullname +
							' ' +
							moment().format('YYYY-MM-DD HH:mm:ss');
          }
          if (this.appendStr) {
            this.initBoAttr = boData[filed[0]][filed[1]];
          }
          if (filed.length == 2) {
            if (this.initBoAttr) {
              if (opinion) {
                boData[filed[0]][filed[1]] = this.initBoAttr + this.wrap + this.wrap + opinioValue;
              } else {
								boData[filed[0]][filed[1]] = this.initBoAttr;
              }
            } else {
              boData[filed[0]][filed[1]] = opinioValue;
            }
          }
          this.appendStr = false;
        }
        /*else if (filed.length==3 &&boData[filed[0]][filed[1]].length>0){//处理子表
          for (let i = 0; i <boData[filed[0]][filed[1]].length ; i++) {
            boData[filed[0]][filed[1]][i][filed[2]]=opinioValue;
          }
        }*/
      }
    },
    cancel() {
      this.dialogVisible = false;
			this.getOpinion('');
    },
		confirm(immediate) {
			if (this.action == 'agree' && this.signatureField) {
        let _this = this;
        this.isSignatureCallBack = false;
				this.$store.dispatch('storeProcess/initSignature', {}).then(rep => {}); //点同意按钮先初始化状态
				this.$store
					.dispatch('storeProcess/doSignature', {
          status: 'start',
          field: this.signatureField,
          isCover: this.signatureCover,
          secretFree: this.secretFree,
          password: this.signaturePassword,
        })
            .then(rep => {
              _this.signatureLoading = this.$loading({
                lock: true,
                text: '正在进行签章处理...',
                spinner: 'el-icon-loading',
							background: 'rgba(0, 0, 0, 0.7)',
              });
              // 设置5秒超时机制，如果超时则弹出提示
              setTimeout(function () {
                _this.signatureLoading.close();
                if (_this.isSignatureCallBack == false) {
								_this.$message({
									type: 'warning',
									message: '签章处理超时，请联系管理员确定是否配置签章控件。',
								});
                  return;
                }
              }, 5000);
            });
      } else {
				this.doConfirm(immediate);
      }
    },
    doConfirm() {
      if (this.$refs.fileUpload.getFiles() != '') {
        this.data.files = JSON.stringify(this.$refs.fileUpload.getFiles());
      }
      if (this.$refs.opinionText.getOpinion()) {
        this.data.opinion = this.$refs.opinionText.getOpinion();
      } else {
					this.$message({ type: 'warning', message: '请输入审批意见' });
        return;
      }
			this.data.data = Base64.encode(JSON.stringify(this.boData));
			this.$store.dispatch('storeProcess/complete', this.data).then(() => {
        //this.$parent.nextTask();
        this.$emit("nextTask");
      })
    }
  },
  mounted() {

  },
};
</script>

<style lang="scss" scoped>
</style>