<template>
  <div>
    <el-dialog
      v-if="dialogVisible"
      title="流程传阅"
      :visible.sync="dialogVisible"
      @close="closeDialog"
      append-to-body
    >
      <span>
        <el-form
          ref="form"
          :model="form"
          label-width="100px"
          :inline="false"
          size="normal"
          data-vv-scope="todoReadForm"
        >
          <ht-form-item label="传阅人员" required>
            <ht-user-selector-input
              ref="htUserSelector"
              v-model="form.users"
              append-to-body
              quick-search-props="fullname,account,phone,email"
              permission="b"
              :config="{ id: 'form' }"
              @input="syncInputUserId"
            ></ht-user-selector-input>
          </ht-form-item>
          <ht-form-item label="传阅说明" required>
            <div class="approval-comments">
              <ht-input
                ref="opinionInput"
                v-model="form.opinion"
                type="textarea"
                display-style="block"
                placeholder="请输入意见内容......"
                name="审批意见"
                validate="required"
                show-word-limit
                :maxlength="500"
                :max="500"
                :autosize="{ minRows: 8 }"
                permission="b"
              />
              <div class="common-words">
                <!-- <el-button
                  title="添加常用语"
                  icon="el-icon-plus"
                  size="mini"
                  @click="addCommonOpinion"
                /> -->
                <!-- <span>常用语：</span> -->
                <span
                  v-for="commonOpinion in commonWordsList"
                  :key="commonOpinion"
                >
                  <el-tag
                    v-if="commonOpinion.length > 7"
                    :title="commonOpinion"
                    :key="commonOpinion"
                    effect="plain"
                    type="info"
                    @click.native="choseCommonOpinion(commonOpinion)"
                  >
                    {{ commonOpinion.substring(0, 7) }}...
                  </el-tag>
                  <el-tag
                    v-else
                    :key="commonOpinion"
                    effect="plain"
                    type="info"
                    @click.native="choseCommonOpinion(commonOpinion)"
                  >
                    {{ commonOpinion }}
                  </el-tag>
                </span>
                <!-- <span class="word-count">{{ wordCount }}/500</span> -->
              </div>
              <div class="common-words-btns">
                <el-dropdown
                  v-if="moreTagList && moreTagList.length"
                  trigger="click"
                  @command="choseCommonOpinion"
                >
                  <i class="icon-daohanglan-gengduo more-dropdown-icon"></i>
                  <el-dropdown-menu
                    slot="dropdown"
                    class="common-words__dropdown"
                  >
                    <el-dropdown-item
                      v-for="(item, index) in moreTagList"
                      :key="index"
                      :command="item"
                    >
                      {{ item }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button
                  title="添加常用语"
                  icon="el-icon-plus"
                  size="small"
                  @click="addCommonOpinion"
                />
              </div>
            </div>
          </ht-form-item>
          <ht-form-item label="附件上传">
            <ht-file v-model="fileList" type="list" :downloadable="false" />
          </ht-form-item>
        </el-form>
      </span>
      <span slot="footer">
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'TemplateTaskCirculate',
    data() {
      return {
        dialogVisible: false,
        form: {
          users: '',
          userId: '',
          opinion: '',
        },
        fileList: '',
        defKey: '',
        instId: '',
        taskId: '',
        commonWordsList: [],
        moreTagList: [],
        commonWordLoaded: false,
        wordCount: 0,
      }
    },
    watch: {
      'form.opinion': {
        handler(val) {
          this.$emit('get-opinion', val)
          this.opinionInput()
        },
        deep: true,
      },
    },
    methods: {
      showDialog(row, flowBtnPermission) {
        const instId = row['bpm_proc_inst_id_']
        this.defKey = row['bpm_proc_def_key_']
        this.instId = instId
        if (instId) {
          this.taskId = flowBtnPermission[instId]
            ? flowBtnPermission[instId].taskId || ''
            : ''
        }
        this.$validator = this.$root.$validator
        this.commonWordLoaded || this.loadCommonWord()
        this.dialogVisible = true
      },
      confirm() {
        this.$validator.validateAll('todoReadForm').then((result) => {
          if (!result) {
            this.$message.warning('表单校验不通过，请完善表单信息')
            return false
          }
          const data = {
            copyToType: '0',
            files: JSON.stringify(this.fileList || []),
            instanceId: this.instId,
            opinion: this.form.opinion,
            messageType: 'inner',
            userId: this.form.userId,
            taskId: this.taskId,
          }
          this.$requestConfig.transToMore(data).then((resp) => {
            if (resp.state) {
              this.$message.success(resp.message)
              this.closeDialog()
            } else if (resp.message) {
              this.$message.error(resp.message)
            }
          })
        })
      },
      loadCommonWord() {
        this.$requestConfig
          .getCommonWordsByDefKeyAndTypeId(this.defKey)
          .then((res) => {
            this.commonWordLoaded = true
            // this.commonWordsList = resp
            const firstShowTagNum = this.calculateTagCount(res, 332)
            const secondShowTagNum = this.calculateTagCount(
              res.slice(firstShowTagNum),
              332
            )
            this.moreTagList = res.slice(firstShowTagNum + secondShowTagNum)
            this.commonWordsList = res.filter(
              (item, index) => index < firstShowTagNum + secondShowTagNum
            )
          })
      },
      calculateTagCount(tagList, containerWidth) {
        let tagCount = 0
        let currentWidth = 0

        for (let i = 0; i < tagList.length; i++) {
          const tag = tagList[i]
          const tagWidth = this.calculateTagWidth(tag)
          const TAG_MARGIN_RIGHT = 8
          if (currentWidth + tagWidth + TAG_MARGIN_RIGHT <= containerWidth) {
            currentWidth += tagWidth + TAG_MARGIN_RIGHT
            tagCount++
          } else {
            break
          }
        }
        return tagCount
      },
      calculateTagWidth(tag) {
        const TAG_FONT_SIZE = 12
        const TAG_LEFT_RIGHT_PADDING = 32
        const TAG_MAX_NUM_WORDS = 7
        const tagTextLength =
          tag.length > TAG_MAX_NUM_WORDS ? TAG_MAX_NUM_WORDS : tag.length

        return tagTextLength * TAG_FONT_SIZE + TAG_LEFT_RIGHT_PADDING
      },
      closeDialog() {
        this.$set(this, 'form', {
          users: '',
          userId: '',
          opinion: '',
        })
        this.taskId = ''
        this.instId = ''
        this.fileList = ''
        this.dialogVisible = false
      },
      //选择常用语
      choseCommonOpinion(commonOpinion) {
        this.form.opinion += commonOpinion
        this.opinionInput()
        // 触发校验
        this.$nextTick(() => {
          this.$refs.opinionInput.$validator.validate()
        })
        if (this.form.opinion.length >= 500) {
          this.form.opinion = this.form.opinion.substr(0, 500)
          this.opinionInput()
          return
        }
      },
      //统计输入和选择常用语长度
      opinionInput() {
        this.wordCount = this.form.opinion.length
      },
      //添加常用语
      addCommonOpinion() {
        if (!this.form.opinion) {
          this.$message.warning('请输入审批意见')
          return
        }
        this.$confirm(`确认添加 【${this.form.opinion}】 为常用语?`)
          .then(() => {
            const params = {
              expression: this.form.opinion,
              departmentId: '',
              postId: '',
              roleId: '',
              type: 4,
            }
            this.$requestConfig.savaCommonWords(params).then((data) => {
              if (data.state) {
                this.$message({ type: 'success', message: data.message })
                this.loadCommonWord()
              } else if (data.message) {
                this.$message.error(data.message)
              }
            })
          })
          .catch(() => {})
      },
      syncInputUserId() {
        let selection =
          this.$refs['htUserSelector'].$refs['userSelectorEl'].selectors
        this.form.userId = selection.map((item) => item.id).join(',')
      },
    },
  }
</script>

<style lang="scss" scoped>
  $base-radius8: 8px;

  .approval-comments {
    // outline: 1px solid #e8e8e8;
    ::v-deep {
      div[aria-invalid='true'] + .field-tail__wrap {
        margin-bottom: 20px;
        .el-form-item__error {
          top: 91%;
        }
      }
      .el-input__count {
        font-size: 14px;
        color: #cccccc;
      }
    }
    .common-words {
      // padding: 5px 10px;
      // border-top: 1px solid #e8e8e8;
      // background-color: #f7f8fa;
      padding-top: 8px;
      .el-button {
        margin-right: 10px;
      }
      .word-count {
        float: right;
      }
      ::v-deep {
        .el-tag {
          margin-right: 8px;
          border-color: #dcdee0;
          border-radius: $base-radius8;
          color: #262626;
          padding: 4px 16px;
          height: 32px;
          margin-bottom: 8px;
        }
        .el-tag + .el-tag {
          margin-left: 0;
        }
      }
    }

    ::v-deep {
      .inputs {
        .el-textarea__inner {
          border: none;
        }
      }
    }
    .el-tag {
      margin-right: 10px;
      cursor: pointer;
    }
  }
  ::v-deep {
    .el-dialog__footer {
      padding: 20px;
      text-align: right;
      border-top: 1px solid #dcdfe6;
    }
    .el-form-item__content {
      line-height: 32px;
      .ht-form-inputs__inline,
      .ht-form__sunOrSub {
        width: 100% !important;
      }
    }
    .common-words-btns {
      display: flex;
      align-items: center;
      .el-button {
        width: 32px;
        height: 32px;
        // line-height: 30px;
        padding: 7.8px 8.2px;
        // background-color: var(--themeColor);
        color: var(--themeColor);
        border-radius: $base-radius8;
        border-color: var(--themeColor);
        display: flex;
        justify-content: center;
        align-items: center;
        // &:hover {
        //   background-color: var(--themeColor);
        //   border-color: var(--themeColor);
        //   color: #fff;
        // }
        i {
          &:hover {
            opacity: 1;
          }
        }
      }
      .el-dropdown {
        width: 30px;
        height: 30px;
        border: 1px solid #dcdee0;
        text-align: center;
        border-radius: $base-radius8;
        margin-right: 8px;
        cursor: pointer;
        .more-dropdown-icon {
          color: var(--themeColor);
          width: 30px;
          height: 30px;
          line-height: 30px;
          display: block;
          border-radius: $base-radius8 !important;
          border: 1px solid var(--themeColor);
        }
        // &:hover {
        //   color: var(--themeColor);
        //   border-color: var(--themeColor);
        // }
      }
    }
  }
</style>
