<template>
  <el-dialog :visible.sync="showPop" width="600px" @close="closePop" destroy-on-close title="新增标签">
    <div class="manualTagEdit-wrap">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="标签名称：" prop="tagName">
          <el-input class="w-full" placeholder="请输入内容" v-model="ruleForm.tagName" :maxlength="15" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="所属分类：" prop="tagLevel">
          <div class="tagLevel">
            <el-form-item prop="tagTwoLevelGroupId" class="fl">
              <el-select class="w-225" placeholder="请选择" v-model="ruleForm.tagTwoLevelGroupId" @change="changeTwo">
                <el-option v-for="item in optionsTwo" :key="item.tagLevelGroupId" :label="item.levelName" :value="item.tagLevelGroupId"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="tagLevelGroupId" class="fl">
              <el-select class="w-225 ml10" placeholder="请选择" v-model="ruleForm.tagLevelGroupId">
                <el-option v-for="item in optionsThree" :key="item.tagLevelGroupId" :label="item.levelName" :value="item.tagLevelGroupId"> </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="标签值：" prop="tagValue">
          <div class="tag-list">
            <tag-value-item v-for="item in ruleForm.tagValue" :current-length="ruleForm.tagValue.length" :key="item.id" :item="item" class="w-full" @add="onAddTagVal" @del="onDelTagVal" />
          </div>
        </el-form-item>
        <el-form-item label="标签描述：" prop="tagDescribe">
          <el-input class="w-full" type="textarea" v-model="ruleForm.tagDescribe" :maxlength="100" show-word-limit placeholder="请输入标签描述，最多100字"></el-input>
        </el-form-item>
      </el-form>
      <div class="manualTagEdit-btns">
        <el-button @click="$emit('update:showPop', false)">取消</el-button>
        <el-button type="primary" @click="confirmSave">保存</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
const validateTagValue = (rule, value, cb) => {
  if (value.some(el => !el.tagItemName)) {
    return cb(new Error('请完善标签值'));
  }
  cb();
};
const GenNonDuplicateID = () => {
  return Math.random().toString();
};
import tagValueItem from './tag-value-item.vue';
export default {
  name: 'manualTagEdit',
  props: {
    showPop: Boolean,
    options: Object
  },
  data() {
    return {
      // 编辑标签的时候,获取标签的 id
      // tagId: '',
      // 标签基本信息模块的表单
      ruleForm: {
        tagName: '',
        tagLevel: 'test',
        tagTwoLevelGroupId: '',
        tagLevelGroupId: '',
        tagDescribe: '',
        pending: false,
        tagSort: null,
        tagType: 0,
        tagValue: [{ id: GenNonDuplicateID(), deleteFlag: false, tagItemName: '' }]
      },
      // 标签基本信息模块的表单验证
      rules: {
        tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
        tagLevel: [{ required: true, message: '' }],
        tagLevelGroupId: [{ required: true, message: '请选择所属分类', trigger: 'blur' }],
        tagTwoLevelGroupId: [{ required: true, message: '请选择所属分类', trigger: 'blur' }],

        tagType: [{ required: true, trigger: 'blur' }],
        tagValue: [{ required: true, trigger: 'blur', validator: validateTagValue }]
      },
      // 标签所属分类的下拉列表数据
      optionsTwo: [],
      optionsThree: [],

      // 标签值列表的数据
      tagValTableData: [],
      preSyncWmStatus: 0,
      deleteList: [],
      isEdit: false
    };
  },
  watch: {
    options: {
      deep: true,
      immediate: true,
      handler(newVal) {
        this.ruleForm.tagTwoLevelGroupId = newVal.tagTwoLevelGroupId;
        this.ruleForm.tagLevelGroupId = newVal.tagLevelGroupId;
        if (newVal.tagId) {
          this.isEdit = true;
          this.getTagData(newVal.tagId);
        } else {
          this.isEdit = false;
          this.ruleForm.tagName = '';
          this.ruleForm.tagDescribe = '';
          this.ruleForm.tagSort = null;
          this.ruleForm.tagType = 0;
          this.ruleForm.tagTwoLevelGroupId = '';
          this.ruleForm.tagLevelGroupId = '';
          // 刷新tagValue
          this.ruleForm.tagValue = [{ id: GenNonDuplicateID(), deleteFlag: false, tagItemName: '' }];
          // this.getOptionsThree(newVal.tagTwoLevelGroupId);
        }
        // 获取初始化分类是否同步至微盟的状态
        const initData = this.optionsThree.find(el => el.tagLevelGroupId == this.ruleForm.tagLevelGroupId);
        if (initData) this.preSyncWmStatus = initData.syncWmFlag;
        this.getOptionsTwo();
      }
    }
  },
  components: {
    tagValueItem
  },
  methods: {
    closePop() {
      this.$refs.ruleForm.resetFields();
      this.$emit('update:showPop', false);
    },
    // 保存标签基本信息
    confirmSave() {
      if (this.ruleForm.pending) return;
      this.ruleForm.pending = true;
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const isSyncWm = this.optionsThree.find(el => el.tagLevelGroupId == this.ruleForm.tagLevelGroupId).syncWmFlag;
          const isAutoSync = this.options.isSync;
          // 开启手动同步且移动前已同步至微盟，移动后未同步至微盟
          if (!isAutoSync && this.preSyncWmStatus && !isSyncWm) {
            this.$confirm('该分类未开启微盟标签同步，修改后标签将不会再同步至微盟，并且已同步至微盟侧的会员标签将从微盟侧删除，是否继续保存？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                this.saveApi();
              })
              .catch(() => (this.ruleForm.pending = false));
          } else {
            this.saveApi();
          }
        } else {
          this.ruleForm.pending = false;
        }
      });
    },

    // 保存标签基本信息
    saveApi() {
      const tagItemList = this.ruleForm.tagValue.concat(this.deleteList).map(el => {
        delete el.id;
        return el;
      });
      const data = {
        tagId: this.options.tagId,
        tagName: this.ruleForm.tagName,
        tagDescribe: this.ruleForm.tagDescribe,
        tagLevelGroupId: this.ruleForm.tagLevelGroupId,
        tagItemList,
        isMultiple: this.ruleForm.tagType,
        tagType: 2 // 2 活动标签 1 手工
      };

      this.axios
        .post('/gic-member-tag-web/memberTag/saveHandMemberTag?requestProject=marketing', data)
        .then(res => {
          const { errorCode, message } = res.data;
          this.ruleForm.pending = false;
          if (errorCode !== 1) {
            this.$message.error({
              duration: 1000,
              message: message
            });
            return;
          }
          this.$message.success('保存成功', 'success');
          this.$emit('save');
          this.closePop();
        })
        .catch(error => {
          this.ruleForm.pending = false;
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    // 获取二级分类列表
    getOptionsTwo() {
      const params = { tagLevelType: 2 };
      console.log(params);
      this.axios
        .get('/gic-member-tag-web/tagLevel/handSecondLevel?requestProject=marketing&tagLevelType=2')
        .then(res => {
          const { errorCode, result } = res.data;
          if (errorCode === 1) {
            this.optionsTwo = result;
          }
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    // 点击二级分类获取三级分类列表
    changeTwo(value) {
      this.ruleForm.tagLevelGroupId = '';
      this.getOptionsThree(value);
    },

    // 获取三级分类列表
    getOptionsThree(tagLevelGroupId) {
      this.axios
        .get(`/gic-member-tag-web/tagLevel/handThirdLevel?requestProject=marketing&tagLevelGroupId=${tagLevelGroupId}`)
        .then(res => {
          const { errorCode, result } = res.data;
          if (errorCode === 1) {
            this.optionsThree = result;
          }
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    // 编辑时获取当前标签数据
    getTagData(tagId) {
      this.axios
        .get(`/gic-member-tag-web/memberTag/getTagById?requestProject=marketing&tagId=${tagId}`)
        .then(res => {
          const { errorCode, result } = res.data;
          if (errorCode === 1) {
            this.ruleForm.tagName = result.tagName;
            this.ruleForm.tagLevelGroupId = result.tagLevelGroupId;
            this.ruleForm.tagTwoLevelGroupId = result.tagTwoLevelGroupId;
            this.ruleForm.tagDescribe = result.tagDescribe;
            this.ruleForm.tagSort = result.sort;
            this.ruleForm.tagType = result.isMultiple;
            this.ruleForm.tagValue = result.itemList || [];
            if (result.itemList.length) {
              this.ruleForm.tagValue = result.itemList.map(el => {
                el.id = GenNonDuplicateID();
                el.deleteFlag = false;
                return el;
              });
            } else {
              this.ruleForm.tagValue = [{ id: GenNonDuplicateID(), deleteFlag: false, tagItemName: '' }];
            }
            // 根据已选二级 id 获取三级列表
            if (result.tagTwoLevelGroupId) {
              this.getOptionsThree(result.tagTwoLevelGroupId);
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    onAddTagVal(id) {
      const index = this.ruleForm.tagValue.findIndex(el => el.id == id);
      const obj = { id: GenNonDuplicateID(), deleteFlag: false, tagItemName: '' };
      this.ruleForm.tagValue.splice(index + 1, 0, obj);
    },
    onDelTagVal(id) {
      const index = this.ruleForm.tagValue.findIndex(el => el.id == id);
      if (this.ruleForm.tagValue[index].tagItemId) {
        // 编辑数据删除的维护到list中，修改deletFlag= true在合并到请求数据中
        const deleteData = this.ruleForm.tagValue.splice(index, 1)[0];
        deleteData.deleteFlag = true;
        this.deleteList.push(deleteData);
      } else {
        this.ruleForm.tagValue.splice(index, 1);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/ .el-dialog-title {
  font-size: 16px;
  font-weight: bold;
}
.input-label {
  position: absolute;
  top: 2px;
  right: 45px;
  z-index: 1;
  font-size: 12px;
  color: #c0c4cc;
}

.textarea-label {
  .input-label {
    top: 92px;
    right: 45px;
  }
}

.manualTagEdit-btns {
  padding: 10px 0;
  text-align: right;
}

.w-447 {
  width: 447px;
}

.w-560 {
  width: 560px;
}
.icon {
  font-size: 14px;
  color: #606266;
  margin-left: 1px;
  position: relative;
  top: 1px;
}
.w-full {
  width: 100%;
}
.w-225 {
  width: 225px;
}
.ml10 {
  margin-left: 10px;
}
footer {
  margin-bottom: 4px;
}
.tag-list {
  max-height: 100px;
  min-height: 40px;
  overflow-y: auto;
}
.manual-dialog .el-dialog__footer {
  margin-top: 15px;
  border-top: 1px solid #dcdfe6;
}
.uploading .uploading-progress .el-progress__text {
  font-size: 12px !important;
  color: #909399;
}
.manualTagEdit-wrap .el-form-item__label {
  color: #606266;
}
.manualTagEdit-wrap .el-textarea__inner {
  height: 96px;
  resize: none;
  box-sizing: border-box;
}
.tag-value-wrapper .tag-cell {
  height: 56px;
}
.tag-value-wrapper .tag-head {
  height: 23px;
}
.fl {
  float: left;
}
.tagLevel {
  display: flex;
}
</style>
