<template>
  <div class="memberGroupEdit-wrap 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" class="demo-ruleForm">
            <el-form-item label="" prop="selectedTag">
              <div class="memberGroupEdit-wrap__item__title">已选标签<span class="color-c0c4cc font-14">（筛选同时符合下列条件的会员）</span>
              <el-button type="text" class="m-l-220" @click="showAddTag">添加标签</el-button>
              </div>
              <div class="memberGroupEdit-wrap__tags w-548 border-box">

                <div class="memberGroupEdit-wrap__tagcell" v-for="(item,index) in selectedTagData" :key="index">
                  <span>{{item.tagName}}</span>
                  <span class="memberGroupEdit-wrap__tag-name">【选择:{{item.newTagVal}}】</span>
                  <i class="iconfont icon-bianji" @click="editSelTag(index,item)"></i>
                  <i class="iconfont icon-shanchu" @click="delSelTag(index,item)"></i>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="" prop="groupName" class="w-220">
              <div class="memberGroupEdit-wrap__item__title">分组名称</div>
              <el-input class="w-220" v-model="ruleForm.groupName" @focus="focus('groupName',10)" @keyup.native="(value) => toInput(value)">
              </el-input>
              <label class="input-label">{{inputNumObj.groupName}}/10</label>
            </el-form-item>
            <el-form-item label="" prop="effectiveDateTmp">
              <div class="memberGroupEdit-wrap__item__title">分组有效期</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><label class="p-l-8">*人群有效期需早于所用标签的最早有效期，且最长不超过365天</label>
            </el-form-item>
            <el-form-item label="" prop="describle" class="w-548">
              <div class="memberGroupEdit-wrap__item__title">分组描述</div>
              <el-input class="w-407" type="textarea" v-model="ruleForm.describle" style="height: 96px;" @focus="focus('describle',200)" @keyup.native="(value) => toInput(value)">
              </el-input>
               <template><label class="input-label textarea-label">{{inputNumObj.describle}}/200</label></template>
            </el-form-item>
            <el-form-item label="" class="" prop="updateDay" v-if="ruleForm.isActive == 1">
            <div class="memberGroupEdit-wrap__item__title">更新频率</div>
              <el-select v-model="ruleForm.updateType" placeholder="请选择" class="w-200" @change="changeRate(ruleForm.updateType)">
                <el-option label="每日一次" value="1"></el-option>
                <el-option label="每周一次" value="2"></el-option>
                <el-option label="每月一次" value="3"></el-option>
              </el-select><el-select
                v-model="ruleForm.updateDay"
                v-if="ruleForm.updateType != 1"
                placeholder="请选择"
                class="w-200 p-l-8">
                <el-option
                v-for="item in rateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">

                </el-option>
              </el-select>
              <label class="p-l-8">*更新时间预计选择日期的凌晨0点至6点</label>
            </el-form-item>
            <el-form-item label="" class="">
              <el-button type="primary" @click.stop="confirmSave('ruleForm')">保存</el-button>
              <el-button @click.stop="cancelSave">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <vue-gic-footer></vue-gic-footer>
    <!-- 标签详情缩写版 -->
    <tagShortDetail
      :fromFlag="fromFlag"
      :showTagDetail="showTagDetail"
      :tagShortId.sync="tagShortDetailId"
      :tabActive="tabActiveName"
      @hideTag="handleHideTag"
      @returnTagData="returnTagData" >
    </tagShortDetail>

    <!-- 会员分组-我的标签列表和暂存架 -->
    <add-tag-view
      ref="addTagViewComponent"
      :delTagId="delTagId"
      :addTagShow.sync="showTagFlag"
      :selTagData="selectedTagData"
      :returnEditObj="returnEditObj"
      @showTabActive="showTabActive"
      @showShortDetail="showShortDetail"
      @returnTempData="returnTempData"
      @returnTempTableData="returnTempTableData"
      @returnTempTagId="returnTempTagId"
      @returnTempRowData="returnTempRowData">
    </add-tag-view>
  </div>
</template>
<script>
  import navCrumb from '@/components/nav/nav.vue';
  import addTagView from '@/components/addTagView.vue';
  import tagShortDetail from '@/components/tagShortDetail.vue';
  import strLength from '@/common/js/strlen';
  import showMsg from '@/common/js/showmsg';
  import errMsg  from '@/common/js/error';
  import { _debounce } from "@/common/js/public";
  import { getRequest, postRequest, postJson, postForm } from '@/api/api';
  export default {
      name: "memberGroupEdit",
      data() {

        const rateOneValid = (rule, value, callback) => {
          console.log(value)
          if (this.ruleForm.isActive == 1 && value == '') {
            callback(new Error('请选择更新频率'));
          } else {
             callback();
          }
        };
        const rateValid = (rule, value, callback) => {
          console.log(value,this.ruleForm)
          if (this.ruleForm.isActive == 1 && (this.ruleForm.updateType != '1'||this.ruleForm.updateType == '') && value == '') {
            console.log(value,this.ruleForm)
            callback(new Error('请选择更新频率'));
          } else {
             callback();
          }
        };
        return {
          // 面包屑参数
          navpath: [
            {
              name: '首页',
              path: ''
            },
            {
              name: '会员标签',
              path: ''
            },
            {
              name: '会员分组编辑',
              path: ''
            }
          ],

          // 编辑数据
          ruleForm: {
            memberTagGroupId: '',
            selectedTag: [],
            newTagVal: '',
            groupName: '',
            effectiveDateTmp: '',
            describle: '',
            isActive: 0, // 非实时需要根据标签判断
            updateType: '',
            updateDay: '',
            effectiveStatus: 1,
          },
          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' }
            ],
          },

          // 计算输入
          inputNumObj: {
            groupName: 0,
            describle: 0,
          },

          // 频率
          rateOptions:[
            // {
            //   value: '0',
            //   label: '周一'
            // },
            // {
            //   value: '1',
            //   label: '周二'
            // },
          ],

          showTagFlag: false, //是否显示需要添加的标签层

          // 已选标签数据
          selectedTagData: [
            // {
            //   tagId: 1,
            //   tagName: '有车一族',
            //   tagValue: '233',
            //   newTagVal: ''
            //   tagParams: '',
            //   isActive: 0,
            // },
          ],

          showTagDetail: false, // 标签详情缩小版显示/隐藏
          tagShortDetailId: '', // 标签详情缩写版 id
          fromFlag: 'memberGroup', // 参数--来源标志
          delTagId: '',// 删掉 id
          returnEditObj: {}, // 标签详情缩小版返回的对象

          tabActiveName: 'first',// 我的标签列表/暂存架

        }
      },
      methods: {
        /**
         * 路由跳转
         */
        changeRoute(route) {
          this.$router.push(route);
        },

        /**
         * 点击显示添加标签层
         */
        showAddTag() {
          const that = this
          that.showTagFlag = true;
        },

        /**
         * 点击输入框
         */
        focus(name,num) {
          const that = this
          console.log(name,num);
          that.inputFlag = name;
          that.inputFlagNum = num;
        },

        /**
         * 输入
         */
        toInput: function(value) {
          const that = this;
          console.log(value);

          let temp = '';
          temp = strLength.getByteVal(value.target.value,that.inputFlagNum);
          console.log(temp)
          that.ruleForm[that.inputFlag] = temp.trim();

          that.inputNumObj[that.inputFlag] = strLength.getZhLen(that.ruleForm[that.inputFlag]);

          console.log(that.ruleForm[that.inputFlag]);
        },

        /**
         * 更新频率
         */
        changeRate(rate,day) {
          const that = this
          console.log(rate,day)
          that.ruleForm.updateDay = !!day? String(day): '';
          if (rate == 2) {
            that.rateOptions = [];
            let week = ['一','二','三','四','五','六','日'];
            for (var i = 0; i <7; i++) {
              that.rateOptions.push(
                {
                  value: String(i+1),
                  label: `周${week[i]}`
                }
              )
            }
            return
          }
          if (rate == 3) {
            that.rateOptions = [];

            for (var i = 1; i <29; i++) {
              that.rateOptions.push(
                {
                  value: ''+i,
                  label: `${i} 号`
                }
              )
            }
            return
          }
        },

        /**
         * 已选标签-编辑
         */
        editSelTag(index,item) {
          const that = this
          that.showTagDetail = true;
          that.tagShortDetailId = item.tagId;
        },

        /**
         * 已选标签-删除
         */
        delSelTag(index,item) {
          const that = this
          console.log(that.selectedTagData)
          that.selectedTagData.splice(index,1)
          console.log(that.selectedTagData)
          that.ruleForm.selectedTag = that.selectedTagData
          // 检查实时
          that.checkRealTime();
          that.delTagId = item.tagId;
          // setTimeout(function(){
          //   that.$refs.addTagViewComponent.toDelTagId()
          // },10)
        },

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

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

        /**
         * 点击取消
         */
        cancelSave() {
          const that = this;
          that.changeRoute('/memberGroupList')
        },

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

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

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

          let postUrl = '/member-tag-group/add.json';
          if (!!that.ruleForm.memberTagGroupId) {
            postUrl = '/member-tag-group/update.json';
          }

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

            errMsg.errorMsg(resData)

          })
          .catch(function (error) {
            console.log(error);

            that.$message.error({
              duration: 1000,
              message: error.message
            })
          });
        },



        /**
         * 子组件 我的标签库/暂存架 -点击名字显示标签详情缩略版
         */
        showShortDetail(id) {
          const that = this;
          that.showTagDetail = true
          that.tagShortDetailId = id
        },

        /**
         * 子组件触发---隐藏标签详情缩小版
         */
        handleHideTag(val) {
          const that = this;
          that.showTagDetail = false
        },

        /**
         * 判断添加重复字段
         */
        isRepeat(arr) {
          var hash = {};
          for(var i in arr) {
            if(hash[arr[i]]){
               return true;
             }
             hash[arr[i]] = true;
          }
          return false;
        },

        /**
         *  子组件触发---标签详情缩略版编辑值后返回参数
         */
        returnTagData(obj) {
          const that = this;
          console.log("返回obj:",obj)
          that.returnEditObj = obj; // 标签详情编辑后返回的标签数据
          if (that.tabActiveName == 'second') {
            // 如果是在暂存架修改标签值

            return false;
          }
          let allIds = !!that.selectedTagData.length? that.selectedTagData.map(item=>item.tagId): [];

          if (allIds.indexOf(obj.tagId) != -1) {
            // 存在覆盖
            let newList = JSON.parse(JSON.stringify(that.selectedTagData))
            newList.forEach(function(ele,index){
              if (ele.tagId == obj.tagId) {
                ele.tagValue = obj.tagValue;
                ele.tagParams = obj.tagParams;
              }
            })
            that.selectedTagData = newList;
          }else {
            console.log(allIds.indexOf(obj.tagId))
            // 不存在直接追加
            that.selectedTagData.unshift(JSON.parse(JSON.stringify(obj)))
            console.log("处理obj:",that.selectedTagData)
          }
          that.handleReturnData(that.selectedTagData)
        },

        /**
         *  子组件触发-- 全选---暂存架全选后返回参数
         */
        returnTempData(arr){
          const that = this;
          console.log("暂存架全选数据:",arr)
          if (!!arr.length) {
            let tagAllIds = arr.map(item=>item.tagId)
            console.log(tagAllIds)
            // 存在先删除,后追加新数据
            let midData = JSON.parse(JSON.stringify(that.selectedTagData))
            let newMidData = [];
            midData.forEach(function(ele,index){
              // 全选中如果有标签不在 已选数据中,就要单独挑出来
              if (!tagAllIds.includes(ele.tagId)) {
                newMidData.push(ele)
              }
            })
            // midData = midData.filter(item=>(tagIds.indexOf(item.tagId) == -1))
            // console.log("处理已选的时候:",newMidData)
            arr.forEach(function(ele,index){
              newMidData.unshift(ele)
            })
            that.selectedTagData = newMidData
            // console.log("全选的时候:",newMidData)
            that.handleReturnData(that.selectedTagData)
          }
        },

        /**
         *  子组件触发--全不选---返回暂存架所有标签数据
         */
        returnTempTableData(arrData){
          const that = this
          console.log("返回暂存架所有标签数据:",arrData)
          let tagIds = arrData.map(item=>item.tagId);
          // 存在先删除,后追加新数据
          let midData = JSON.parse(JSON.stringify(that.selectedTagData))
          let newMidData = [];
          midData.forEach(function(ele,index){
            if (!tagIds.includes(ele.tagId)) {
              newMidData.push(ele);
            }
          })

          console.log("全不选:",midData)
          that.selectedTagData = newMidData;
          that.handleReturnData(that.selectedTagData);
        },

        /**
         *  子组件触发--返回暂存架标签 id
         */
        returnTempTagId(id){
          const that = this
          console.log("返回暂存架标签 id:",id)
          let delData = JSON.parse(JSON.stringify(that.selectedTagData))
          delData.forEach(function(ele,index){
            if (ele.tagId == id) {
              that.selectedTagData.splice(index,1)
            }
          })
          console.log("返回暂存架标签 id 后:",that.selectedTagData)
          // 更新 form 数据
          that.ruleForm.selectedTag = that.selectedTagData
        },

        /**
         *  子组件触发--返回暂存架当前标签数据
         */
        returnTempRowData(row){
          const that = this
          // 判断当前标签是否在已选数据中
          let delData = JSON.parse(JSON.stringify(that.selectedTagData))
          delData.forEach(function(ele,index){
            if (ele.tagId == row.tagId) {
              ele.tagParams = row.tagParams;
              ele.tagValue = row.tagValue;
              ele.newTagVal = row.newTagVal;
            }
          })
          let ids = delData.map(item=>item.tagId)
          // 暂存架选择的标签不在已选数据中
          if (ids.indexOf(row.tagId) == -1) {
            delData.unshift(row)
          }

          that.selectedTagData = delData;
          that.ruleForm.selectedTag = that.selectedTagData;
        },

        /**
         *  子组件触发--返回参数处理
         */
        handleReturnData(selectedTagData) {
          const that = this;
          // 提取选择值
          selectedTagData.forEach(function(ele,index){
            let newTagVal = JSON.parse(ele.tagParams)
            if (newTagVal.selectedVal != '') {
              ele.newTagVal = newTagVal.selectedVal
            }else{
              ele.newTagVal = ''
            }
          })

          that.ruleForm.selectedTag = selectedTagData
          // 判断实时非实时
          that.checkRealTime();

          // 刷新暂存架
          // console.log(that.$refs.addTagViewComponent)
          // that.$refs.addTagViewComponent.refreshTemp();
        },

        /**
         *  子组件触发--返回当前 tab
         */
        showTabActive(name){
          const that = this;
          that.tabActiveName = name;
        },

        /**
         *  编辑时候---获取分组数据
         */
        getGroupData(){
          const that = this;
          const para = {
            memberTagGroupId: that.ruleForm.memberTagGroupId,
          }

          postRequest('/member-tag-group/findOneDetial.json',para)
          .then((res) => {
            // console.log(res,res.data,res.data.errorCode)
            const resData = res.data
            if (resData.errorCode == 1) {

              let tagGroupDto = resData.result.tagGroupDto;
              if (!!tagGroupDto) {
                that.ruleForm.groupName = tagGroupDto.groupName;
                that.ruleForm.isActive = tagGroupDto.isRealTime;
                that.ruleForm.effectiveStatus = tagGroupDto.effectiveStatus;
                that.ruleForm.describle = tagGroupDto.describle;
                that.ruleForm.effectiveDateTmp = tagGroupDto.effectiveDate;
                that.ruleForm.updateType = String(tagGroupDto.updateType);
                that.ruleForm.updateDay = String(tagGroupDto.updateDay);
                that.inputNumObj['groupName'] = strLength.getZhLen(that.ruleForm['groupName']);

                if (that.ruleForm.updateType != 1) {
                  that.changeRate(that.ruleForm.updateType,that.ruleForm.updateDay)
                }
              }

              let tagValueDtoList = resData.result.tagValueDtoList;

              tagValueDtoList.forEach(function(ele,index){
                let newTagVal = JSON.parse(ele.tagParams)
                if (newTagVal.selectedVal != '') {
                  ele.newTagVal = newTagVal.selectedVal
                }else{
                  ele.newTagVal = ''
                }
              })

              that.ruleForm.selectedTag = tagValueDtoList;
              that.selectedTagData = tagValueDtoList;
              return;
            }

            errMsg.errorMsg(resData)

          })
          .catch(function (error) {
            console.log(error);

            that.$message.error({
              duration: 1000,
              message: error.message
            })
          });
        }

      },
      mounted() {
        const that = this
        let localData = sessionStorage.getItem('selectTempTag')
        if (!!localData) {
          // that.selectedTagData = JSON.parse(localData);
          that.ruleForm.selectedTag = JSON.parse(localData);
          setTimeout(function(){
            that.selectedTagData = JSON.parse(localData);
          },500)
          sessionStorage.removeItem('selectTempTag')
        }

        if (!!that.$route.query.memberTagGroupId) {
          that.ruleForm.memberTagGroupId = that.$route.query.memberTagGroupId;
          that.getGroupData();
        }
      },
      components: {
        navCrumb,
        addTagView,
        tagShortDetail
      }
    }
</script>
<style lang="scss" scoped>

  .memberGroupEdit-wrap__tags {
    max-height: 222px;
    min-height: 100px;
    padding: 12px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    overflow-y:auto;

    .memberGroupEdit-wrap__tagcell {
      display: inline-block;
      vertical-align: top;
      padding: 0 10px;
      margin-right: 8px;
      margin-bottom: 8px;
      background: #F3F6F9;
      border-radius: 2px;
      &:last-child {
        margin-bottom: 0;
      }

      span {
        display: inline-block;
        vertical-align: middle;
      }

      i {
        font-size: 18px;
        color: #4A4A4A;
        cursor: pointer;
      }

      .memberGroupEdit-wrap__tag-name {
        max-width: 200px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

  }

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

    .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>
