<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-14 09:50:16
 * @LastEditors: Drama
 * @LastEditTime: 2022-10-13 16:49:34
 -->
<!--
  <text-edit :categoryId="categoryId" @closeText="closeText" @submitText="submitText"></text-edit>
  import textEdit from '@/components/set/text-edit.vue';
 -->
<template>
  <el-dialog :title="!!editRow.materialId ? '编辑文本' : '新建文本'" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
    <div class="">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="文本标题" prop="materialTitle">
          <limitInput :inputWidth="440" :inputValue.sync="ruleForm.materialTitle" :holder="'请输入文本标题'" :getByType="'word'" :maxLength="20"> </limitInput>
        </el-form-item>
        <el-form-item label="内容" prop="materialContent">
          <div class="material-content">
            <el-input id="inputContent" show-word-limit placeholder="请输入内容" type="textarea" v-model="ruleForm.materialContent" maxlength="1000" class="w-440 welcomeContent"></el-input>
            <el-popover placement="top" width="388" trigger="click" @show="showPopover('inputContent')">
              <ul class="flex flex-wrap">
                <li v-for="(item, index) in emojiList" :key="index + 'emoji'">
                  <img :src="item.gifUrl" alt="" @click.stop="selectEmoji(item)" />
                </li>
              </ul>
              <img class="emoji-img cursor-pointer" slot="reference" src="https://pic01-10001430.image.myqcloud.com/b0d3c14f-69e7-4753-8fbc-3bffcff9f8ce" alt="" />
            </el-popover>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="toCancel">取消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { emojiArr } from '@/utils/emoji';
export default {
  props: {
    editRow: {
      type: Object,
      default() {
        return {};
      }
    },
    categoryId: {
      type: Object,
      default() {
        return '';
      }
    }
  },
  components: {
    limitInput
  },
  data() {
    return {
      editPersion: localStorage.getItem('userName'),
      dialogVisible: true,
      ruleForm: {
        materialId: '',
        materialTitle: '',
        materialContent: ''
      },
      rules: {
        materialTitle: [{ required: true, message: '请输入文本标题', trigger: 'blur' }],
        materialContent: [{ required: true, message: '请输入文本内容', trigger: 'blur' }]
      },
      emojiList: emojiArr,
      ele: '' // dom元素id
    };
  },
  methods: {
    /**
     * 获取dom
     */
    showPopover(id) {
      this.ele = id;
    },
    /**
     * 输入内容
     **/
    handleInput($event) {
      const that = this;
      that.ruleForm.materialContent = $event.target.innerText;
    },
    /**
     * 选中表情
     **/
    selectEmoji(item) {
      const that = this;
      // const str = that.ruleForm.materialContent + item.key;

      let textArea = document.getElementById(this.ele);
      let startPos = textArea.selectionStart;
      let endPos = textArea.selectionEnd;
      if (startPos === undefined || endPos === undefined) return;
      let currentTxt = textArea.value;
      const str = currentTxt.substring(0, startPos) + item.key + currentTxt.substring(endPos);
      // const str = that.ruleForm.materialContent + item.key;
      textArea.value = str;
      textArea.focus();
      this.$nextTick(() => {
        textArea.selectionStart = startPos + item.key.length;
        textArea.selectionEnd = endPos + item.key.length;
      });
      if (str.length > 1000) {
        this.$message('添加该表情后文本内容将超过字数限制，无法添加！');
      } else {
        that.ruleForm.materialContent = str;
      }
    },
    toCancel() {
      const that = this;
      that.$emit('closeText');
      that.$refs['ruleForm'].resetFields();
    },
    handleClose(done) {
      const that = this;
      that.$emit('closeText');
      that.$refs['ruleForm'].resetFields();
    },
    submitForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSave();
        }
      });
    }, 300),
    postSave() {
      const that = this;
      const data = {
        categoryId: that.categoryId,
        materialType: 1,
        materialId: that.ruleForm.materialId,
        materialTitle: that.ruleForm.materialTitle,
        materialContent: that.ruleForm.materialContent
      };
      postRequest(that.ruleForm.materialId ? '/haoban-manage3-web/material-edit' : '/haoban-manage3-web/material-add', data)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            that.$refs['ruleForm'].resetFields();
            that.$emit('submitText');
          } else {
            errMsg.errorMsg(resData);
          }
        })
        .catch(error => {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    editRow(newData) {
      const that = this;
      if (Object.keys(newData).length) {
        that.ruleForm = JSON.parse(JSON.stringify(newData));
      }
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.editRow).length) {
      that.ruleForm = JSON.parse(JSON.stringify(that.editRow));
    }
  }
};
</script>
<style lang="scss" scoped>
.m-b-20 {
  margin-bottom: 20px;
}
.p-l-18 {
  padding-left: 18px;
}
.w-440 {
  width: 440px;
}
.material-content {
  position: relative;
  .material-body {
    /*  resize: none;
    width: 440px;
    height: 273px;
    border-radius: 2px;
    border: 1px solid rgba(196, 198, 207, 1); */
    .el-textarea {
      >>> .el-textarea__inner {
        height: 273px;
      }
    }
  }
  .emoji-img {
    position: absolute;
    left: 10px;
    bottom: 10px;
  }
}
.el-textarea {
  >>> .el-textarea__inner {
    height: 273px;
  }
}
</style>
