<template>
  <el-dialog :visible.sync="showPop" :title="options.popTitle" width="600px" @close="closePop" destroy-on-close>
    <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"></el-input>
          <label class="input-label">{{ ruleForm.tagName.length }}/15</label>
        </el-form-item>
        <el-form-item label="所属分类：" prop="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>
        </el-form-item>
        <el-form-item label="排序：" prop="tagSort" v-if="currentType == 'manual'">
          <template #label> 排序<i class="iconfont icon-QuestionCircleOutlined icon" />： </template>
          <el-input v-model="ruleForm.tagSort" placeholder="请输入1-100000之间的整数" class="w-full" @input="validateInputSort" @blur="blurSort" />
        </el-form-item>
        <el-form-item label="标签类型：" prop="tagType" v-if="currentType == 'manual'">
          <el-radio-group v-model="ruleForm.tagType" :disabled="isEdit">
            <el-radio :label="0">单选</el-radio>
            <el-radio :label="1">多选</el-radio>
          </el-radio-group>
        </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>
import './manualTagEdit.css';
import showMsg from '@/common/js/showmsg';
import { getRequest, postJson } from '@/api/api';
import tagValueItem from './tag-value-item.vue';
import { GenNonDuplicateID } from '@/common/js/public';
/**
 * 轮询接口的实现方式
 *  refreshTag用来保存需要轮询的标签值tagItemIndex索引和tagItemId ID
 *  页面打开后，会调用getValueData根据取到的标签值的状态，将需要轮询的标签值存入refreshTag中，然后开始轮询
 *  添加和删除标签值后，会重新调用getValueData，执行上一步操作
 *  当有标签值状态更新后，会将refreshTag中对应的标签值移除
 *  当refreshTag中无数据时，终止轮询。
 * */
const validateTagValue = (rule, value, cb) => {
  if (value.some(el => !el.tagItemName)) {
    return cb(new Error('请完善标签值'));
  }
  cb();
}
const validateTagSort = (rule, value, cb) => {
  const res = /^[0-9]+$/;
  if (!res.test(value) || value > 100000 || value < 1) {
    cb(new Error('仅支持输入1-1-100000之间的整数'))
  }
  cb();
}
export default {
  name: 'manualTagEdit',
  props: {
    showPop: Boolean,
    options: Object,
    currentType: String  // manual手工标签  active活动标签
  },
  components: {
    tagValueItem
  },
  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' }],
        tagSort: [{ required: true, trigger: 'blur', validator: validateTagSort }],
        tagType: [{ required: true, trigger: 'blur' }],
        tagValue: [{ required: true, trigger: 'blur', validator: validateTagValue }]
      },
      // 标签所属分类的下拉列表数据
      optionsTwo: [],
      optionsThree: [],

      // 标签值列表的数据
      tagValTableData: [],
      preSyncWmStatus: 0,
      deleteList: [],
      isEdit: false
    };
  },
  watch: {
    options: {
      deep: 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();
      }
    }
  },
  methods: {
    closePop() {
      this.optionsThree = [];
      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 para = {
        tagId: this.options.tagId,
        tagName: this.ruleForm.tagName,
        tagDescribe: this.ruleForm.tagDescribe,
        tagLevelGroupId: this.ruleForm.tagLevelGroupId,
        tagItemList,
        isMultiple: this.ruleForm.tagType,
        tagType: this.currentType == 'active' ? 2 : 1 // 2 活动标签 1 手工
      };
      if (this.currentType == 'manual') {
        para.sort = this.ruleForm.tagSort;
      }
      postJson('/memberTag/saveHandMemberTag', para)
        .then(res => {
          const { errorCode, message } = res.data;
          this.ruleForm.pending = false;
          if (errorCode !== 1) {
            this.$message.error({
              duration: 1000,
              message: message
            });
            return;
          }
          showMsg.showmsg('保存成功', 'success');
          this.$emit('save');
          this.closePop();
        })
        .catch(error => {
          this.ruleForm.pending = false;
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    // 获取二级分类列表
    getOptionsTwo() {
      const { currentType } = this;
      const params = { tagLevelType: currentType == 'active' ? 2 : 1 };
      return getRequest('/tagLevel/handSecondLevel', params)
        .then(res => {
          const { errorCode, result } = res.data;
          if (errorCode === 1) {
            this.optionsTwo = result;
            if (currentType == 'active' && !this.isEdit) {
              this.ruleForm.tagTwoLevelGroupId = result.find(el => el.name === '渠道标签').id;
              this.getOptionsThree(this.ruleForm.tagTwoLevelGroupId);
            }
          }
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

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

    // 获取三级分类列表
    getOptionsThree(tagLevelGroupId) {
      getRequest('/tagLevel/handThirdLevel', { 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) {
      getRequest('/memberTag/getTagById', { 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 获取三级列表
            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 {
  margin-top: 10vh !important;
}
/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: 200px;
  overflow-y: auto;
}
</style>
