<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" v-loading="loading" @select="handleSelect" @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-tag size="mini" :type="!row.isRealTime ? 'warning' : ''"> {{ !row.isRealTime ? '非实时' : '实时' }}</el-tag>
          {{ row.groupName }}
        </template>
      </el-table-column>
      <el-table-column label="覆盖人群" prop="memberCount" />
      <el-table-column label="最近更新时间" 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: ''
    },
    effectiveStatus: {
      type: [String, Number],
      default: 1
    },
    maxLimit: {
      type: Number
    },
    readonly: {
      // 只读
      type: Boolean,
      default: false
    },
    name: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      baseUrl,
      loading: false,
      tableData: [],
      totalCount: 0,
      pageSize: 5,
      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) {
        this.$nextTick(() => {
          this.selected.forEach(item => {
            val.forEach(row => {
              if (item.memberTagGroupId == row.memberTagGroupId) {
                // 必须要传入从this.tableData里查询到的对象才能出现被勾选样式
                this.$refs.table.toggleRowSelection(
                  this.tableData.find(row => {
                    return row.memberTagGroupId == item.memberTagGroupId;
                  }),
                  true
                );
              }
            });
          });
        });
      }
    },
    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) {
      if (this.readonly) {
        return false;
      } else if (!this.realTimeType.includes(row.isRealTime)) {
        return false;
      } else {
        return true;
      }
    },
    addGroup() {
      window.open('http://gicdev.demogic.com/member-tag/#/memberGroupEdit?refresh', '_blank');
    },
    selectRow(row) {
      if (this.realTimeType.some(el => el == row.isRealTime)) {
        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=${this.effectiveStatus}`;
      if (this.activeName == '2') {
        url = `${this.baseUrl}/gic-member-tag-web/memberTagGrade/gradeGroupList?requestProject=${this.projectName}&pageSize=${this.pageSize}&pageNum=${this.currentPage}&groupName=${this.dataSearch}`;
      }
      this.axios
        .get(url)
        .then(res => {
          if (res.data.errorCode == 1) {
            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;
  }
}
.pageBtn {
  float: right;
  margin: 13px 0 18px 0;
}
.h-18 {
  line-height: 18px;
}
</style>
