<template>
  <!-- 催办 -->
  <el-dialog
    title="任务催办"
    :visible.sync="showTaskUrgent"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="container">
      <div v-if="nodeList.length" class="row">
        <div class="label">催办节点：</div>
        <div class="value">
          <el-radio-group v-model="selectedNodeId">
            <el-radio
              v-for="item in nodeList"
              :key="item.nodeId"
              :label="item.nodeId"
            >
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <div class="row">
        <div class="label required">被催办人：</div>
        <div class="value">
          <el-checkbox
            v-if="showAppointee && assigneeUsers && assigneeUsers.length > 0"
            v-model="checked"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group v-if="showAppointee" v-model="appointee">
            <el-checkbox
              v-for="item in assigneeUsers"
              :key="item.id"
              :label="item"
            >
              {{ item.fullname }}
            </el-checkbox>
          </el-checkbox-group>

          <div v-if="showSelectNode">请先选择催办节点</div>
          <div v-if="!hasTaskUser">要催办的任务无审批人</div>
        </div>
      </div>

      <div class="row">
        <div class="label">是否催办秘书：</div>
        <div class="value">
          <el-radio v-model="appointeeSecretary" label="0">否</el-radio>
          <el-radio v-model="appointeeSecretary" label="1">是</el-radio>
        </div>
      </div>

      <div class="row">
        <div class="label required">催办方式：</div>
        <div class="value urgent-type">
          <el-radio-group v-model="urgentType">
            <el-radio label="mail">邮箱</el-radio>
            <el-radio v-if="showMessageType('sms')" label="sms">短信</el-radio>
            <el-radio v-if="showSmsApproval" label="smsApproval">
              短信审批
            </el-radio>
            <el-radio label="inner" v-if="showMessageType('inner')">
              站内消息
            </el-radio>
            <el-radio label="voice" v-if="showMessageType('voice')">
              语音
            </el-radio>
            <el-radio
              label="wxEnterprise"
              v-if="showMessageType('wxEnterprise')"
            >
              微信
            </el-radio>
            <el-radio label="dingTalk" v-if="showMessageType('dingTalk')">
              钉钉
            </el-radio>
            <el-radio label="flyBook" v-if="showMessageType('flyBook')">
              飞书
            </el-radio>
          </el-radio-group>

          <el-dropdown
            class="dropdown"
            split-button
            type="primary"
            @command="handleCommand"
          >
            可选变量
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in dropdownMenu"
                :key="item.id"
                :command="item.command"
              >
                {{ item.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <div v-if="urgentType != 'smsApproval'" class="row">
        <div class="label required">催办内容：</div>
        <div class="value">
          <el-input
            v-if="urgentType == 'mail'"
            v-model="contentMail"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="请输入催办内容"
            maxlength="100"
            show-word-limit
          ></el-input>
          <el-input
            v-else-if="['sms', 'smsApproval'].includes(urgentType)"
            v-model="contentSms"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="请输入催办内容"
            maxlength="100"
            show-word-limit
          ></el-input>
          <el-input
            v-else
            v-model="contentOthers"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="请输入催办内容"
            maxlength="100"
            show-word-limit
          ></el-input>
        </div>
      </div>

      <div v-else class="row">
        <div class="label">短信审批备注：</div>
        <div class="value">
          <el-input
            v-model="contentSms"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="短信审批备注会显示在发出的短信内容中,可在备注中对流程信息做补充说明,但请勿涉及敏感内容。"
          ></el-input>
          <div class="tips">
            注意：因为短信渠道未加密，发送的短信内容中不会包含详细批呈信息，请在短信催办前先与审批处理人做好沟通。
          </div>
        </div>
      </div>
    </div>

    <div slot="footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { defGet, getExcutorByInstId, sendBpmTaskUrgent } from '@/api/process'
  export default {
    name: 'TaskUrgent',
    props: {
      defId: {
        type: String,
        default: '',
      },
      instId: {
        type: String,
        default: '',
      },
      subject: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        urgentType: 'mail', // 催办凡事
        hasTaskUser: true, // 是否有任务审批人
        showTaskUrgent: false,

        nodeList: [],
        nodeDefMap: {},
        selectedNodeId: '',

        appointee: [], //被催办人
        appointeeSecretary: '0', // 是否催办秘书
        contentSms: '', //短信催办内容
        contentMail: '', //邮件催办内容
        contentOthers: '', //其他催办内容
        checked: true,
        dropdownMenu: [
          { id: 1, label: '催办人', command: '{催办人:promoter}' },
          { id: 2, label: '被催办人', command: '{被催办人:appointee}' },
          { id: 3, label: '流程编号', command: '{流程编号:instId}' },
          { id: 4, label: '流程标题', command: '{流程标题:subject}' },
          { id: 5, label: '流程发起人', command: '{流程发起人:sponsor}' },
          { id: 6, label: '任务节点名称', command: '{任务节点名称:nodeName}' },
        ],
      }
    },
    watch: {
      appointee: {
        handler(val) {
          if (
            val &&
            this.assigneeUsers &&
            val.length === this.assigneeUsers.length
          ) {
            this.checked = true
          } else {
            this.checked = false
          }
        },
        immediate: true,
        deep: true,
      },
    },
    computed: {
      showSms() {
        const node = this.nodeDefMap[this.selectedNodeId]
        return node && !node.localProperties.allowSmsApproval
      },
      showSmsApproval() {
        const node = this.nodeDefMap[this.selectedNodeId]
        return node && node.localProperties.allowSmsApproval
      },
      showAppointee() {
        return this.nodeDefMap[this.selectedNodeId]
      },
      showSelectNode() {
        const node = this.nodeDefMap[this.selectedNodeId]
        return node && node.assigneeUsers.length == 0 && this.hasTaskUser
      },
      assigneeUsers() {
        let assigneeUsers =
          this.nodeDefMap[this.selectedNodeId] &&
          this.nodeDefMap[this.selectedNodeId].assigneeUsers
        return assigneeUsers
          ? this.nodeDefMap[this.selectedNodeId].assigneeUsers
          : []
      },
    },
    methods: {
      // 全选
      handleCheckAllChange(val) {
        this.appointee = val ? this.assigneeUsers : []
      },
      showMessageType(label) {
        const node = this.nodeDefMap[this.selectedNodeId]
        return (
          node &&
          node.localProperties.notifyType &&
          node.localProperties.notifyType.includes(label)
        )
      },
      handleCommand(command) {
        if (this.urgentType == 'mail') {
          this.contentMail = this.contentMail + command
        } else if (['sms', 'smsApproval'].includes(this.urgentType)) {
          this.contentSms = this.contentSms + command
        } else {
          this.contentOthers = this.contentOthers + command
        }
      },
      handleOpen() {
        // 根据实例Id获取当前任务节点审批人
        getExcutorByInstId(this.instId, (data) => {
          if (data) {
            const { length } = data
            this.nodeList = data
            if (length == 0) {
              this.hasTaskUser = false
            }
            if (length == 1) {
              this.selectedNodeId = data[0].nodeId
            }

            data.forEach((nodeDef) => {
              this.nodeDefMap[nodeDef.nodeId] = nodeDef
            })
            //默认全选

            this.handleCheckAllChange(true)
          }
        })

        // 根据流程定义Id获取流程信息
        defGet(this.defId, (data) => {
          if (data) {
            const { urgentMailTel, urgentSmsTel } = data
            this.contentSms = urgentSmsTel ? urgentSmsTel : ''
            this.contentMail = urgentMailTel ? urgentMailTel : ''
          }
        })

        this.showTaskUrgent = true
      },
      cancel() {
        this.showTaskUrgent = false
      },
      confirm() {
        let content = ''
        if (this.urgentType == 'mail') {
          content = this.contentMail
        } else if (this.urgentType == 'sms') {
          content = this.contentSms
        } else {
          content = this.contentOthers
        }

        if (!this.selectedNodeId) {
          this.$message.warning('被催办人不能为空')
          return
        }
        if (this.appointee.length == 0) {
          this.$message.warning('请选择被催办人')
          return
        }
        if (content == '') {
          this.$message.warning('请输入催办内容')
          return
        }

        const appointeeIds = []
        const appointeeNames = []
        this.appointee.forEach((item) => {
          appointeeIds.push(item.userId)
          appointeeNames.push(item.fullname)
        })

        const { userId, username } = this.$store.state.user
        const data = {
          type: this.urgentType,
          instId: this.instId,
          subject: this.subject,
          content,
          promoter: username,
          promoterId: userId,
          nodeId: this.selectedNodeId,
          nodeName: this.nodeDefMap[this.selectedNodeId].name,
          appointee: appointeeNames.join(','),
          appointeeId: appointeeIds.join(','),
          appointeeSecretary: this.appointeeSecretary == '1',
        }
        sendBpmTaskUrgent(data, (res) => {
          if (res.state) {
            this.showTaskUrgent = false
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .container {
    height: 100%;
    .row {
      display: flex;
      align-items: center;
      border: 1px solid #eee;
      .label {
        width: 120px;
        text-align: right;
        padding: 10px 20px;
      }
      .dropdown {
        width: 150px;
        float: right;
      }
      .value {
        flex: 1;
        padding: 10px 20px;
        border-left: 1px solid #eee;
      }
      .urgent-type {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .el-radio {
          white-space: normal;
          margin-top: 10px;
        }
      }
      .tips {
        font-size: 12px;
        margin-top: 10px;
      }
      .required {
        &::before {
          display: inline-block;
          content: '*';
          color: #f00;
          margin-right: 5px;
        }
      }
      &:not(:last-child) {
        border-bottom: none;
      }
    }
  }
</style>
