<template>
  <div>
    <div class="leftHead">
      <div class="tips">
        <li><span class="dots"></span> 选择多个分组时，会自动去重分组下的客户；</li>
        <li><span class="dots"></span> 非实时分组到期后，客户数据会清空，任务将不在继续执行；</li>
      </div>
      <div class="searchWrap">
        <div><el-input prefix-icon="el-icon-search" v-model="dataSearch" placeholder="请输入分组名称" @keyup.enter.native="search" clearable @clear="search"></el-input></div>
        <div class="btn"><el-button size="small" type="primary" @click="addGroup">新增分组</el-button></div>
      </div>
    </div>
    <el-table :data="tableData" ref="table" style="width:100%" v-loading="loading" @select="handleSelect" height="355px" @selection-change="handleSelectionChange" row-key="memberTagGroupId" @row-click="selectRow">
      <el-table-column type="selection" width="55" :selectable="selectable"> </el-table-column>
      <el-table-column label="分组名称" min-width="180px" prop="groupName">
        <template slot-scope="{ row }">
          <el-tooltip :disabled="row.readyStatus == 1" content="当前分组还未更新完成">
            <div>
              <el-tag size="mini" v-show="activeName != 2" :type="!row.isRealTime ? 'warning' : ''"> {{ !row.isRealTime ? '非实时' : '实时' }}</el-tag>
              {{ row.groupName }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="最近更新时间" v-if="activeName != 2" min-width="120px" prop="latestUpdateTime">
        <template slot-scope="scope">
          <p class="h-18">{{ scope.row.latestUpdateTime | formatTimeYMD }}</p>
          <p class="h-18">{{ scope.row.latestUpdateTime | formatTimeHMS }}</p>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" v-if="activeName != 2" min-width="120px" prop="recentUpdateDate">
        <template slot-scope="scope">
          <p class="h-18">{{ scope.row.recentUpdateDate | formatTimeYMD }}</p>
          <p class="h-18">{{ scope.row.recentUpdateDate | formatTimeHMS }}</p>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageBtn">
      <el-pagination layout="prev, pager, next" v-if="totalCount" :total="totalCount" :page-size="pageSize" :current-page.sync="currentPage" @current-change="getGroupList"> </el-pagination>
    </div>
  </div>
</template>

<script>
import { baseUrl } from './index.js';
export default {
  props: {
    realTimeType: {
      type: Array,
      default: () => [0, 1]
    },
    selected: {
      type: Array,
      default: () => []
    },
    activeName: {
      type: String,
      default: ''
    },
    projectName: {
      type: String,
      default: 'memberTag'
    },
    creatorId: {
      type: String,
      default: ''
    },
    maxLimit: {
      type: Number
    },
    name: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      baseUrl,
      loading: false,
      tableData: [],
      totalCount: 0,
      pageSize: 20,
      currentPage: 1,
      dataSearch: '',
      fixedType: 0 // 0普通的分组，  1固化分组  3固化分组分堆
    };
  },
  filters: {
    formatTimeYMD(data) {
      return data && data != '- -' ? String(data).split(' ')[0] : '--';
    },
    formatTimeHMS(data) {
      return data && data != '- -' ? String(data).split(' ')[1] : '--';
    }
  },
  mounted() {
    console.log('mounted');
  },
  watch: {
    tableData(val) {
      if (!val.length) return;
      this.$nextTick(() => {
        if (!this.selected.length) return;
        const obj = {};
        val.forEach(item => {
          obj[item.memberTagGroupId] = item;
        });
        this.selected.forEach(item => {
          obj[item.memberTagGroupId] && this.$refs.table.toggleRowSelection(obj[item.memberTagGroupId]);
        });
      });
    },
    activeName: {
      handler(val) {
        if (val == '0' && this.name == '0') {
          this.fixedType = 0;
          this.getGroupList();
        } else if (val == '1' && this.name == '1') {
          this.fixedType = 1;
          this.getGroupList();
        } else if (val == '2' && this.name == '2') {
          this.getGroupList();
        }
      },
      immediate: true
    }
  },
  methods: {
    selectable(row) {
      return row.readyStatus == 1 && this.realTimeType.includes(row.isRealTime);
    },
    addGroup() {
      let str = window.location.host.includes('localhost') ? 'http://gicdev.demogic.com' : '';
      window.open(`${str}/member-tag/#/memberGroupEdit?refresh`, '_blank');
    },
    selectRow(row) {
      if (this.realTimeType.some(el => el == row.isRealTime) && row.readyStatus == 1) {
        if (this.selected.length && this.selected.find(item => item.memberTagGroupId == row.memberTagGroupId)) {
          this.$emit('deleteRow', row);
        } else {
          this.$refs.table.toggleRowSelection(row);
        }
      }
    },
    handleSelectionChange(val) {
      if (val.length) {
        this.$emit('handleSelectionChange', val);
      }
    },
    handleSelect(selection, row) {
      if (this.selected.length && this.selected.find(item => item.memberTagGroupId == row.memberTagGroupId)) {
        this.$emit('deleteRow', row);
      }
    },
    search() {
      this.currentPage = 1;
      this.getGroupList();
    },
    /**
     * 获取 列表数据
     */
    getGroupList() {
      this.loading = true;
      this.tableData = [];
      this.totalCount = 0;
      let url = `${this.baseUrl}/gic-member-tag-web/member-tag-group/findList.json?requestProject=${this.projectName}&fixedType=${this.fixedType}&creatorId=${this.creatorId}&pageSize=${this.pageSize}&pageNum=${this.currentPage}&groupName=${this.dataSearch}&effectiveStatus=1&permissionType=1`;
      if (this.activeName == '2') {
        url = `${this.baseUrl}/gic-member-tag-web/memberTagGrade/gradeGroupListV2?requestProject=${this.projectName}&pageSize=${this.pageSize}&pageNum=${this.currentPage}&groupName=${this.dataSearch}`;
      }
      this.axios
        .get(url)
        .then(res => {
          if (res.data.errorCode == 1) {
            res.data.result.result.forEach(item => (item.activeName = this.activeName));
            this.tableData = res.data.result.result;
            this.totalCount = res.data.result.totalCount;
            return;
          }
          this.$message.error({
            duration: 2000,
            message: res.data.message
          });
        })
        .catch(error => {
          this.$message.error({
            duration: 2000,
            message: error.message
          });
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.leftHead {
  .tips {
    padding-bottom: 15px;
    li {
      display: flex;
      align-items: center;
      line-height: 17px;
      &:last-child {
        margin-top: 4px;
      }
    }
    .dots {
      width: 5px;
      height: 5px;
      background: #c4c6cf;
      display: inline-block;
      border-radius: 2.5px;
      margin-right: 6px;
    }
  }
  .searchWrap {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    /deep/ .el-input__inner {
      border-color: #dcdfe6 !important;
    }
  }
}
.pageBtn {
  float: right;
  margin-top: 5px;
}
.h-18 {
  line-height: 18px;
}
/deep/ .el-table__header .el-checkbox {
  display: none;
}
</style>
