<template>
  <div class="common-wrap">
    <div class="right-content">
      <div class="right-box">
        <div class="memberGroupEdit-wrap__body">
          <div v-if="$route.query.memberTagGroupId && useList.length" class="m-b-30 alert-title">
            <el-alert
              title="警告提示的文案"
              type="warning"
              class="alert"
              :closable="false"
              show-icon>
              <template #title>
                <span class="label font-12">编辑后会影响正在使用该分组的活动，请谨慎编辑。使用该分组的活动</span>
                <span class="tips font-12">(仅展示未开始和进行中的活动)：</span>
                <span v-for="(item, idx) in useList" :key="idx" style="display:inline-block">
                  <a class="font-12" :href="item.businessLink" target="_blank">{{ item.businessModuleName }}-{{ item.businessName }}</a>
                  <span style="color: #303133" v-if="idx < useList.length - 1">、</span>
                </span>
              </template>
            </el-alert>
          </div>
          <dm-sub-title text="配置标签" class="m-b-10" />
          <div class="group-tips">
            <span class="desc">一个标签框内标签之间的关系为且，可添加多个标签框，多个标签框之间可切换“或者”/“剔除”。</span>
          </div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
            <el-form-item label prop="selectedTag">
              <tags-group-list
                :selectedTagsData="ruleForm.selectedTags"
                :tagsGroupRelation="ruleForm.tagsGroupRelation"
                :activeTagsGroupIndex.sync="activeTagsGroupIndex"
                :activeTagIndex.sync="activeTagIndex"
                :showAddMenu="true"
                @addTags="addTags"
                @editTags="editTags"
              />
            </el-form-item>
            <dm-sub-title text="配置分组" style="margin-top: 34px" class="m-b-24 m-t-34" />
            <el-form-item
              label
              prop="groupName"
            >
              <div class="label-title">分组名称</div>
              <el-input
                v-model="ruleForm.groupName"
                :maxlength="10"
                placeholder="请输入分组名称"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item
              label
              prop="effectiveDateTmp"
              v-if="!ruleForm.isActive"
            >
              <div class="effective label-title">
                分组有效期至
                <el-tooltip content="分组有效期需早于所用标签的最早有效期，且最长不超过730天">
                  <i class="iconfont icon-QuestionCircleOutlined m-l-4 tip-icon"></i>
                </el-tooltip>
              </div>
              <el-date-picker
                v-model="ruleForm.effectiveDateTmp"
                type="date"
                :clearable="false"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                default-time="23:59:59"
                style="width: 100%"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label prop>
              <div class="label-title">分组所属分类</div>
              <el-select v-model="ruleForm.memberTagGroupClassifyId" v-loadmore="onLoadmore" style="width: 100%" filterable placeholder="请选择">
                <el-option
                  v-for="item in memberGroupList"
                  :key="item.memberTagGroupClassifyId"
                  :value="item.memberTagGroupClassifyId"
                  :label="item.classifyName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label prop="fixedType">
              <div class="label-title m-b-15">是否固化<el-link class="m-l-16" type="primary" :underline="false" target="_blank" href="https://www.yuque.com/exnmlu/hpbb1c/ke8o0d">什么是固化？</el-link></div>
              <el-radio-group v-model="ruleForm.fixedType" class="radio-group" :disabled="$route.query.memberTagGroupId">
                <el-radio :label="0" class="m-b-0">否</el-radio>
                <el-radio :label="1" class="m-b-0">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label prop="fixedTime" v-if="ruleForm.fixedType">
              <div class="label-title">固化生效时间</div>
              <el-date-picker :clearable="false" :picker-options="ruleForm.isActive ? realTimeOptions : fixedTimeOptions" v-model="ruleForm.fixedTime" value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label prop="isTogether" v-if="ruleForm.fixedType">
             <div class="label-title m-b-15">是否同时生成非固化分组</div>
              <el-radio-group v-model="ruleForm.isTogether" class="radio-group" :disabled="$route.query.memberTagGroupId">
                <el-radio :label="false" class="m-b-0">否</el-radio>
                <el-radio :label="true" class="m-b-0">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label
              prop="updateDay"
            >
            <div class="form-item">
              <div class="label-title">更新频次<span class="desc-labeltxt">{{ updateTypeDesc() }}</span></div>
              <el-select v-model="ruleForm.updateType" placeholder="请选择" disabled  style="width: 100%">
                <el-option v-for="item in rateData" :key="item.label" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </div>
            </el-form-item>
            <el-form-item
              label
              prop="describle"
            >
              <div class="label-title">分组描述</div>
              <el-input
                type="textarea"
                v-model="ruleForm.describle"
                resize="none"
                :maxlength="100"
                show-word-limit
                rows="4"
              ></el-input>
            </el-form-item>
            <el-form-item label :class="{'m-l-60': ruleForm.selectedTags.length > 1}">
              <!-- <div class="tips-count" style="color: red;margin-bottom: 15px;" v-show="!(ruleForm.fixedType && !ruleForm.isTogether) && ruleForm.isActive == 0 && realCount.totalCount <= realCount.currCount">
                您的非实时会员分组数量已达上限{{realCount.totalCount}}，建议您删除或失效部分非实时会员分组！
              </div> -->
              <template v-if="hasFixed">
                <el-tooltip class="item" effect="dark" placement="top-start" content="该分组包含固化人群，不可编辑">
                  <el-button type="primary" style="color: #c0c4cc;cursor: not-allowed;background-image: none;background-color: #F5F7FA;border-color: #DCDFE6;">{{$route.query.memberTagGroupId ? '保存': '创建会员分组'}}</el-button>
                </el-tooltip>
              </template>
              <div class="footer">
                <template v-if="!hasFixed">
                  <el-tooltip class="item" effect="dark" :disabled="ruleForm.isActive == 0 && realCount.totalCount <= realCount.currCount" content="您商户的非实时分组数量已达到上限" placement="top-start" v-if="isAllowAdd && ruleForm.isActive == 0">
                    <el-button type="primary" style="color: #c0c4cc;cursor: not-allowed;background-image: none;background-color: #F5F7FA;border-color: #DCDFE6;">{{$route.query.memberTagGroupId ? '保存': '创建会员分组'}}</el-button>
                  </el-tooltip>
                   <!-- :disabled="!($route.query.memberTagGroupId && ruleForm.isActive == 1) && (!(ruleForm.fixedType && !ruleForm.isTogether) && ruleForm.isActive == 0 && realCount.totalCount <= realCount.currCount)" -->
                  <el-button
                    v-else
                    type="primary"
                    @click.stop="confirmSavePost"
                  >{{$route.query.memberTagGroupId ? '保存': '创建会员分组'}}</el-button>
                </template>
                <el-button>
                  <router-link to="/memberGroupList">返回</router-link>
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 选择标签 -->
    <el-dialog :visible.sync="showSelectTagPop" title="选择标签" custom-class="tags-body" width="980px">
      <el-tabs v-model="activeTag" @tab-click="handleClick" class="tabs">
        <el-tab-pane v-if="isShowSystem" label="系统标签" name="system"></el-tab-pane>
        <el-tab-pane label="手工标签" name="manual"></el-tab-pane>
        <el-tab-pane label="活动标签" name="active"></el-tab-pane>
        </el-tabs>
      <div class="tags">
        <div class="tags-list">
          <el-tree
            :data="setCurrentTagList"
            class="tags-tree"
            :props="{ label: 'nameStr', children: 'children' }"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false"
            @node-click="treeClick"
          ></el-tree>
        </div>
        <div class="tags-table">
          <div class="tags-search">
            <el-input
              placeholder="请输入标签名称"
              prefix-icon="el-icon-search"
              v-model="searchData"
              @change="searchTags"
              clearable
            ></el-input>
          </div>
          <tag-container
            :data="tagsGroupList"
            resource="memberGroupEdit"
            :refersh="refreshList"
            @addTag="selectedTag"
            :type="activeTag"
            :key="activeTag"
            style="height: 475px;overflow-y: auto;"
          ></tag-container>
          <div class="page-box">
            <dm-pagination
              :pager-count="5"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-size="pageSize"
              layout="prev, pager, next"
              :total="total"
              v-if="total > 0"
            ></dm-pagination>
          </div>
        </div>
      </div>
    </el-dialog>
    <!--  添加标签、编辑标签  -->
    <edit-tag
      :showEditTagPop.sync="showEditTagPop"
      :tagData="tagData"
      :title="editPopType === 'add' ? '添加标签' : '编辑标签'"
      @returnTagData="returnTagData"
      @refersh="refresh"
      :creatorId="creatorId"
    ></edit-tag>
    <!-- <vue-gic-footer></vue-gic-footer> -->
  </div>
</template>

<script>
import './tags-detail.css';
import tagContainer from './choose-tag-table.vue';
import editTag from './edit-tag';
import tagsGroupList from './tags-group-list.vue';
import showMsg from '@/common/js/showmsg';
import { postRequest } from '@/api/api';
import { getMemberTagCount } from '@/request/memberGroup.js';
import { getMemberTagList, memberGroupList, getIsAllowAdd, groupCount } from '@/request/api.js';
import { parseTime } from '@/utils'
import { dateformat } from '@/utils/formatTime';
import errMsg from '@/common/js/error';
import {
  getGroupUseList,
  isShowSystemTag
} from '@/request/api';;
let fixBeginTime = +new Date() + (1000 * 60 * 60 * 24);
const shortTimeFn = (text, day, type) => {
  return {
    text,
    onClick(picker) {
      let curDate = new Date();
      if (type == 'day') {
        curDate.setDate(day + curDate.getDate());
      } else {
        curDate.setMonth(day + curDate.getMonth());
        curDate = new Date(+new Date(curDate) - 24 * 60 * 60 * 1000);
      }
      picker.$emit('pick', curDate);
    }
  }
}
export default {
  name: 'memberGroupEdit',
  data() {
    return {
      pager: {
        pageNum: 1,
        total: 1
      },
      realCount: {},
      templateCode: '',
      // 编辑数据
      ruleForm: {
        // 会员分组id
        memberTagGroupId: '',
        // 会员分组分类id
        memberTagGroupClassifyId: '',
        creatorId: '',
        // 已选标签
        selectedTags: [
          [
            // {
            //   tagId: 'a',
            //   tagName: '有车一族',
            //   tagValue: '233',
            //   newTagVal: '233',
            //   tagParams: '',
            //   isActive: 0
            // }
          ]
        ],
        // 标签组之间的关系
        tagsGroupRelation: [],
        newTagVal: '',
        // 分组名称
        groupName: '',
        // 分组有效期
        effectiveDateTmp: '',
        // 分组描述
        describle: '',
        // 非实时需要根据标签判断
        isActive: 0,
        // 更新频率类型 1=每日一次 2=每周一次 3=每月一次
        updateType: 1,
        // 更新日期
        // 每日更新一次，无更新日期
        // 每周更新一次，更新日期1到7对应周一到周日
        // 每月更新一次，更新日期为每月1到28号
        updateDay: '',
        effectiveStatus: 1,
        fixedType: 0, // 是否固化人群
        fixedTime: parseTime(new Date().setHours(24,0,0,0), '{y}-{m}-{d}'), // 期初固化时间
        isTogether: false // 是否同时开启非固化分组
      },
      refreshList: {},

      // 标签组的索引
      activeTagsGroupIndex: 0,
      // 标签的索引
      activeTagIndex: 0,

      // 有效期时间选择器的配置
      pickerOptions: {
        disabledDate(time) {
          let curDate = new Date().getTime();
          let twoYears = 2 * 365 * 24 * 3600 * 1000;
          let y = curDate + twoYears;
          return time.getTime() < Date.now() - 8.64e7 || time.getTime() > y;
        },
        shortcuts: [
          shortTimeFn('一天', 0, 'day'),
          shortTimeFn('一周', 6, 'day'),
          shortTimeFn('一个月', 1, 'month'),
          shortTimeFn('三个月', 3, 'month'),
          shortTimeFn('六个月', 6, 'month'),
        ]
      },
      fixedTimeOptions: {
        disabledDate: (date)=> {
          let begin = new Date().setHours(24,0,0,0);
          let end = new Date(this.ruleForm.effectiveDateTmp).getTime();
          return date.getTime() < begin || date.getTime() > end ;
        }
      },
      realTimeOptions: {
        disabledDate: date => {
          return date.getTime() < +new Date()
        }
      },
      // 会员分组分类
      memberGroupList: {},
      // 表单验证规则
      rules: {
        selectedTags: [{ type: 'array', required: true, message: '请选择标签', trigger: 'blur' }],
        groupName: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
        effectiveDateTmp: [{ required: true, message: '请选择分组过期时间', trigger: 'change' }],
      },

      // 更新频率
      rateData: [
        {
          label: '实时更新',
          value: 0
        },
        {
          label: '每日一次',
          value: 1
        },
        {
          label: '生效后更新一次',
          value: 2
        },
        {
          label: '生效后更新一次',
          value: 3
        },
      ],

      // 是否显示选择标签的弹窗
      showSelectTagPop: false,
      // 标签分组的数据
      tagsList: [],
      // 一组标签的数据
      tagsGroupList: [],
      // 搜索框
      searchData: '',

      // 是否显示编辑标签的弹窗
      showEditTagPop: false,
      // 编辑标签的弹窗类型 add=新增 edit=编辑
      editPopType: 'add',
      // 单个标签的数据
      tagData: {},

      // 分页相关
      pageNum: 1,
      pageSize: 20,
      total: 0,

      isAllowAdd: false,
      hasFixed: false, // 是否包含固化人群
      useList: [], // 引用列表
      activeTag: 'system',
      isShowSystem: true,
    };
  },
  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: ''
        }
      ];

    },
    setCurrentTagList() {
      const { activeTag } = this;
      if (activeTag == 'manual') {
        let arr = this.tagsList.find(el => el['handTag'] === 1);
        arr = arr ? arr.children : arr;
        return arr || [];
      } else if (activeTag == 'active') {
        let arr = this.tagsList.find(el => el['handTag'] === 2);
        arr = arr ? arr.children : arr;
        return arr || [];
      } else {
        return this.tagsList.filter(el => {
          return el['handTag'] === 0;
        });
      }
    }
  },
  /**
   * 检查标签是不是实时
   * 1=实时 0=非实时
   */
  watch: {
    ruleForm: {
      deep: true,
      handler: function(n,o){
        console.log(0)
        let flag =
          this.ruleForm.selectedTags.length === 0 ||
          this.ruleForm.selectedTags.some(tagsGroup => {
            return tagsGroup.length === 0 || tagsGroup.some(tag => parseInt(tag.isActive) === 0);
          });
        this.ruleForm.isActive = flag ? 0 : 1;
        this.handlerIsActive(this.ruleForm.isActive);
      }
    },
    'ruleForm.fixedType'(newVal) {
      const { isActive } = this.ruleForm;
      this.ruleForm.updateType = this.watchUpdateType(isActive, newVal);
    }
  },
  directives: {
    loadmore: {
      inserted(el, binding) {
        const SELECTDOWN_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTDOWN_DOM.addEventListener('scroll', function() {
          const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (CONDITION) {
            binding.value();
          }
        })
      }
    }
  },
  methods: {
    handlerIsActive(newVal){
      const { fixedType } = this.ruleForm;
      this.ruleForm.updateType = this.watchUpdateType(newVal, fixedType);
    },
    validPeriodDateChange(v){
      this.ruleForm.fixedTime=parseTime(fixBeginTime)

    },
    // 设置默认的分组有效期
    defaultDate() {
      let curDate = new Date();
      curDate.setMonth(3 + curDate.getMonth());
      curDate = new Date(+new Date(curDate) - 24 * 60 * 60 * 1000);
      this.ruleForm.effectiveDateTmp = dateformat(curDate, 'yyyy-MM-dd') + ' 23:59:59';
    },
    _groupCount() {
      groupCount().then(res => {
        if (res.errorCode == 0) {
          this.realCount = res.result;
        }
      })
    },
    /**
     * 路由跳转
     */
    changeRoute(route) {
      this.$router.push(route);
    },
    refresh(list) {
      list.changeRefersh = true;
      this.refershList = list;
    },

    // 添加标签
    addTags() {
      this.editPopType = 'add';
      this.showSelectTagPop = true;
    },

    // 编辑标签
    editTags() {
      this.editPopType = 'edit';
      this.showEditTagPop = true;
      this.$nextTick(() => {
        this.tagData = Object.assign({}, this.tagData, this.ruleForm.selectedTags[this.activeTagsGroupIndex][this.activeTagIndex]);
        this.tagData.editCondition = true;
      });
    },

    // 选择标签
    selectedTag(tagData) {
      this.showEditTagPop = true;
      this.tagData = Object.assign({}, this.tagData, tagData);
      this.tagData.editCondition = false;
    },
    // 保存选择的标签数据
    returnTagData(data) {
      let tagParams = JSON.parse(data.tagParams);
      data.newTagVal = JSON.stringify(tagParams.selectedVal);

      data.level = this.activeTagsGroupIndex;

      switch (this.editPopType) {
        case 'add':
          const isHad = this.ruleForm.selectedTags[this.activeTagsGroupIndex].some(item => item.tagId === data.tagId);
          if (isHad) {
            this.ruleForm.selectedTags[this.activeTagsGroupIndex].forEach((tag, tagIndex) => {
              if (tag.tagId === data.tagId) {
                this.ruleForm.selectedTags[this.activeTagsGroupIndex].splice(tagIndex, 1, data);
              }
            });
          } else {
            this.ruleForm.selectedTags[this.activeTagsGroupIndex].push(data);
          }
          break;
        case 'edit':
          // 注意有坑
          let tagsGroup = this.ruleForm.selectedTags[this.activeTagsGroupIndex];
          tagsGroup.splice(this.activeTagIndex, 1, { ...tagsGroup[this.activeTagIndex], ...data });
          this.ruleForm.selectedTags.splice(this.activeTagsGroupIndex, 1, tagsGroup);
          break;
      }
    },

    /**
     * 点击保存
     */
    confirmSavePost() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const { fixedType, fixedTime, effectiveDateTmp } = this.ruleForm;
          const isEmpty = this.ruleForm.selectedTags.length === 0 || this.ruleForm.selectedTags.some(item => item.length === 0);
          if (isEmpty) {
            this.$message.error({ message: '请至少保留一个标签!' });
            return false;
          }
          if (!this.ruleForm.isActive && fixedType && new Date(fixedTime).setHours(0,0,0,0) > new Date(effectiveDateTmp).setHours(0,0,0,0)) {
            this.$message.error({ message: '固化生效时间不能晚于分组有效期' });
            return false;
          }
          this.postSave();
        }
      });
    },

    /**
     * 点击保存---api
     */
    postSave() {
      let ruleForm = this.ruleForm;

      ruleForm.selectedTags.forEach((tagsGroup, tagsGroupIndex) => {
        let relation = ruleForm.tagsGroupRelation[tagsGroupIndex - 1];
        tagsGroup.forEach(item => {
          item.levelType = relation ? relation : 'or';
        });
      });
      const curFixedType = ruleForm.fixedType ? ruleForm.isTogether ? 2 : 1 : 0;
      const para = {
        memberTagGroupId: ruleForm.memberTagGroupId,
        memberTagGroupClassifyId: ruleForm.memberTagGroupClassifyId,
        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`,
        fixedType: curFixedType
      };

      if(para.fixedType) {
        para.fixedTime = this.ruleForm.fixedTime;
      }
      if(para.isRealTime==1&&!this.ruleForm.memberTagGroupId){
        const arr = ruleForm.effectiveDateTmp.split(' ')[0].split('-')
        arr[0] = Number(arr[0])+100;
        para.effectiveDateTmp=`${arr.join('-')} 23:59:59`;
      }
      let postUrl = !!this.ruleForm.memberTagGroupId ? '/member-tag-group/update.json' : '/member-tag-group/add.json';

      postRequest(postUrl, para)
        .then(res => {
          if (res.data.errorCode == 0) {
            showMsg.showmsg(this.ruleForm.memberTagGroupId ? '编辑成功' : '新增成功', 'success');
            this.changeRoute('/memberGroupList');
          }else if(res.data.errorCode == '200009'){
            this.$alert(res.data.message, '提示', {
              confirmButtonText: '知道了',
              type: 'warning',
              customClass: 'addNewGroupClass'
            })
          } else {
            this.$message.warning(res.data.message);
          }
        })
        .catch(error => {
          this.$message.warning(error);
        });
    },

    // 获取标签分类
    getTagsList() {
      getMemberTagCount().then(res => {
        if (res.result && res.result.length) {
          this.tagsList = res.result.map(first => {
            first.nameStr = first.name;
            if (Array.isArray(first.children)) {
              first.children = first.children.map(second => {
                second.nameStr = second.name;
                if (Array.isArray(second.children)) {
                  second.children.map(el => {
                    el.nameStr = el.count > 0 ? `${el.name} (${el.count})`: el.name;
                  })
                }
                return second;
              })
            }
            return first;
          })
        } else {
          this.tagsList = [];
        }
      });
    },
    // 获取一个标签分类下面的标签数据
    getTagsGroupList() {
      const tagType = this.activeTag == 'system' ? 0 : this.activeTag == 'manual' ? 1 : 2;
      console.log(this.searchData, 'this.searchData');
      const params = {
        requestProject: 'gic-member-tag-web',
        search: this.searchData || null, // 模糊查询的标签名
        tagLevelGroupId: this.treeNodeId || 0, // 标签层级
        tagType, // 标签类型 手工标签传1
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        orderType: -1,
        showMemberCount: 1
      };
      getMemberTagList(params).then(res => {
        if (res.result.result && res.result.result.length) {
          this.tagsGroupList = res.result.result;
          this.total = res.result.totalCount;
        } else {
          this.tagsGroupList = [];
          this.total = 0;
        }
      });
    },
    // 搜索标签
    searchTags() {
      this.pageNum = 1;
      this.getTagsGroupList();
    },
    // 点击tree 选择标签组
    treeClick(data, node) {
      this.pageNum = 1;
      this.treeNodeId = data.id;
      this.getTagsGroupList();
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.getTagsGroupList();
    },
    // 页码改变
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getTagsGroupList();
    },
    /**
     * 编辑会员分组的时候时候---获取会员分组数据
     */
    getGroupData() {
      postRequest('/member-tag-group/findOneDetial.json', { memberTagGroupId: this.ruleForm.memberTagGroupId })
        .then(res => {
          const resData = res.data;
          if (resData.errorCode == 0) {
            let tagGroupDto = resData.result.tagGroupDto;
            this.creatorId = tagGroupDto.createUser || '';
            if (!!tagGroupDto) {
              this.ruleForm.memberTagGroupClassifyId = tagGroupDto.memberTagGroupClassifyId || '0';
              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.updateType = 1;
              // this.ruleForm.updateDay = '';
              this.ruleForm.fixedType = +tagGroupDto.fixedType ? 1 : 0
              this.ruleForm.fixedTime = tagGroupDto.fixedTime || this.ruleForm.fixedTime
              this.hasFixed = tagGroupDto.fixedType == 1;
              this.ruleForm.isTogether = tagGroupDto.fixedType == 2 ? true : false
            }

            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);
            this.ruleForm.selectedTags.map((tagsGroup, index) => {
              if (this.ruleForm.selectedTags[index + 1]) {
                this.ruleForm.tagsGroupRelation.push(this.ruleForm.selectedTags[index + 1][0].levelType ? this.ruleForm.selectedTags[index + 1][0].levelType : 'or');
              }
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    onLoadmore() {
      if (this.pager.pageNum >= this.pager.total) return;
      this.pager.pageNum++;
      this.getMemberGroupList();
    },
    getMemberGroupList() {
      if (this.pager.pageNum == 1) {
        this.memberGroupList = [];
      }
      memberGroupList({ requestProject: 'gic-member-tag-web', type: 0, pageSize: 20, pageNum: this.pager.pageNum })
        .then(res => {
          let { errorCode, message, result } = res;
          if (errorCode != 0) {
            this.$message.error(message);
            return;
          }
          if (Array.isArray(result.result)) {
            this.memberGroupList = this.memberGroupList.concat(result.result);
          }
          this.pager.total = result.totalPage;
          this.ruleForm.memberTagGroupClassifyId = this.ruleForm.memberTagGroupClassifyId || '0';
        })
        .catch(err => {
          console.log(err);
        });
    },
    getIsAllowAdd() {
      getIsAllowAdd({ tagGroupId: this.$route.query.memberTagGroupId || undefined }).then(res => {
        res.errorCode == 0 && !res.result && (this.isAllowAdd = res.result);
      })
    },
    updateTypeDesc() {
      const { isActive, fixedType } = this.ruleForm;
      if (isActive && !fixedType) {
        return `(创建成功后更新)`;
      } else if (!isActive && !fixedType) {
        return `(更新时间预计选择日期的0点至9点)`;
      } else if (!isActive && fixedType) {
        return `(更新时间预计固化生效日期的0点至9点)`;
      } else if (isActive && fixedType) {
        return `(创建成功后更新)`;
      }
    },
    watchUpdateType(isActive, fixedType) {
      console.log(isActive, fixedType)
      if (isActive && !fixedType) {
        return 0;
      } else if (!isActive && !fixedType) {
        return 1;
      } else if (!isActive && fixedType) {
        return 2;
      } else if (isActive && fixedType) {
        return 3;
      }
    },
    checkGroup() {
      const params = {
        memberTagGroupIds: this.$route.query.memberTagGroupId,
        operateType: 0,
        requestProject: 'gic-member-tag-web'
      };
      getGroupUseList(params).then(res => {
        const { errorCode, result } = res;
        if (errorCode == 0) {
          this.useList = result || [];
          return;
        }
        errMsg.errorMsg(res.data);
      });
    },
    handleClick() {
      this.treeNodeId = '';
      this.pageNum = 1;
      this.getTagsGroupList();
      this.pageSize = 20;
    },
    // 是否展示系统标签
    getShowSystem() {
      return isShowSystemTag().then(res => {
        this.isShowSystem = res.result;
        if(!res.result) {
          this.activeTag='manual';
        };
      })
    },
  },
  created() {
    if (this.$route.query.type === 'fixed') this.ruleForm.fixedType = 1;
  },
  async mounted() {
    await this.getShowSystem();
    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() + 2 * 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';
    }
    memberTagGroupId && this.checkGroup();
    this.defaultDate();
    this.getTagsList();
    this.getTagsGroupList();
    this.getMemberGroupList();
    this.getIsAllowAdd();
    this._groupCount();
  },
  components: {
    tagsGroupList,
    tagContainer,
    editTag
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-tabs__header {
  margin-bottom: 0;
}
.tabs {
  padding: 14px 24px 0;
}
.m-l-60 {
  margin-left: 60px;
}
.w-460 {
  width: 460px;
}

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

  .effective {
    display: flex;
    align-items: center;
  }
  .label-title {
    font-size: 14px;
    color: #606266;
    color: #303133;
    margin-bottom: 10px;
    line-height: 14px;
  }

  .form-tip-text {
    margin-top: 8px;
    height: 14px;
    line-height: 14px;
    font-size: 14px;
    color: #909399;
  }
  .form-tip-icon {
    margin-left: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 14px;
    height: 14px;
    font-size: 12px;
    color: #909399;
    border: 1px solid #909399;
    border-radius: 14px;
    cursor: pointer;
  }

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

  .textarea-label {
    position: absolute;
    right: 10px;
    top: 126px;
    font-size: 12px;
    color: #909399;
  }
 .alert-title {
    .label {
      color: #303133;
    }
    .tips {
      color: #606266;
    }
    a {
      word-break: break-all;
      color: #2f54eb;
    }
  }
  .group-tips {
    display: flex;
    align-items: flex-start;
    margin-bottom: 25px;
    .desc {
      font-size: 12px;
      color: #606266;
    }
  }
}

.tags {
  margin: 0 24px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  .tags-list {
    padding: 16px 20px 0 0;
    height: 550px;
    width: 220px;
    border-right: 1px solid #dcdfe6;
    overflow-y: scroll;
    .tags-tree {
      width: 100%;
      /deep/ .el-tree-node.is-current > .el-tree-node__content {
        background-color: #EBEFFE;
        color: #2f54eb;
      }
      /deep/ .el-tree-node__content {
        line-height: 32px;
        height: 32px;
        color: #303133;
      }
    }
  }
  .tags-table {
    padding-top: 20px;
    margin-bottom: 20px;
    width: calc(100% - 220px);
    .tags-search {
      margin: 0 0 20px 20px;
      width: 260px;
    }
  }
}
.page-box {
  float: right;
  margin-top: 20px;
  margin-right: 20px;
}
.tip-icon {
  color: #606266;
  font-size: 14px;
}
.radio-group {
  display: flex;
}
.desc-labeltxt {
  padding: 0 10px;
  color: #606266;
  font-size: 12px;
}
.footer {
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 56px;
  left: 232px;
  right: 0;
  background: #FFFFFF;
  box-shadow: 1px -2px 8px 0px rgba(220, 223, 230, 0.6);
}
</style>
