<template>
  <div class="member-group-container">
    <div class="echo-member-group" v-if="echoFlag">
      <div class="mini-sub-title">
        <div class="line"></div>
        <div class="text">
          <div class="space-between">
            已选分组
            <span v-if="!onlyRead"><el-button type="text" class="delBtn" @click="del">删除</el-button><el-button type="text" @click="edit">编辑</el-button></span>
          </div>
        </div>
      </div>
      <div class="echoLine" v-for="item in defaultSelected" :key="item.memberTagGroupId">
        <div class="dot"></div>
        <el-tag size="mini" v-if="item.isRealTime">实时</el-tag>
        <el-tag size="mini" type="warning" v-else>非实时</el-tag>
        <span class="groupName"> {{ item.groupName }}</span>
      </div>
    </div>
    <el-dialog title="选择客户分组" :visible.sync="visiable" width="1000px" :before-close="close" custom-class="member-group-dialog" class="member-group-dialog-wrap">
      <div class="member-group">
        <div class="left">
          <el-tabs v-model="activeName">
            <el-tab-pane :label="item.label" v-for="item in options" :name="item.name" :key="item.name">
              <tableComponent :ref="`table${item.name}`" :name="item.name" :creatorId="creatorId" :key="visiable" :realTimeType="realTimeType" :activeName="activeName" :selected="selectedArray" @handleSelectionChange="handleSelectionChange" @deleteRow="deleteRow" />
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="right">
          <div class="right-top">
            已选分组
          </div>
          <ul class="right-content">
            <li class="contact-li" v-for="item in selectedArray" :key="item.memberTagGroupId">
              <div class="li-cell cursor-pointer">
                <div>
                  <el-tag size="mini" v-if="item.isRealTime">实时</el-tag>
                  <el-tag size="mini" type="warning" v-else>非实时</el-tag>
                  <span class="groupName"> {{ item.groupName }}</span>
                </div>
                <i class="el-icon-close" @click="deleteRow(item)"></i>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { baseUrl } from './index.js';
import table from './table';
export default {
  name: 'gic-new-member-group',
  props: {
    selectedIds: {
      type: String,
      default: ''
    },
    visiable: {
      type: Boolean,
      default: false
    },
    projectName: {
      type: String,
      default: 'memberTag'
    },
    creatorId: {
      type: String,
      default: ''
      // require: true
    },
    maxLimit: {
      type: Number,
      default: 5
    },
    showTabs: {
      // 展示哪些tab
      type: Array,
      default: () => [0, 1, 2]
    },
    realTimeType: {
      // 实时与非实时分组的可选
      // 0：可选非实时分组 1：可选实时分组
      type: Array,
      default: () => [0, 1]
    },
    onlyRead: {
      type: Boolean,
      default: false
    }
  },
  components: {
    tableComponent: table
  },
  data() {
    return {
      activeName: 0, //0 我的客户分组 1固化分组 2金字塔会员分层
      baseUrl,
      echoFlag: false,
      selected: {},
      optionsVal: [
        {
          name: 0,
          label: '我的客户分组'
        },
        {
          name: 1,
          label: '固化分组'
        },
        {
          name: 2,
          label: '金字塔会员分层'
        }
      ],
      options: [
        {
          name: 0,
          label: '我的客户分组'
        },
        {
          name: 1,
          label: '固化分组'
        },
        {
          name: 2,
          label: '金字塔会员分层'
        }
      ]
    };
  },
  mounted() {
    document.addEventListener('visibilitychange', () => {
      if (!document.hidden) {
        try {
          this.$refs[`table${this.activeName}`][0].getGroupList();
        } catch (e) {
          return null;
        }
      }
    });
  },
  computed: {
    selectedArray() {
      let arr = [];
      Object.keys(this.selected).forEach(item => {
        arr.push(this.selected[item]);
      });
      return arr;
    }
  },
  watch: {
    selectedIds: {
      immediate: true,
      handler(val) {
        if (val.length) {
          this.echoFlag = true;
          this.getDefaultSelected(val);
        }
      }
    },
    visiable(val) {
      if (val && this.selectedIds) {
        this.getDefaultSelected(this.selectedIds);
      }
    },
    showTabs: {
      immediate: true,
      handler(val) {
        console.log(val);
        let arr = this.optionsVal;
        if (val && val.length) {
          arr = this.optionsVal.filter(item => val.includes(item.name));
        }
        this.options = arr;
      }
    }
  },
  methods: {
    getDefaultSelected(val) {
      this.axios.get(`${this.baseUrl}/gic-member-tag-web/member-tag-group/queryGroupByIds?requestProject=${this.projectName}&memberTagGroupIds=${val}`).then(res => {
        if (res.data.errorCode == 0) {
          this.defaultSelected = res.data.result;
          this.handleSelectionChange(this.defaultSelected);
        }
      });
    },
    confirm() {
      if (!Object.keys(this.selected).length) {
        this.$message.warning('请选择分组');
        return;
      }
      let arr = [];
      Object.keys(this.selected).forEach(key => {
        arr.push(this.selected[key]);
      });
      const str = arr.map(item => item.memberTagGroupId).join(',');
      if (arr.length) {
        this.echoFlag = true;
      } else {
        this.echoFlag = false;
      }
      this.initPage();
      this.$emit('change', arr, str); // 被选中数组，数组id的字符串
    },
    close() {
      Object.keys(this.selected).forEach(key => {
        this.deleteRow(this.selected[key]);
      });
      this.initPage();
    },
    initPage() {
      this.activeName = '0';
      this.$emit('update:visiable', false);
    },
    del() {
      this.selected = {};
      this.$emit('change', [], '');
      this.echoFlag = false;
    },
    edit() {
      this.$emit('update:visiable', true);
    },
    handleSelectionChange(val) {
      const obj = JSON.parse(JSON.stringify(this.selected));
      if (val.length) {
        val.forEach(item => {
          obj[item.memberTagGroupId] = item;
        });
        if (Object.keys(obj).length > this.maxLimit) {
          this.deleteRow(val[val.length - 1]);
          this.$message.error(`最多支持选择${this.maxLimit}个分组`);
          return false;
        }
      }
      this.selected = obj;
    },
    deleteRow(row) {
      console.log(this.activeName);
      console.log(this.$refs);
      delete this.selected[row.memberTagGroupId];
      this.selected = Object.assign({}, this.selected);
      this.$refs[`table${this.activeName}`][0].$refs.table.toggleRowSelection(row, false);
    }
  }
};
</script>

<style lang="scss" scoped>
.member-group-dialog-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
}
.member-group-dialog {
  margin: 0 !important;
  padding: 0 4px 4px;
  max-height: 700px;
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding-bottom: 0 !important;
  }
  .el-dialog__footer {
    padding: 20px 0;
  }
}
.delBtn {
  color: #f5222d;
}

.space-between {
  display: flex;
  justify-content: space-between;
}
.subTitle {
  width: 100%;
  height: 40px;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  margin-bottom: 5px;
  .line {
    width: 2px;
    height: 14px;
    background: #2f54eb;
    margin-right: 8px;
  }
  .text {
    font-size: 14px;
    color: #303133;
    width: 100%;
  }
}
.member-group-container {
  width: 400px;
}
.echo-member-group {
  width: 100%;
  background: #f7f8fa;
  border-radius: 4px;
  padding: 0 16px 16px;
  box-sizing: border-box;
  .echoLine {
    margin-bottom: 8px;
    line-height: 20px;
    .dot {
      display: inline-block;
      width: 6px;
      height: 6px;
      background: #2f54eb;
      border-radius: 3px;
      margin-right: 6px;
    }
    .groupName {
      font-weight: 400;
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}
.member-group {
  background: #ffffff;
  display: flex;
  .left {
    width: 666px;
    height: 560px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    padding: 5px 17px;
    box-sizing: border-box;
    /deep/ .el-table th.el-table__cell {
      line-height: 1;
    }
  }

  .right {
    width: 274px;
    // height: 582px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    margin-left: 12px;

    .right-top {
      padding: 20px 15px;
      display: flex;
      justify-content: space-between;
      color: #303133;
      box-sizing: border-box;
      line-height: 20px;
      background: #fff;
    }
    .right-content {
      color: #303133;
      overflow-y: auto;
      height: 89%;
    }
    .contact-li {
      padding: 0 12px 0 16px;
      margin-top: 4px;
      &:hover {
        background: #f7f8fa;
      }
      &:first-child {
        margin-top: 0;
      }
      .li-cell {
        border-radius: 2px;
        line-height: 32px;
        display: inline-flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
        box-sizing: border-box;

        i {
          width: 20px;
          height: 20px;
          border-radius: 10px;
          cursor: pointer;
          font-size: 12px;
          display: inline-flex;
          justify-content: center;
          align-items: center;
          &:hover {
            background: #e5e6eb;
          }
        }
      }
    }
    .contact-li + .contact-li {
      margin-top: 4px;
    }
  }
}
</style>
