<template>
  <div class="daily-set-wrap ">
    <div class="daily-set-content border-box">
      <div class="salutatory-set-wrap m-t-20">
        <el-form label-width="117px" ref="form" :model="form" :rules="rules" refs="form">
          <el-form-item label="欢迎语标题" prop="title">
            <el-input show-word-limit placeholder="请输入欢迎语标题" type="text" v-model="form.title" maxlength="20" class="w-384"></el-input>
          </el-form-item>
          <el-form-item label="欢迎语内容" prop="welcomeContent" class="welcomeContentItem">
            <textEditor :msgText="form.welcomeContent" :xcxwechatContent="wechatContent" @listenWxText="getWxText"></textEditor>
            <single-upload uploadType="1" :imgSrc.sync="form.welcomeImg" :field="''" class="app-set" :uploadLimit="1"> </single-upload>
          </el-form-item>
          <el-button type="primary" style="margin-left:117px;" @click="submit">保存</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { getRequest, postForm } from '@/api/api';
import textEditor from '@/components/common/editor';
import singleUpload from '@/components/single-upload.vue';
import errMsg from '@/common/js/error';
export default {
  props: {},
  data() {
    return {
      form: {
        title: '系统默认',
        welcomeContent: '',
        welcomeImg: ''
      },
      wechatContent: '',
      rules: {
        title: [{ required: true, message: '请输入欢迎语标题', trigger: 'blur' }],
        welcomeContent: [{ required: true, message: '请输入欢迎语内容', trigger: 'blur' }]
      }
    };
  },
  mounted() {
    // this.configEditor();
    this.$emit('showTab', 4);
    document.documentElement.style.backgroundColor = '#f0f2f5';
    this.getData();
  },
  methods: {
    handleRequest(file) {
      let files = new FormData();
      files.append('file', file);
      return new Promise((resolve, reject) => {
        postForm('/haoban-manage3-web/upload-file?fileType=jpg', files)
          .then(res => {
            const { data } = res;
            if (data.errorCode == 1) {
              resolve(data.result.url);
            }
            resolve(null);
            errMsg.errorMsg(data);
          })
          .catch(function(error) {
            resolve(null);
            errMsg.errorMsg(error);
          });
      });
    },
    appendVal() {
      // this.editor.txt.append('<p><微信昵称></p>');
      this.editor.cmd.do('insertHTML', '<p><微信昵称></p>');
    },
    getWxText(data) {
      console.log(data);
      // 单独转义一下被html转义的  & > < 空格 单引号
      // this.wxTextContent=data.textarea.replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/<\/?[^>]*>/g,'').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
      this.form.welcomeContent = data.textarea;
    },
    validate() {
      // const reg = /<(?!(a|\/a|div|\/div|br)).*?>/gim; // 只保留a 和 div 标签
      let str = this.form.welcomeContent.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); // 单独转义一下被html转义的   > <
      let str1 = str.replace(/<\/div>|&nbsp;/g, '');
      let str2 = str1.replace(/<((div)).|<((br)).*?>/g, '<br>');
      let str3 = str2
        .split('<br>')
        .filter(v => v)
        .join('');
      let hrefReg = /href=['"]([^"]*)['"].*?/g;
      // let hrefReg = /(?<=href=\").*?(?=\")/img;  // 获取a标签的href值
      if (hrefReg.test(str3)) {
        let hrefArr = str3.match(hrefReg);
        if (hrefArr.length > 1) {
          this.$message.error('只能添加一个链接');
          return;
        }
        let href = str3.match(hrefReg)[0];
        str3 = str3.replace(/<((a)).*?>/g, '<a ' + href + '>'); // 获取 <a> 并替代
      }
      console.log(str3);
      if (!str3 || /^[ ]*$/.test(str3)) {
        // str3不是空字符串 或 不全是空格
        this.$message.error('请输入欢迎语内容');
        return false;
      } else {
        this.form.welcomeContent = str3;
        return true;
      }
    },
    changeRoute() {
      this.$router.push('/contactsList');
    },
    getData() {
      const that = this;
      let para = {
        wxEnterpriseId: that.wxEnterpriseId
      };
      getRequest('/haoban-manage3-web/get-welcome', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1 && resData.result) {
            that.form = resData.result;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    submit() {
      const that = this;
      if (!this.validate()) return;
      that.$refs.form.validate(value => {
        if (value) {
          this.$confirm('确认保存此欢迎语？', '提示')
            .then(() => {
              const para = { ...that.form };
              getRequest('/haoban-manage3-web/save-welcome', para)
                .then(res => {
                  let resData = res.data;
                  if (resData.errorCode == 1) {
                    this.$message({
                      type: 'success',
                      message: '保存成功!'
                    });
                    window.location.reload();
                  }
                  errMsg.errorMsg(resData);
                })
                .catch(function(error) {
                  that.$message.error({
                    duration: 1000,
                    message: error.message
                  });
                });
            })
            .catch();
        }
      });
    }
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  },
  components: {
    singleUpload,
    textEditor
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.w-384 {
  width: 384px;
  box-sizing: border-box;
}
.welcomeContent {
  height: 220px;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  >>> .el-textarea__inner {
    height: 181px;
    border: none;
    &:focus {
      box-shadow: none;
    }
  }
  >>> .el-input__count {
    bottom: 44px;
  }
}
.daily-set-wrap {
  height: 100%;
  .daily-set-content {
    padding: 20px;
    .table-condition-left {
      font-size: 0;
    }
  }
}
.salutatory-set-wrap {
  >>> .el-input__inner:focus {
    box-shadow: none;
  }
  .welcomeContentItem {
    width: 600px;
    .text-bottom {
      position: absolute;
      bottom: 1px;
      left: 1px;
      justify-content: space-between;
      align-items: center;
      height: 38px;
      width: 382px;
      box-sizing: border-box;
      padding: 0 9px;
      background: #f5f7fa;
    }
  }
}
.app-set {
  margin-top: 10px;
  .avatar-uploader {
    .el-upload {
      width: 60px !important;
      height: 60px !important;
      .font-12 {
        display: none;
      }
      .avatar-uploader-icon {
        font-size: 14px;
        color: #303133;
        font-weight: bold;
      }
    }
  }
  .upload-tip {
    display: none;
  }
}
</style>
