<template>
  <div class="common-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <div class="memberGroupEdit-wrap__body">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
            <el-form-item label="" prop="selectedTag">
              <div class="m-l-60">
                已选标签
                <span class="color-c0c4cc font-14">（同一个输入框内标签关系为且）</span>
              </div>
              <tags-group-list
                :selectedTagsData="ruleForm.selectedTags"
                :tagsGroupRelation="ruleForm.tagsGroupRelation"
                :activeTagsGroupIndex.sync="activeTagsGroupIndex"
                :showAddMenu="true"
                @addTags="addTags"
                @editTags="editTags"
              />
            </el-form-item>
            <el-form-item label="" prop="groupName" class="w-220">
              <div>分组名称</div>
              <el-input class="w-220" v-model="ruleForm.groupName" @input.native="e => toInput(e, 'groupName')"> </el-input>
              <label class="input-label">{{ ruleForm.groupNameLength }}/10</label>
            </el-form-item>
            <el-form-item label="" prop="effectiveDateTmp">
              <div>分组有效期</div>
              <el-date-picker v-model="ruleForm.effectiveDateTmp" type="date" :editable="false" format="yyyyMMdd" value-format="yyyy-MM-dd HH:mm:ss" default-time="23:59:59" :picker-options="pickerOptions">
              </el-date-picker>
              <div class="form-tip-text">
                <label>*分组有效期需早于所用标签的最早有效期，且最长不超过365天</label>
              </div>
            </el-form-item>
            <el-form-item label="" prop="describle" class="w-548">
              <div>分组描述</div>
              <el-input class="w-548" type="textarea" v-model="ruleForm.describle" style="height: 96px;" @input.native="e => toInput(e, 'describle')"> </el-input>
              <template>
                <label class="input-label textarea-label">{{ ruleForm.describleLength }}/200</label>
              </template>
            </el-form-item>
            <el-form-item label="" prop="updateDay" v-show="ruleForm.isActive == 0">
              <div>更新频率</div>
              <el-select class="w-200" v-model="ruleForm.updateType" placeholder="请选择" @change="ruleForm.updateDay = ''">
                <el-option v-for="(item, index) in rateData" :key="item.label" :label="item.label" :value="index + 1"></el-option>
              </el-select>
              <el-select class="w-200 p-l-8" v-model="ruleForm.updateDay" v-show="ruleForm.updateType != 1" placeholder="请选择">
                <el-option v-for="(item, index) in rateData[ruleForm.updateType ? ruleForm.updateType - 1 : 0].options" :key="item" :label="item" :value="index + 1"></el-option>
              </el-select>
              <div class="form-tip-text"><label>*更新时间预计选择日期的凌晨0点至6点</label></div>
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" @click.stop="confirmSave">保存</el-button>
              <el-button>
                <router-link to="/memberGroupList">返回</router-link>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <vue-gic-footer></vue-gic-footer>
  </div>
</template>

<script>
/**
 * #/member-tag
 * */
import navCrumb from '@/components/nav/nav.vue';
import tagsGroupList from './tags-group-list.vue';
import strLength from '@/common/js/strlen';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';

export default {
  name: 'memberGroupEdit',
  data() {
    const rateOneValid = (rule, value, callback) => {
      console.log(value);
      if (this.ruleForm.isActive == 0 && value == '') {
        callback(new Error('请选择更新频率'));
      } else {
        callback();
      }
    };
    const rateValid = (rule, value, callback) => {
      console.log(value, this.ruleForm);
      if (this.ruleForm.isActive == 0 && (this.ruleForm.updateType != '1' || this.ruleForm.updateType == '') && value == '') {
        console.log(value, this.ruleForm);
        callback(new Error('请选择更新频率'));
      } else {
        callback();
      }
    };
    return {
      // 编辑数据
      ruleForm: {
        // 会员分组id
        memberTagGroupId: '',
        // 已选标签
        selectedTags: [
          [
            // {
            //   tagId: 1,
            //   tagName: '有车一族',
            //   tagValue: '233',
            //   newTagVal: '',
            //   tagParams: '',
            //   isActive: 0
            // }
          ]
        ],
        // 标签组之间的关系
        tagsGroupRelation: [],
        newTagVal: '',
        // 分组名称
        groupName: '',
        // 分组名称的长度
        groupNameLength: 0,
        // 分组有效期
        effectiveDateTmp: '',
        // 分组描述
        describle: '',
        // 分组描述的长度
        describleLength: 0,
        // 非实时需要根据标签判断
        isActive: 0,
        // 更新频率类型 1=每日一次 2=每周一次 3=每月一次
        updateType: '',
        // 更新日期
        // 每日更新一次，无更新日期
        // 每周更新一次，更新日期1到7对应周一到周日
        // 每月更新一次，更新日期为每月1到28号
        updateDay: '',
        effectiveStatus: 1
      },
      activeTagsGroupIndex: 0,
      // 有效期时间选择器的配置
      pickerOptions: {
        disabledDate(time) {
          let curDate = new Date().getTime();
          let oneYear = 365 * 24 * 3600 * 1000;
          let y = curDate + oneYear;
          return time.getTime() < Date.now() - 8.64e7 || time.getTime() > y;
        }
      },
      // 表单验证规则
      rules: {
        selectedTag: [{ type: 'array', required: true, message: '请选择标签', trigger: 'blur' }],
        groupName: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
        effectiveDateTmp: [{ required: true, message: '请选择分组过期时间', trigger: 'change' }],
        updateType: [{ validator: rateOneValid, trigger: 'blur' }],
        updateDay: [{ validator: rateValid, trigger: 'change' }]
      },

      // 更新频率
      rateData: [
        {
          label: '每日一次',
          options: []
        },
        {
          label: '每周一次',
          options: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        {
          label: '每月一次',
          options: [
            '1号',
            '2号',
            '3号',
            '4号',
            '5号',
            '6号',
            '7号',
            '8号',
            '9号',
            '10号',
            '11号',
            '12号',
            '13号',
            '14号',
            '15号',
            '16号',
            '17号',
            '18号',
            '19号',
            '20号',
            '21号',
            '22号',
            '23号',
            '24号',
            '25号',
            '26号',
            '27号',
            '28号'
          ]
        }
      ]
    };
  },
  computed: {
    // 面包屑参数
    navpath() {
      let memberTagGroupId = this.$route.query.memberTagGroupId;
      return [
        {
          name: '首页',
          path: `${window.location.origin}/report/#/memberSummary`,
          relocation: true
        },
        {
          name: '会员标签',
          path: ''
        },
        {
          name: '会员分组',
          path: '/memberGroupList'
        },
        {
          name: memberTagGroupId ? '会员分组编辑' : '新增会员分组',
          path: ''
        }
      ];
    }
  },
  methods: {
    /**
     * 路由跳转
     */
    changeRoute(route) {
      this.$router.push(route);
    },

    // 添加标签
    addTags(data) {
      console.log(`添加标签，标签组的索引是${this.activeTagsGroupIndex}`);
    },

    // 编辑标签
    editTags(data) {
      console.log(`编辑标签，标签组的索引是${data.tagsGroupIndex}，标签的索引是${data.tagsIndex}`);
    },

    /**
     * 计算输入内容的长度、限制输入的长度
     */
    toInput(e, target) {
      let temp = '';
      switch (target) {
        case 'groupName':
          // 限制输入内容的长度
          temp = strLength.getCharVal(e.target.value, 10).trim();
          // 计算已经输入的内容的长度
          this.ruleForm.groupNameLength = strLength.getZhLen(temp);
          break;
        case 'describle':
          temp = strLength.getByteVal(e.target.value, 200).trim();
          this.ruleForm.describleLength = strLength.getByteLen(temp);
          break;
      }
    },

    /**
     * 已选标签-删除-检查实时 ????
     */
    checkRealTime() {
      const that = this;

      if (!!that.selectedTagData.length) {
        const arrTag = that.selectedTagData.map(item => parseInt(item.isActive));
        console.log('已选标签实时/非实时:', arrTag);
        if (arrTag.includes(0)) {
          that.ruleForm.isActive = 0; // 如果有非实时,最后都是非实时
        } else {
          that.ruleForm.isActive = 1;
        }
        console.log(that.ruleForm);
        return false;
      }
      that.ruleForm.isActive = 0; // 如果已选标签为空,就是非实时
    },

    /**
     * 点击保存
     */
    confirmSave: _debounce(function() {
      const that = this;
      that.$refs.ruleForm.validate(valid => {
        if (valid) that.postSave();
      });
    }, 500),

    confirmSavePost(formName) {
      // 优化掉
      return;
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          console.log('valid', that.ruleForm);
          const flag = that.ruleForm.isActive == 0 && that.ruleForm.updateType != 1 && that.ruleForm.updateDay == '';
          if (!!flag) {
            that.$message.error({ message: '请选择更新频率!' });
            return false;
          }

          that.postSave(that.ruleForm);
        } else {
          return false;
        }
      });
    },

    /**
     * 点击保存---api
     */
    postSave() {
      const that = this;
      let ruleForm = this.ruleForm;
      const para = {
        memberTagGroupId: ruleForm.memberTagGroupId,
        groupName: ruleForm.groupName,
        isRealTime: ruleForm.isActive,
        describle: ruleForm.describle,
        updateType: ruleForm.updateType,
        updateDay: ruleForm.updateDay,
        effectiveStatus: ruleForm.effectiveStatus,
        json: JSON.stringify(ruleForm.selectedTags),
        effectiveDateTmp: `${ruleForm.effectiveDateTmp.split(' ')[0]} 23:59:59`
      };

      let postUrl = !!that.ruleForm.memberTagGroupId ? '/member-tag-group/update.json' : '/member-tag-group/add.json';

      postRequest(postUrl, para)
        .then(res => {
          if (res.data.errorCode == 1) {
            showMsg.showmsg('编辑成功', 'success');
            that.changeRoute('/memberGroupList');
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    /**
     *  编辑时候---获取分组数据
     */
    getGroupData() {
      postRequest('/member-tag-group/findOneDetial.json', { memberTagGroupId: this.ruleForm.memberTagGroupId })
        .then(res => {
          const resData = res.data;
          if (resData.errorCode == 1) {
            let tagGroupDto = resData.result.tagGroupDto;
            if (!!tagGroupDto) {
              this.ruleForm.groupName = tagGroupDto.groupName;
              this.ruleForm.isActive = tagGroupDto.isRealTime;
              this.ruleForm.effectiveStatus = tagGroupDto.effectiveStatus;
              this.ruleForm.describle = tagGroupDto.describle;
              this.ruleForm.effectiveDateTmp = tagGroupDto.effectiveDate;
              this.ruleForm.updateType = !!tagGroupDto.updateType ? Number(tagGroupDto.updateType) : '';
              this.ruleForm.updateDay = !!tagGroupDto.updateDay ? Number(tagGroupDto.updateDay) : '';
              this.ruleForm.groupNameLength = strLength.getZhLen(this.ruleForm.groupName);
              this.ruleForm.describleLength = strLength.getByteLen(this.ruleForm.describle);
            }

            let tagValueDtoList = Array.isArray(resData.result.tagValueDtoList) ? resData.result.tagValueDtoList : [];

            this.ruleForm.selectedTags = tagValueDtoList.map(item => {
              return item.map(el => {
                if (Object.prototype.toString.call(el) === '[object Object]') {
                  let newTagVal = JSON.parse(el.tagParams);
                  el.newTagVal = newTagVal.selectedVal ? JSON.stringify(newTagVal.selectedVal) : '';
                }
                return el;
              });
            });
            this.ruleForm.selectedTags = this.ruleForm.selectedTags.filter(item => item.length > 0);
          }
        })
        .catch(error => {
          console.log(error);
        });
    }
  },
  mounted() {
    let localData = sessionStorage.getItem('selectTempTag');
    let memberTagGroupId = this.$route.query.memberTagGroupId;
    if (!!localData) {
      this.ruleForm.selectedTags = JSON.parse(localData);
      sessionStorage.removeItem('selectTempTag');
    }

    if (!!memberTagGroupId) {
      this.ruleForm.memberTagGroupId = memberTagGroupId;
      this.getGroupData();
    } else {
      let date = new Date(new Date().getTime() + 365 * 24 * 3600 * 1000);
      let Y = date.getFullYear() + '-';
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      this.ruleForm.effectiveDateTmp = Y + M + D + '23:59:59';
    }
  },
  components: {
    navCrumb,
    tagsGroupList
  }
};
</script>

<style lang="scss" scoped>
.m-l-60 {
  margin-left: 60px;
}

.memberGroupEdit-wrap__body {
  width: 100%;
  font-size: 14px;

  .form-tip-text {
    margin-top: 8px;
    height: 13px;
    line-height: 13px;
    font-size: 13px;
    color: #909399;
  }

  .input-label {
    position: absolute;
    right: 10px;
    top: 34px;
    font-size: 12px;
    color: #909399;
  }

  .textarea-label {
    position: absolute;
    right: 10px;
    top: 96px;
    font-size: 12px;
    color: #909399;
  }
}
</style>
