//任务催办
<template>
  <div>
    <van-popup
      v-model="show"
      round
      duration="0.5"
      :close-on-click-overlay="false"
      safe-area-inset-bottom
      position="bottom"
      v-if="show"
      style="max-height: 80%"
    >
      <van-nav-bar
        :title="title"
        left-text="取消"
        right-text="确定"
        @click-left="show = false"
        @click-right="onClickRight"
        class="popup_header_fixed"
      />
      <van-form
        ref="form"
        v-form
        validate-trigger="onChange"
        class="popup_header_margin"
      >
        <van-field
          v-if="nodeList.length > 0"
          label="催办节点"
          v-model="form.selectedNodeId"
          input-align="right"
        >
          <template #input>
            <van-radio-group
              v-model="form.selectedNodeId"
              direction="horizontal"
            >
              <van-radio
                v-for="item in nodeList"
                :key="item.nodeId"
                :name="item.nodeId"
              >
                {{ item.name }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          label="被催办人"
          required
          name="ht-user-selector-input"
          :rules="[
            {
              required: true,
              message: `请选择被催办人`,
            },
          ]"
          v-model="form.appointee"
          input-align="right"
          placeholder="请选择"
          class="contentButton"
          readonly
          @click="showUserPopup"
        >
          <template #button>
            <!-- <div @click="showUser = true">
              {{ form.appointee }}
              <span v-if="!form.appointee" class="seleceFont">请选择</span>
              <van-icon name="arrow" />
            </div> -->
            <van-button size="small" icon="arrow"></van-button>
            <!-- <ht-user-selector-input
              v-model="form.users"
              :single="userSelectorIsSingle"
              quick-search-props="fullname,account,phone,email"
              :append-to-body="true"
              :config="{ id: 'form.userId' }"
              permission="b"
            ></ht-user-selector-input> -->
          </template>
        </van-field>
        <van-field name="radio" label="是否催办秘书" input-align="right">
          <template #input>
            <van-switch
              v-model="form.appointeeSecretary"
              inactive-value="0"
              active-value="1"
              size="20"
            />
          </template>
        </van-field>

        <!-- <van-field name="radio" label="催办方式" input-align="right">
          <template #input>
            <van-radio-group v-model="form.urgentType" direction="horizontal">
       
              <van-radio name="mail">邮箱</van-radio>
              <van-radio v-if="showMessageType('sms')" name="sms">
                短信
              </van-radio>
              <van-radio v-if="showSmsApproval" name="smsApproval">
                短信审批
              </van-radio>
              <van-radio name="inner" v-if="showMessageType('inner')">
                站内消息
              </van-radio>
              <van-radio name="voice" v-if="showMessageType('voice')">
                语音
              </van-radio>
              <van-radio
                name="wxEnterprise"
                v-if="showMessageType('wxEnterprise')"
              >
                微信
              </van-radio>
              <van-radio name="dingTalk" v-if="showMessageType('dingTalk')">
                钉钉
              </van-radio>
              <van-radio name="flyBook" v-if="showMessageType('flyBook')">
                飞书
              </van-radio>
            </van-radio-group>
          </template>
        </van-field> -->
        <template v-if="form.urgentType != 'smsApproval'">
          <van-field
            v-if="form.urgentType == 'mail'"
            v-model="form.contentMail"
            name="contentMail"
            rows="3"
            autosize
            :rules="[
              {
                required: true,
                message: `请输入催办内容`,
              },
            ]"
            type="textarea"
            maxlength="100"
            placeholder="请输入催办内容"
            show-word-limit
          />
          <van-field
            v-else-if="['sms', 'smsApproval'].includes(form.urgentType)"
            v-model="form.contentSms"
            name="contentSms"
            rows="3"
            autosize
            :rules="[
              {
                required: true,
                message: `请输入催办内容`,
              },
            ]"
            type="textarea"
            maxlength="100"
            placeholder="请输入催办内容"
            show-word-limit
          />
          <van-field
            v-else
            v-model="form.contentOthers"
            name="contentOthers"
            rows="3"
            :rules="[
              {
                required: true,
                message: `请输入催办内容`,
              },
            ]"
            autosize
            type="textarea"
            maxlength="100"
            placeholder="请输入催办内容"
            show-word-limit
          />
        </template>

        <van-field
          v-else
          v-model="form.contentSms"
          name="contentOthers"
          rows="3"
          autosize
          type="textarea"
          maxlength="100"
          placeholder="短信审批备注会显示在发出的短信内容中,可在备注中对流程信息做补充说明,但请勿涉及敏感内容。"
          show-word-limit
        />
      </van-form>
      <!-- <div class="form_buttom" @click="showOften = true">
        <i class="icon-yucetu"></i>
        可选变量
      </div> -->

      <van-divider style="margin: 0.22667rem 0 0" />
    </van-popup>
    <van-action-sheet
      v-model="showOften"
      :actions="oftenActions"
      cancel-text="取消"
      close-on-click-action
      @cancel="showOften = false"
      @select="selectOften"
    />
    <!-- v-model="showUser" -->
    <van-popup
      v-model="showUser"
      :close-on-click-overlay="false"
      safe-area-inset-bottom
      round
      position="bottom"
      style="min-height: 40%; max-height: 80%"
    >
      <van-nav-bar
        title="选择被催办人"
        left-text="取消"
        right-text="确定"
        class="popup_header_fixed"
        @click-left="onUserkLeft"
        @click-right="onUserkRight"
      />

      <div class="selectConten popup_header_margin">
        <van-checkbox
          v-model="checked"
          shape="square"
          @click="changeChecked(checked)"
        >
          全选
        </van-checkbox>

        <!-- <van-divider /> -->
        <van-checkbox-group v-model="checkedNodes" ref="checkboxGroup">
          <template v-for="(item, i) of assigneeUsers">
            <van-checkbox :name="item" shape="square" :key="i">
              {{ item.fullname }}
            </van-checkbox>
            <!-- <van-divider v-if="i + 1 !== List.length" /> -->
          </template>
        </van-checkbox-group>
      </div>
    </van-popup>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import {
    getExcutorByInstId,
    defGet,
    sendBpmTaskUrgent,
  } from '@/api/process.js'
  export default {
    name: 'TaskCunBan',

    props: {
      title: {
        type: String,
        default: '任务催办',
      },
      userSelectorIsSingle: {
        type: Boolean,
        default: false,
      },
      defId: {
        type: String,
        default: '',
      },
      instId: {
        type: String,
        default: '',
      },
      subject: {
        type: String,
        default: '',
      },
    },
    computed: {
      ...mapState('login', ['currentUser']),
      userId() {
        return this.currentUser.userId
      },
      userName() {
        return this.currentUser.username
      },
      showSms() {
        const node = this.nodeDefMap[this.form.selectedNodeId]
        return node && !node.localProperties.allowSmsApproval
      },
      showSmsApproval() {
        const node = this.nodeDefMap[this.form.selectedNodeId]
        return node && node.localProperties.allowSmsApproval
      },
      showAppointee() {
        return this.nodeDefMap[this.form.selectedNodeId]
      },
      showSelectNode() {
        const node = this.nodeDefMap[this.form.selectedNodeId]
        return node && node.assigneeUsers.length == 0 && this.hasTaskUser
      },
      assigneeUsers() {
        return (
          this.nodeDefMap[this.form.selectedNodeId] &&
          this.nodeDefMap[this.form.selectedNodeId].assigneeUsers
        )
      },
    },
    watch: {
      checkedNodes: {
        handler(val) {
          if (this.assigneeUsers && this.assigneeUsers.length > 0) {
            if (val.length === this.assigneeUsers.length) {
              this.checked = true
            } else {
              this.checked = false
            }
          }
        },
        immediate: true,
        deep: true,
      },
      showUser: {
        handler(val) {
          if (val && this.checked == true) {
            this.checkedNodes = this.assigneeUsers
          }
        },
        immediate: true,
        deep: true,
      },
    },
    data() {
      return {
        checked: false,
        checkedNodes: [],

        showRejectMethod: false,
        showOften: false,
        showUser: false,
        hasTaskUser: true, // 是否有任务审批人
        showTaskUrgent: false,
        nodeList: [],
        nodeDefMap: {},
        form: {
          people: '',
          contentMail: '',
          contentSms: '',
          contentOthers: '',
          appointee: '',
          userId: '',
          files: '',
          urgentType: '',
          selectedNodeId: '',
          appointeeSecretary: '0',
        },
        show: false,
        oftenActions: [
          { id: 1, name: '催办人', command: '{催办人:promoter}' },
          { id: 2, name: '被催办人', command: '{被催办人:appointee}' },
          { id: 3, name: '流程编号', command: '{流程编号:instId}' },
          { id: 4, name: '流程标题', command: '{流程标题:subject}' },
          { id: 5, name: '流程发起人', command: '{流程发起人:sponsor}' },
          { id: 6, name: '任务节点名称', command: '{任务节点名称:nodeName}' },
        ],
        copyData: {},
      }
    },

    methods: {
      onUserkRight() {
        if (this.checkedNodes.length < 1) {
          this.$toast.fail('请选择被催办人')
          return
        }
        let list = []
        this.checkedNodes.forEach((item) => {
          list.push(item.fullname)
        })
        this.form.appointee = list.join(',')

        this.showUser = false
      },
      onUserkLeft() {
        this.form.appointee = this.copyData.appointee
        this.checkedNodes = this.copyData.Node
        this.showUser = false
      },
      showUserPopup() {
        this.copyData.Node = this.checkedNodes
        this.copyData.appointee = this.form.appointee

        this.showUser = true
      },
      async showDialog() {
        let that = this
        // this.checkedNodes = []
        this.copyData = {}

        this.form = {
          people: '',
          contentMail: '',
          contentSms: '',
          contentOthers: '',
          appointee: '',
          userId: '',
          files: '',
          selectedNodeId: '',
          // urgentType: '',
          appointeeSecretary: '0',
        }
        // 根据实例Id获取当前任务节点审批人
        await getExcutorByInstId(this.instId, (data) => {
          if (data) {
            const { length } = data
            this.nodeList = data

            if (length == 0) {
              this.hasTaskUser = false
            }
            if (length == 1) {
              this.form.selectedNodeId = data[0].nodeId
            }

            data.forEach((nodeDef) => {
              this.nodeDefMap[nodeDef.nodeId] = nodeDef
            })

            //全选默认
            this.$nextTick(() => {
              this.checkedNodes =
                this.nodeDefMap[this.form.selectedNodeId] &&
                this.nodeDefMap[this.form.selectedNodeId].assigneeUsers
              this.checked = true
            })
          }
        })

        // 根据流程定义Id获取流程信息
        await defGet(this.defId, (data) => {
          if (data) {
            const { urgentMailTel, urgentSmsTel } = data
            this.contentSms = urgentSmsTel ? urgentSmsTel : ''
            this.contentMail = urgentMailTel ? urgentMailTel : ''
          }
        })
        setTimeout(() => {
          this.show = true
        }, 200)
      },
      showMessageType(label) {
        const node = this.nodeDefMap[this.form.selectedNodeId]
        return (
          node &&
          node.localProperties.notifyType &&
          node.localProperties.notifyType.includes(label)
        )
      },
      onClickRight() {
        this.$refs.form
          .validate()
          .then(() => {
            let content = ''
            if (this.form.urgentType == 'mail') {
              content = this.form.contentMail
            } else if (this.form.urgentType == 'sms') {
              content = this.form.contentSms
            } else {
              content = this.form.contentOthers
            }

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

            const appointeeIds = []
            const appointeeNames = []
            this.checkedNodes.forEach((item) => {
              appointeeIds.push(item.userId)
              appointeeNames.push(item.fullname)
            })
            const data = {
              type: this.form.urgentType || 'mail',
              instId: this.instId,
              subject: this.subject,
              content,
              promoter: this.userName,
              promoterId: this.userId,
              nodeId: this.form.selectedNodeId,
              nodeName: this.nodeDefMap[this.form.selectedNodeId].name,
              appointee: this.form.appointee,
              appointeeId: appointeeIds.join(','),
              appointeeSecretary: this.form.appointeeSecretary == 1,
            }
            sendBpmTaskUrgent(data, (res) => {
              if (res.state) {
                this.show = false
                this.$toast.success(res.message)
              } else {
                this.$toast.fail(res.message)
              }
            })
          })
          .catch(() => {})
      },

      changeChecked(Blo) {
        this.$refs.checkboxGroup && this.$refs.checkboxGroup.toggleAll(Blo)
      },
      selectOften(val) {
        this.form.contentMail = `${
          this.form.contentMail ? this.form.contentMail : ''
        }${val.command}`
      },
      selectUser(val) {},
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/styles/matterButton.scss';
  .form_buttom {
    padding: 12px 16px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    border-top: 1px solid #eee;
    font-size: 14px;
    i {
      font-size: 22px;
      margin-right: 4px;
    }
  }
  .seleceFont {
    font-size: 14px;
    color: #bfbfbf;
  }
  .van-checkbox {
    font-size: 14px;
    padding: 0 12px;
    height: 44px;
    line-height: 44px;
  }
  .selectConten {
    // padding: 12px 0 16px;
  }
  ::v-deep .van-field__label {
    color: #262626;
  }
  ::v-deep {
    .van-switch--on {
      background-color: #409eff;
    }
  }
</style>
