<!--
 * @Descripttion: 编辑标签
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-09-01 17:16:25
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-21 10:29:20
-->

<!--
  <edit-tag-dialog  :brand-id="brandId" :current-category-id="currentCategoryId" :edit-row="editRow" @closeTag="closeTag"></edit-tag-dialog>
  import editTagDialog from '@/components/app/my-customer/edit-tag-dialog.vue';
-->
<template>
  <el-dialog :title="form.tagId ? '编辑标签' : '新建标签'" width="600px" :visible.sync="editVisible" :before-close="handleClose" append-to-body>
    <common-alert-tip :width="'476px'" :tip-content="tipContent"></common-alert-tip>
    <el-form class="m-t-20" :model="form" :rules="rules" ref="tagForm" label-width="110px">
      <el-form-item label="标签名称" prop="tagName">
        <limit-input
          :input-width="440"
          :input-value.sync="form.tagName"
          :holder="'请输入标签名称'"
          :get-by-type="'normal'"
          :max-length="15">
        </limit-input>
      </el-form-item>
      <el-form-item label="所属分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择">
          <el-option
            v-for="item in tagsClassifyData"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签值" prop="">
        <el-tag
          :key="index+'tag'"
          v-for="(item, index) in form.tagValueDTOList"
          closable
          :disable-transitions="false"
          @close="handleDel(index)">
          {{item.tagValue}}
        </el-tag>
        <div v-if="form.tagValueDTOList.length < 20" class="m-t-5 input-tag-div">
          <el-input
            class="input-new-tag"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            maxlength="15"
            placeholder="请输入标签值并回车添加多个"
            @keyup.enter.native="handleInputConfirm">
          </el-input>
          <span class="input-cell-tip">{{inputValue.length}}/15</span>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" :loading="loadingBtn" @click="submit('tagForm')">{{form.tagId ? '保存' : '新建'}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import limitInput from '@/components/limit-input.vue';
import commonAlertTip from '@/components/common/common-alert-tip.vue';
import { _debounce, emojiToStr } from '@/common/js/public.js';
import showMsg from '@/common/js/showmsg.js';
import api from '@/api/my-customer-app.js';
const { addClerkTag, editClerkTag, getTagClassify } = api;
export default {
  name: 'TagClassifyDialog',
  components: {
    limitInput,
    commonAlertTip
  },
  props: {
    brandId: {
      type: String,
      default: ''
    },
    currentCategoryId: {
      type: String,
      default: ''
    },
    editRow: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      tipContent: '在好办新建的标签会在GIC虫洞派应用中也会同步创建并消耗license',
      tagsClassifyData: [],
      form: {
        tagId: '',
        tagName: '',
        linkId: '',
        categoryId: '',
        tagValueDTOList: []
      },
      rules: {
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' },
        ],
        categoryId: [
          { required: true, message: '请选择所属分类', trigger: 'change' }
        ],
        /* tagValueDTOList: [
          { type: 'array', required: true, message: '请添加标签值', trigger: 'change' }
        ], */
      },
      inputValue: '',
      editVisible: true,
      loadingBtn: false
    };
  },
  // 生命周期
  beforeMount() {
    const that = this;
    if (that.brandId) {
      that.getClassifyList();
    }
  },
  // methods
  methods: {
    /**
     * @description: 标签操作
     * @param {Number}  index
     * @author: 无尘
     */
    handleDel(index) {
      this.form.tagValueDTOList.splice(index, 1);
    },

    handleInputConfirm() {
      const that = this;
      let inputValue = emojiToStr(that.inputValue);
      if (inputValue) {
        that.form.tagValueDTOList.push(
          {
            tagValueId: '',
            tagValue: inputValue
          }
        );
      }
      that.inputValue = '';
    },
    /**
     * @description: 关闭弹窗
     * @author: 无尘
     */
    cancel() {
      const that = this;
      that.$emit('closeTag', 'close');
    },
    handleClose() {
      const that = this;
      that.tableData = [];
      that.$emit('closeTag', 'close');
    },
    /**
     * @description: 确定保存
     * @param {String} formName
     * @returns {Boolean}
     * @author: 无尘
     */
    submit: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSave();
        }
      });
    }, 300),
    postSave() {
      const that = this;
      that.loadBtn = true;
      const param = {
        tagId: that.form.tagId,
        tagName: emojiToStr(that.form.tagName),
        linkId: that.form.linkId,
        tagValueDTOList: JSON.stringify(that.form.tagValueDTOList),
        categoryId: that.form.categoryId,
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId
      };
      if (that.form.tagId) {
        that.editPost(param);
      }else {
        that.addPost(param);
      }
    },
    addPost(param) {
      const that = this;
      addClerkTag(param, { headers: { sign: that.brandId } })
        .then(res => {
          that.loadBtn = false;
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
            that.$refs['tagForm'].resetFields();
            that.$emit('closeTag', 'success');
          }else {
            showMsg.showmsg(res.message || '未知错误', 'warning');
          }
        })
        .catch(error => {
          that.loadBtn = false;
        });
    },
    editPost(param) {
      const that = this;
      editClerkTag(param, { headers: { sign: that.brandId } })
        .then(res => {
          that.loadBtn = false;
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
            that.$refs['tagForm'].resetFields();
            that.$emit('closeTag', 'success');
          }else {
            showMsg.showmsg(res.message || '未知错误', 'warning');
          }
        })
        .catch(error => {
          that.loadBtn = false;
        });
    },
    /**
     * @description: 获取分类数据
     * @author: 无尘
     */
    getClassifyList() {
      const that = this;
      const para = {
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId
      };
      getTagClassify(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.tagsClassifyData = res.result || [];
          that.currentCategoryId ? that.form.categoryId = that.currentCategoryId : '';
          if (Object.keys(that.editRow).length) {
            that.form = JSON.parse(JSON.stringify(that.editRow));
          }
        })
        .catch(function(error) {
          that.currentCategoryId ? that.form.categoryId = that.currentCategoryId : '';
        });
    }
  },
  watch: {
    brandId(val) {
      const that = this;
      if (val) {
        that.getClassifyList();
      }
    }
  }
};
</script>
<style lang='less' scoped>
  .m-t-5 {
    margin-top: 5px;
  }
  .el-form {
    .el-select {
      width: 440px;
    }
    .el-input {
      width: 440px;
    }
    .input-tag-div {
      position: relative;
      .input-cell-tip {
        position: absolute;
        top: 2px;
        right: 20px;
        display: inline-block;
        line-height: 30px;
        text-align: right;
        font-size: 12px;
        color: #c0c4cc;
        font-weight: 400;
      }
    }
  }
</style>
