<template>
  <div class="form-inline">
    <label class="control-label">{{ node.name }}({{ node.nodeId }})</label
    ><el-button type="text" size="mini" icon="icon-editor1" @click="editBtns"
      >编辑</el-button
    ><br />
    <div v-if="nodeBtns && nodeBtns.length > 0">
      <div
        v-for="btn in nodeBtns"
        :key="btn.alias"
        style="display: inline-block"
      >
        <span class="node-button">{{ btn.name }}</span>
      </div>
    </div>
    <el-dialog
      width="70%"
      :title="titleSetting"
      :visible="dialogVisibleSetting"
      :before-close="close"
      :close-on-click-modal="false"
      append-to-body
      top="8vh"
    >
      <div style="width: 100%; height: 600px">
        <el-row :gutter="24" type="flex" justify="space-around">
          <el-col :span="9">
            <div class="div_list">
              按钮列表
              <el-button
                type="text"
              
                icon="icon-append"
                @click="addButton"
                >新增</el-button
              >
            </div>
            <el-table
              :data="buttonList"
              border
              ref="htTableSetting"
              @row-click="orgRowClick"
              height="528"
            >
              <el-table-column type="index" width="40"></el-table-column>
              <el-table-column prop="alias" label="按钮别名" width="130" />
              <el-table-column prop="name" label="按钮名称" />
              <el-table-column label="操作" width="90">
                <template v-slot="{row, $index}">
                  <el-button
                    size="mini"
                    type="text"
                    @click="deleteSetting(buttonList, $index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="15">
            <div class="div_list">按钮编辑</div>
            <el-form
              :model="btn"
              data-vv-scope="settingSave"
              style="height:488px;overflow: auto; border: 1px solid #EBEBEB; padding:20px"
              v-if="JSON.stringify(btn) != '{}'"
              label-width="110px"
              label-position="left"
            >
              <ht-form-item label="按钮名称" class="is-required"
                ><ht-input
                  v-model="btn.name"
                  placeholder="请输入按钮名称"
                  autocomplete="off"
                  validate="required"
                >
                  <el-button
                    icon="icon-guojihua"
                    slot="append"
                    style="width: 80px"
                    @click="
                      editI18nMessage(
                        `flow.bnt.${defConfigData.initData.bpmDefinition.defKey}.${node.nodeId}.${btn.alias}`
                      )
                    "
                    >国际化</el-button
                  ></ht-input
                ></ht-form-item
              >
              <ht-form-item label="按钮动作" class="is-required"
                ><span v-if="btn.status != 2">{{ btn.alias }}</span>
                <ht-input
                  v-if="btn.status == 2"
                  v-model="btn.alias"
                  style="width: 170px"
                  placeholder="请输入按钮动作"
                  autocomplete="off"
                  validate="required"
                ></ht-input
                >&nbsp;
                <!-- <ht-select
                              clearable
                              v-if="btn.status==2"
                              v-model="btn.alias"
                              :options="buttonNoInitList"
                              :disabled="!btn.disabled"
                              :props="{key:'alias',value:'name'}"
                              @change="changeButtonType(btn)"
                            /> -->
                <el-select
                  v-if="btn.status == 2"
                  v-model="btn.alias"
                  @change="changeButtonType(btn)"
                >
                  <el-option
                    v-for="btn in buttonNoInitList"
                    :key="btn.alias"
                    :label="btn.name"
                    :value="btn.alias"
                    :disabled="isAliasExist(btn)"
                  ></el-option> </el-select
              ></ht-form-item>
              <ht-form-item v-if="btn.alias == 'reject'"
                ><el-tooltip
                  slot="label"
                  class="item"
                  effect="dark"
                  content="驳回方式至少选择一种"
                  placement="left-start"
                >
                  <i class="icon-notes">驳回方式</i></el-tooltip
                >
                <ht-checkbox
                  style="margin-top: -10px"
                  display-style="block"
                  :options="[
                    {key: 'backToStart', value: '驳回发起人'},
                    {key: 'rejectPre', value: '驳回上一步'},
                    {key: 'reject', value: '驳回指定节点'}
                  ]"
                  v-model="btn.rejectMode"
                  validate="required"
                />
              </ht-form-item>
        
        
              <ht-form-item v-if="btn.alias == 'reject'"
                ><el-tooltip
                  class="item"
                  effect="dark"
                  slot="label"
                  content="驳回重提模式至少选择一种"
                  placement="left-start"
                >
                  <i class="icon-notes">重提模式</i></el-tooltip
                >
                <ht-checkbox
                  style="margin-top: -10px"
                  display-style="block"
                  :options="[
                    {key: 'normal', value: '重新审批'},
                    {key: 'direct', value: '回到本节点'}
                  ]"
                  v-model="btn.rejectRecallMode"
                  validate="required"
                  @change="rejectRecallModeChange"
                />
              </ht-form-item>
              <ht-form-item
                label="默认重提模式"
                v-if="btn.alias == 'reject' && rejectRecallModeList.length > 1"
                ><ht-switch
                  v-model="btn.defaultRejectRecallMode"
                  active-text="回到本节点"
                  inactive-text="重新审批"
                  active-value="direct"
                  inactive-value="normal"
                ></ht-switch
              ></ht-form-item>
              <!--【流程定义】暂时屏蔽掉节点按钮配置下的消息模板-->
              <!-- <ht-form-item>
                <el-tooltip
                  slot="label"
                  class="item"
                  effect="dark"
                  content="配置按钮操作成功之后发送消息的模板"
                  placement="left-start"
                >
                  <i class="el-icon-warning">消息模板:</i></el-tooltip
                >
                <el-button
                  type="primary"
                  @click="$refs.flowMsgSendConfig.showDailog()"
                  >{{ btn.msgConfig ? '编辑' : '新增' }}</el-button
                ></ht-form-item
              > -->
              <ht-form-item label="强制签收" v-if="btn.alias == 'lockUnlock'">
                <el-checkbox style="margin-top: -10px" v-model="btn.isLock"
                  >强制签收</el-checkbox
                >
              </ht-form-item>
              <ht-form-item v-if="btn.supportScript">
                <el-tooltip
                  slot="label"
                  class="item"
                  effect="dark"
                  content="javascript脚本,在点击确认按钮之前做些处理，参数：_req,boData,_this，返回:true/false。返回false时不做提交动作。"
                  placement="left-start"
                >
                  <span><i class="icon-notes" style="margin-right:4px"></i>前置脚本</span></el-tooltip
                >
                <HtMonacoEditor
                  v-if="showCodeEdie"
                  ref="mycodeAfter"
                  v-model="btn.beforeScript"
                  height="300px"
                />
              </ht-form-item>
              <ht-form-item v-if="btn.supportScript && isSupportAfter(btn)">
                <el-tooltip
                  slot="label"
                  class="item"
                  effect="dark"
                  content="javascript脚本,在点击确认按钮之后做些处理，参数：_req,boData,_this，返回:true/false。返回false时不做提交动作。"
                  placement="left-start"
                >
                <span>  <i class="icon-notes" style="margin-right:4px"></i>后置脚本</span></el-tooltip
                >
                <HtMonacoEditor
                  v-if="showCodeEdie"
                  ref="mycodeAfter"
                  v-model="btn.afterScript"
                  height="300px"
                />
              </ht-form-item>
              <ht-form-item v-if="btn.supportScript">
                <el-tooltip
                  slot="label"
                  class="item"
                  effect="dark"
                  content="java脚本，控制按钮是否显示，返回 false不显示，返回 true显示。上下文变量：1.流程变量。2.BO数据返回:true/false。"
                  placement="left-start"
                >
                  <span><i class="icon-notes" style="margin-right:4px"></i>groovy脚本</span></el-tooltip
                >
                <HtMonacoEditor
                  v-if="showCodeEdie"
                  ref="mycodeAfter"
                  language="java"
                  v-model="btn.groovyScript"
                  height="300px"
                />
              </ht-form-item>
              <ht-form-item
                v-if="btn.supportScript && btn.alias == 'endProcess'"
              >
                <el-tooltip
                  slot="label"
                  class="item"
                  effect="dark"
                  content="java脚本，任务处理后执行的java脚本。上下文变量：1.com.fasterxml.jackson.databind.node.ObjectNode busDataObjectNode  2.data(表单数据 类型为ObjectNode) 3. instance(流程实例对象 类型为DefaultBpmProcessInstance)"
                  placement="left-start"
                >
                  <i class="icon-notes">提交后执行</i></el-tooltip
                >
                <HtMonacoEditor
                  v-if="showCodeEdie"
                  ref="mycodeAfter"
                  language="java"
                  v-model="btn.completeEventGroovyScript"
                  height="300px"
                />
              </ht-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div style="text-align: right; padding: 20px">
        <el-button size="small" @click="close">取 消</el-button>
        <el-button type="primary" size="small" @click="saveButton"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <FlowMsgSendConfig
      :defId="defConfigData.initData.bpmDefLayout.defId"
      :nodeId="node.nodeId"
      type="1"
      v-model="btn.msgConfig"
      ref="flowMsgSendConfig"
    />
    <i18n-message-edit ref="i18nMessageEdit" :messageKey="i18nMessageKey" />
  </div>
</template>

<script>
import req from '@/request.js'
import {Message} from 'element-ui'
const FlowMsgSendConfig = () =>
  import('@/components/flow/FlowMsgSendConfig.vue')
import i18nMessageEdit from '@/components/system/I18nMessageEdit.vue'
export default {
  name: 'FlowNodeBtns',
  components: {FlowMsgSendConfig, i18nMessageEdit},
  props: {
    //任务节点信息
    node: {
      type: Object,
      required: true
    },
    //流程配置信息
    defConfigData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      titleSetting: '设置按钮', //某个节点按钮的标题
      nodeBtns: [], //单个节点按钮的配置信息
      dialogVisibleSetting: false, //是否显示设置节点按钮侧边栏
      buttonList: [], //节点按钮已有的按钮
      buttonNoInitList: [], //节点按钮可新增的按钮
      btn: {}, //单个节点按钮的配置信息
      cmOptions1: {
        value: '',
        mode: 'vue',
        readOnly: false,
        smartIndent: true,
        tabSize: 1,
        theme: 'base16-light',
        lineNumbers: true,
        line: true
      },
      cmOptions2: {
        value: '',
        mode: 'groovy',
        readOnly: false,
        smartIndent: true,
        tabSize: 1,
        theme: 'base16-light',
        lineNumbers: true,
        line: true
      },
      showCodeEdie: true,
      codemirrorStyle:
        'width:' + ((document.body.clientWidth * 0.7 - 40) * 0.63 - 180) + 'px',
      blackBtns: ['saveDraft', 'hangUp', 'cancelHangUp'],
      //目前需要后置JS的按钮。
      afterScriptBtns: ['agree', 'reject', 'saveDraft', 'oppose'],
      i18nMessageKey: ''
    }
  },
  computed: {
    rejectRecallModeList() {
      return (
        (this.btn.rejectRecallMode && this.btn.rejectRecallMode.split(',')) ||
        []
      )
    },
      backUserModeList: function(){
      let list = [{key: 'normal', value: '节点配置人'}, {key: 'history', value: '历史处理人'}]
      if (this.node.type == 'signTask') {
        list.push({key: 'assignHistory', value: '指定历史处理人'})
      }
      return list;
    }
  },
  methods: {
    isSupportAfter(btn) {
      if (this.afterScriptBtns.indexOf(btn.alias) != -1) {
        return true
      }
    },
    //判断按钮是否已经存在。
    isAliasExist(nBtn) {
      for (let i = 0, btn; (btn = this.buttonList[i++]); ) {
        if (btn.alias == nBtn.alias && this.btn !== btn) {
          return true
        }
      }
      return false
    },
    //选择节点按钮可新增的按钮时
    changeButtonType(obj) {
      if (obj.alias) {
        let rtn = this.isAliasExist(obj)
        if (rtn) {
          obj.alias = ''
          Message.warning('新增的按钮已存在')
          return
        } else {
          this.$confirm('是否确认添加？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              obj.status = 1
              obj.name = this.getName(obj.alias)
            })
            .catch(() => {})
        }
      } else {
        obj.status = 2
      }
    },
    //根据按钮别名获取按钮名称
    getName(alias) {
      for (let i = 0; i < this.buttonNoInitList.length; i++) {
        let obj = this.buttonNoInitList[i]
        if (alias == obj.alias) {
          return obj.name
        }
      }
      return ''
    },
    //点击列表某一条数据时触发  groovyScript beforeScript
    orgRowClick(row, column, event) {
      if (column.label != '操作') {
        row.groovyScript = row.groovyScript || ''
        row.beforeScript = row.beforeScript || ''
        let this_ = this
        this.showCodeEdie = false
        setTimeout(function() {
          this_.$set(this_, 'btn', row)
          this_.showCodeEdie = true
        }, 50)
      }
    },
    //保存按钮
    saveButton() {
      const this_ = this
      this_.$validator.validateAll('settingSave').then(result => {
        if (result) {
          let param = {
            nodeId: this_.node.nodeId,
            defId: this_.defConfigData.initData.bpmDefLayout.defId //流程定义ID
          }
          param.btns = this_.buttonList //任务的节点按钮
          let btnArr = []
          for (let i = 0, b; (b = param.btns[i++]); ) {
            if (b.alias && b.name) {
              if (b.alias == 'reject' && !b.rejectMode) {
                Message.warning('驳回按钮中的驳回模式至少选择一种')
                return
              }
              delete b.status
              btnArr.push(b)
            }
          }
          param.btns = btnArr
          //保存节点按钮
          req.post('${bpmModel}/flow/def/v1/saveNodeBtns', param).then(res => {
            if (res.data.state) {
              Message.success(res.data.message)
              this_.dialogVisibleSetting = false //关闭侧边栏
              this_.nodeBtns = _.cloneDeep(btnArr)
            }
          })
        } else {
          let arr = this_.$validator.errors.items.filter(
            item => item.scope == 'settingSave'
          )
          let errorLength = arr.length
          this_.$message({
            showClose: true,
            message: `有${errorLength}个字段未通过校验，请正确填写表单内容。`,
            type: 'warning'
          })
        }
      })
    },
    //新增按钮
    addButton() {
      let btn = {name: '', alias: '', status: 2, supportScript: true}
      this.buttonList.push(btn)
      this.btn = btn
    },
    //编辑任务节点按钮
    editBtns(nodeId) {
      this.dialogVisibleSetting = true //显示设置节点按钮侧边栏
      this.titleSetting =
        '设置按钮' + this.node.name + '(' + this.node.nodeId + ')' //设置某个节点按钮的标题
      this.getButtons(1) //获取已有的按钮
      this.getButtons(2) //获取节点按钮可新增的按钮
    },
    //获取节点按钮  type：0-初始化的按钮，1-已有的按钮，2-可新增的按钮（这个方案已经丢弃）
    //现在全都是从系统配置里面拿
    getButtons(action) {
      const this_ = this
      let defId = this_.defConfigData.initData.bpmDefLayout.defId //流程定义ID
      req
        .post(
          '${bpmModel}/flow/def/v1/getNodeSet?defId=' +
            defId +
            '&nodeId=' +
            this_.node.nodeId +
            '&action=' +
            action
        )
        .then(function(data) {
          data = data.data
          //屏蔽一些多余的按钮配置
          for (let i = data.length - 1; i >= 0; i--) {
            if (
              data[i].alias == 'commu' ||
              data[i].alias == 'startCommu' ||
              data[i].alias == 'instanceTrans' ||
              data[i].alias == 'backToStart'
            ) {
              data.splice(i, 1)
            }
          }
          if (action == 2) {
            this_.setStatus(data, 2)
            this_.buttonNoInitList = data
          } else if (action == 1) {
            this_.setStatus(data, 1)
            this_.buttonList = data
          }
          // this_.buttonList=data;
          // this_.buttonNoInitList=Object.assign([],data);
        })
    },
    //按钮状态 1-已有的按钮，2-可新增的按钮
    setStatus(data, status) {
      for (let i = 0; i < data.length; i++) {
        data[i].status = status
      }
    },
    //关闭设置节点按钮列弹框
    close() {
      this.dialogVisibleSetting = false
    },
    //删除按钮
    deleteSetting(list, index) {
      list.splice(index, 1)
      this.btn = {} //清空单个节点按钮的配置信息
    },
    // 选择驳回重提模式
    rejectRecallModeChange() {
      this.$nextTick(() => {
        if (this.rejectRecallModeList.length < 2) {
          this.btn.defaultRejectRecallMode = ''
        } else if (!this.btn.defaultRejectRecallMode) {
          this.btn.defaultRejectRecallMode = 'normal'
        }
      })
    },
 
    editI18nMessage(data) {
      this.i18nMessageKey = data
      this.$refs.i18nMessageEdit.handleOpen()
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
    this.nodeBtns = this.defConfigData.nodeSetData.nodeBtnMap[this.node.nodeId] //获取单个节点按钮的配置信息
    
  }
}
</script>

<style lang="scss" scoped>
div >>> .el-dialog__body {
  padding: 10px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
.ht_tr {
  width: 100%;
}
.div_list {
  height: 30px;
  line-height: 30px;
  font-size: 16px;
  color: #333;
  font-weight: bold;
  padding-left: 10px;
  margin-bottom: 10px;
}
>>> label.el-checkbox {
  margin: 5px 10px 0 0;
}
.ht {
  width: 300px;
}
.form-inline {
  float: left;
  width: 100%;
  padding-bottom: 16px;
}
.left-label {
  width: 18%;
  float: left;
}
.control-label {
  word-break: break-all;
  text-align: right;
  color: #545252;
  font-size: 12px;
  padding: 0px 10px !important;
  font-weight: bold;
  line-height: 35px;
}
div >>> .box-card {
  margin-bottom: 20px;
}

div >>> .box-card .clearfix {
  padding-top: 20px;
}

div >>> .el-collapse-item__header {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  font-weight: bold;
}
.node-button {
  height: 28px;
  line-height: 28px;
  background: rgb(64, 158, 255);
  color: #fff;
  text-align: center;
  display: inline-block;
  margin: 3px;
  padding: 0px 12px;
  border-radius: 2px;
}
.icon-notes {
  margin-right: 5px;
}

// div>>>.el-button{
//    padding: 7px;
//    margin-right: 10px;
//    margin-left: 0px !important;
// }
</style>
