<template>
  <div>
    <el-dialog
      width="70%"
      top="8vh"
      title="设置消息模板"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form :model="configData" data-vv-scope="msgTemplateForm">
        <el-row v-show="type != 1">
          <el-col>
            <ht-form-item label="发送时机" label-width="120px">
              <ht-radio
                :options="[
                  {key: 'taskCreate', value: '任务创建'},
                  {key: 'taskComplete', value: '任务完成'},
                ]"
                v-model="configData.moment"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ht-form-item label="消息接收人" label-width="120px">
              <el-button
                size="mini"
                type="primary"
                @click="
                  msgRecieverVisible = true
                  tempReceivers = JSON.parse(
                    JSON.stringify(configData.receivers)
                  )
                "
                >设置</el-button
              >
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ht-form-item label="模板参数" label-width="120px">
              流程变量：
              <el-link
                type="primary"
                v-for="param in templateParams"
                :key="param.key"
                @click="addTemplateParam(param.value)"
                >{{ param.label }}</el-link
              >
              表单变量：<FlowVarSelector
                :defId="defId"
                type="1"
                :includeBpmConstants="false"
                @node-click="addTemplateFormParam"
                size="mini"
              />
              <br />选择模板参数的时候，请注意光标位置(光标位置支持[标题，纯文本])。
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ht-form-item label="标题" label-width="120px">
              <ht-input
                ref="subject"
                v-model="configData.subject"
                type="textarea"
                :cols="100"
                :validate="{required: true}"
                :autosize="{minRows: 1, maxRows: 4}"
                @focus="activeTextarea = 'subject'"
                :maxlength="50"
                :showWordLimit="true"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ht-form-item label="纯文本" label-width="120px">
              <ht-input
                ref="plain"
                v-model="configData.plain"
                type="textarea"
                :cols="100"
                :autosize="{minRows: 2, maxRows: 8}"
                @focus="activeTextarea = 'plain'"
                :maxlength="200"
                :showWordLimit="true"
              />
              <el-button @click="$refs.eipMsgTemplateDialog.showDialog()"
                >选择模板</el-button
              >
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <ht-form-item label="模版体HTML" label-width="120px">
              <htEditor
                v-model="configData.html"
                :config="myConfig"
                :focus="htEditorFocus"
                ref="htEditor"
              ></htEditor>
            </ht-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      width="70%"
      top="8vh"
      title="设置消息接收人"
      v-if="msgRecieverVisible"
      :visible.sync="msgRecieverVisible"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form v-form data-vv-scope="receiverSetForm">
        <el-row class="externalUser-row">
          <el-col>
            <ht-form-item label="当前节点审批人" label-width="200px">
              <el-checkbox v-model="tempReceivers.curAuditor"></el-checkbox>
            </ht-form-item>
            <ht-form-item label="当前节点传阅人" label-width="200px">
              <el-checkbox v-model="tempReceivers.curCopyTo"></el-checkbox>
            </ht-form-item>
            <ht-form-item label="历史节点处理人" label-width="200px">
              <el-select
                size="mini"
                v-model="tempReceivers.hisNode"
                placeholder="请选择"
                clearable
                style="width: 250px"
              >
                <el-option
                  v-for="item in nodeList"
                  :key="item.nodeId"
                  :label="`${item.name}(${item.nodeId})`"
                  :value="item.nodeId"
                >
                </el-option>
              </el-select>
            </ht-form-item>
            <ht-form-item label="发起人" label-width="200px">
              <el-checkbox v-model="tempReceivers.startor"></el-checkbox>
            </ht-form-item>
            <ht-form-item label="变量(用户账号)" label-width="200px">
              <el-input
                style="width: 200px"
                size="mini"
                v-model="tempReceivers.var.name"
                :disabled="true"
              ></el-input>
              <FlowVarSelector
                :defId="defId"
                @node-click="varTreeOnConfirm"
                :removeSub="false"
                size="mini"
              />
              <el-button
                @click="tempReceivers.var = {}"
                icon="el-icon-refresh-right"
                size="mini"
              ></el-button>
            </ht-form-item>
            <ht-form-item label="系统用户" label-width="200px">
              <ht-user-selector-input
                :appendToBody="true"
                v-model="tempReceivers.sysUser.name"
                :config="{
                  id: 'tempReceivers.sysUser.userId',
                  account: 'tempReceivers.sysUser.account',
                }"
              />
            </ht-form-item>
            <ht-form-item label="外部用户" label-width="200px">
              <el-button
                size="mini"
                type="primary"
                @click="tempReceivers.externalUser.push({})"
                >添加</el-button
              >
              <el-table
                size="mini"
                border
                :data="tempReceivers.externalUser"
                style="width: 100%"
              >
                <el-table-column prop="name" label="姓名">
                  <template slot-scope="scope">
                    <ht-input
                      size="mini"
                      v-model="scope.row.name"
                      autocomplete="off"
                    ></ht-input>
                  </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机">
                  <template slot-scope="scope">
                    <div class="flexHen">
                      <ht-input
                        size="mini"
                        v-model="scope.row.mobile"
                        autocomplete="off"
                        :validate="{
                          mobile: !/^\${[\w\.]+}/.test(scope.row.mobile),
                        }"
                      ></ht-input>
                      <FlowVarSelector
                        :defId="defId"
                        @node-click="
                          varTreeOnConfirm(arguments[0], scope.row, 'mobile')
                        "
                        :removeSub="false"
                        size="mini"
                        style="margin-left: 5px"
                      />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="email" label="邮箱">
                  <template slot-scope="scope">
                    <div class="flexHen">
                      <ht-input
                        size="mini"
                        v-model="scope.row.email"
                        autocomplete="off"
                        :validate="{
                          email: !/^\${[\w\.]+}/.test(scope.row.email),
                        }"
                      ></ht-input>
                      <FlowVarSelector
                        :defId="defId"
                        @node-click="
                          varTreeOnConfirm(arguments[0], scope.row, 'email')
                        "
                        :removeSub="false"
                        size="mini"
                        style="margin-left: 5px"
                      />
                    </div>
                  </template>
                </el-table-column>

                <el-table-column label="操作" width="80">
                  <template slot-scope="scope">
                    <el-button
                      @click="tempReceivers.externalUser.remove(scope.row)"
                      type="text"
                      size="small"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </ht-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="msgRecieverVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmReceiverSet">确 定</el-button>
      </div>
    </el-dialog>

    <eip-msg-template-dialog
      ref="eipMsgTemplateDialog"
      @onConfirm="templateConfirm"
      append-to-body
    />
  </div>
</template>

<script>
import utils from '@/hotent-ui-util.js'
import {mapState, mapAction} from 'vuex'
const htEditor = () => import('@/components/common/HtEditor.vue')
const EipMsgTemplateDialog = () =>
  import('@/components/dialog/EipMsgTemplateDialog.vue')
const FlowVarSelector = () => import('@/components/flow/FlowVarSelector.vue')

import {Base64} from 'js-base64'
import Debounce from '../vueUeditorWrap/utils/Debounce'

export default {
  props: {
    type: String,
    value: String,
    defId: String,
    nodeId: String,
  },
  components: {
    htEditor,
    EipMsgTemplateDialog,
    FlowVarSelector,
  },
  data() {
    return {
      defaultData: {
        moment: 'taskComplete',
        subject: '',
        plain: '',
        html: '',
        receivers: {externalUser: []},
      },
      configData: {
        moment: 'taskComplete',
        subject: '',
        plain: '',
        html: '',
        receivers: {externalUser: []},
      },
      myConfig: {
        initialFrameHeight: 170,
        UEDITOR_HOME_URL:
          window.location.origin +
          '/' +
          window.location.pathname.split('/')[1] +
          '/static/ueditor/',
        toolbars: [
          [
            // 'source', //源代码
            'undo', //撤销
            'bold', //加粗
            'indent', //首行缩进
            'italic', //斜体
            'underline', //下划线
            'strikethrough', //删除线
            'subscript', //下标
            'fontborder', //字符边框
            'superscript', //上标
            'formatmatch', //格式刷
            'forecolor', //字体颜色
            'justifyleft', //居左对齐
            'justifycenter', //居中对齐
            'justifyright', //居右对齐
            'justifyjustify', //两端对齐
            'fontfamily', //字体
            'fontsize', //字号
            'insertorderedlist', //有序列表
            'insertunorderedlist', //无序列表
            'lineheight', //行间距
            'inserttable', //插入表格
            'link', //超链接
            'simpleupload', //单图上传
            'insertimage', //多图上传
            'attachment', //附件
          ],
        ],
        // 初始容器宽度
        initialFrameWidth: '100%',
        zIndex: 9999,
        enableAutoSave: false,
        readonly: false,
      },
      templateType: [],
      dialogVisible: false,
      templateParams: [
        {
          key: 1,
          value: '${instSubject}',
          label: '流程实例标题',
        },
        {
          key: 2,
          value: '${nodeName}',
          label: '节点名称',
        },
        {
          key: 3,
          value: '${taskSubject}',
          label: '任务标题',
        },
        {
          key: 4,
          value: '${cause}',
          label: '原因',
        },
        {
          key: 5,
          value: '${delegate}',
          label: '委托人',
        },
        {
          key: 6,
          value: '${agent}',
          label: '代理人',
        },
        {
          key: 7,
          value: '${receiver}',
          label: '收信人',
        },
        {
          key: 8,
          value: '${sender}',
          label: '发送人',
        },
      ],
      activeTextarea: '',
      msgRecieverVisible: false,
      tempReceivers: {},
      nodeList: [],
    }
  },
  computed: mapState({
    defConfigData: (state) => state.flow.defConfigData,
    header: (state) => {
      return {
        Authorization: `Bearer ${state.login.currentUser.token}`,
      }
    },
    actionUrl: function () {
      return window.context.portal + '/system/file/v1/upload'
    },
  }),
  watch: {},
  mounted() {},
  methods: {
    htEditorFocus() {
      this.activeTextarea = 'htEditor'
    },
    confirmReceiverSet() {
      this.$validator.validateAll('receiverSetForm').then((r) => {
        if (!r) {
          this.$message.warning('表单校验不通过，请检查表单')
          return
        }
        if (
          !this.tempReceivers.curAuditor &&
          !this.tempReceivers.curCopyTo &&
          !this.tempReceivers.hisNode &&
          !this.tempReceivers.startor &&
          (!this.tempReceivers.externalUser ||
            this.tempReceivers.externalUser.length == 0) &&
          (!this.tempReceivers.var || !this.tempReceivers.var.name) &&
          (!this.tempReceivers.sysUser || !this.tempReceivers.sysUser.userId)
        ) {
          this.$message.warning('请选择消息接收人')
          return
        }
        if (this.tempReceivers.externalUser) {
          let emptyUserIdx = []
          for (
            let index = 0;
            index < this.tempReceivers.externalUser.length;
            index++
          ) {
            const u = this.tempReceivers.externalUser[index]
            if (!u.mobile && !u.email) {
              emptyUserIdx.push(index + 1)
            }
          }
          if (emptyUserIdx.length > 0) {
            this.$message.warning(
              '外部用户第[' +
                emptyUserIdx.join(',') +
                ']行，手机号和邮箱至少填写一个'
            )
            return
          }
        }
        this.configData.receivers = JSON.parse(
          JSON.stringify(this.tempReceivers)
        )
        this.msgRecieverVisible = false
      })
    },
    varTreeOnConfirm(node, subRow, field) {
      let keyStr = node.name
      let source = 'BO'
      if (node.nodeType == 'var') {
        keyStr = node.name
        source = 'flowVar'
      } else {
        keyStr = node.path + '.' + node.name
      }
      let json = {
        source: source,
        name: keyStr,
        executorType: 'user',
        userValType: 'account',
      }
      if (subRow && field) {
        this.$set(subRow, field, '${' + keyStr + '}')
      } else {
        this.tempReceivers['var'] = json
      }
    },
    templateConfirm(data) {
      this.$set(this.configData, 'plain', data)
    },
    addTemplateFormParam(data) {
      this.$refs.htEditor.editorInstance.execCommand(
        'inserthtml',
        data.pathValue
      )
    },
    addTemplateParam(param) {
      if (!this.activeTextarea || this.activeTextarea == 'htEditor') {
        this.$refs.htEditor.editorInstance.execCommand('inserthtml', param)
      } else {
        let textInput =
          this.$refs[this.activeTextarea].$refs.inputEle.$refs.textarea
        let insert = textInput.selectionStart
        this.configData[this.activeTextarea] =
          textInput.value.substr(0, insert) +
          param +
          textInput.value.substr(insert)
      }
    },
    confirm() {
      utils
        .validateForm(this, 'msgTemplateForm')
        .then((r) => {
          if (!this.configData.html && !this.configData.plain) {
            this.$message.error(`纯文本和模板体HTML至少需要填写一个`)
            return
          }
          this.$emit('input', Base64.encode(JSON.stringify(this.configData)))
          this.dialogVisible = false
        })
        .catch((items) => {
          this.$message.error(`请填写标题`)
        })
        .finally(() => {
          this.loading = false
        })
    },
    showDailog() {
      if (!this.value) {
        this.configData = JSON.parse(JSON.stringify(this.defaultData))
      } else {
        this.configData = JSON.parse(Base64.decode(this.value))
      }
      if (this.type == '1') {
        this.configData.moment = 'taskComplete'
      }

      this.nodeList = []
      for (const node of this.defConfigData.nodeSetData.nodes) {
        if (node.nodeId == this.nodeId) {
          this.curNode = node
        } else {
          if (node.type == 'signTask' || node.type == 'userTask') {
            this.nodeList.push(node)
          }
        }
      }
      this.configData.receivers = this.configData.receivers || {}
      this.configData.receivers.externalUser =
        this.configData.receivers.externalUser || []
      this.configData.receivers.var = this.configData.receivers.var || {}
      this.configData.receivers.sysUser =
        this.configData.receivers.sysUser || {}

      this.dialogVisible = true
    },
  },
  created() {
    this.$validator = this.$root.$validator
  },
}
</script>

<style lang="scss" scoped>
.el-link {
  margin: 0 5px;
}

div /deep/ .el-radio-group {
  line-height: 16px;
}
div /deep/.el-form-item--small.el-form-item {
  margin-bottom: 16px;
}
.externalUser-row {
  min-height: 500px;
  max-height: 550px;
  overflow: auto;
}

.externalUser-row /deep/ .el-form-item__error {
  z-index: 1000;
  margin: -1px 0 0 5px;
}

.externalUser-row /deep/ {
  td {
    padding: 0 0;
  }
  .cell {
    margin: 12px 0 0 0;
    & > div {
      margin-bottom: 12px;
    }
  }
}

/deep/ .el-input__count {
  line-height: 20px;
}
.flexHen {
  display: flex;
}
</style>
