<template>
  <section>
    <el-form inline>
      <el-form-item>
        <el-input placeholder="请输入活码ID/名称、创建人" style="width: 300px" @change="searchList" v-model="searchForm.keyword">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.storeSearch" placeholder="请选择" style="width: 128px" @change="searchList">
          <el-option label="成员所属门店" :value="1"></el-option>
          <el-option label="使用成员" :value="2"></el-option>
        </el-select>
        <el-select v-model="searchForm.searchInfo" filterable remote :placeholder="`请输入${searchForm.storeSearch == 1 ? '门店名称' : '成员姓名'} / code`" :remote-method="remoteMethods" :loading="selectLoading" @change="searchList" style="margin-left: -4px; width:196px;">
          <el-option v-for="item in memberOrShopList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.statusFlag" placeholder="全部状态" clearable class="w160" @change="searchList">
          <el-option :key="0" label="删除" :value="0"> </el-option>
          <el-option :key="1" label="正常" :value="1"> </el-option>
          <el-option :key="2" label="作废" :value="2"> </el-option>
          <el-option :key="3" label="待生效" :value="3"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.hmType" placeholder="全部类型" clearable class="w160" @change="searchList">
          <el-option :key="0" label="单人活码" :value="0"> </el-option>
          <el-option :key="1" label="多人活码" :value="1"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="dateTime" @change="searchList" :picker-options="pickerOptions" :editable="false" :value-format="'yyyy-MM-dd HH:mm:ss'" type="datetimerange" align="right" unlink-panels range-separator="至" start-placeholder="创建开始日期" end-placeholder="创建结束日期"> </el-date-picker>
      </el-form-item>
      <el-form-item class="frmbt20">
        <el-button @click="batchGoupEvent">批量分组</el-button>
        <el-button class="ghost-btn " @click="$router.push('/actCodeBatch')">批量创建活码</el-button>
        <el-button type="primary" @click="$router.push('/actCodeAdd')">新增活码</el-button>
      </el-form-item>
    </el-form>
    <el-table ref="actCodeTableRef" v-loading="loadingStatus" :data="actCodeList" tooltip-effect="dark" class="act-code-table" @sort-change="sortChange" :max-height="tableMaxHeight" @select="selectTable">
      <el-table-column type="selection" width="60" fixed> </el-table-column>
      <el-table-column width="60" class-name="table-select-cell" fixed>
        <template #header>
          <dm-table-select-page class="table-select" :type="selectPage.type" :data-ready="selectPage.dataReady" :table-vm="$refs.actCodeTableRef" :table-data="actCodeList" :total="totalCount" @change="t => (selectPage.type = t)" @selection-change="handleSelectionChange"></dm-table-select-page>
        </template>
      </el-table-column>
      <el-table-column label="活码ID" fixed width="110">
        <template slot-scope="{ row }">
          <p>{{ row.hmId }}</p>
        </template>
      </el-table-column>
      <el-table-column label="活码信息" width="100">
        <template slot-scope="{ row }">
          <p class="overflow-ellipsis" :title="row.hmId">{{ row.hmId }}</p>
          <p><span class="oneActCode" v-if="row.hmType == 1">单人活码</span><span class="moreActCOde" v-else>多人活码</span></p>
        </template>
      </el-table-column>
      <el-table-column label="活码状态" width="130">
        <template slot-scope="{ row }">
          <p><span class="dot normal" v-if="row.statusFlag == 1">正常</span><span class="dot voided" v-if="row.statusFlag == 2">作废</span><span class="dot needSure" v-if="row.statusFlag == 3">待生效</span></p>
          <p class="toTopTip" v-if="row.statusFlag == 1">(今日已达上限)</p>
        </template>
      </el-table-column>
      <el-table-column label="添加好友人数" sortable="custom" width="150">
        <template slot-scope="{ row }">
          <p>{{ row.hmId }}</p>
        </template>
      </el-table-column>
      <el-table-column label="今日新增人数" sortable="custom" width="150">
        <template slot-scope="{ row }">
          <p>{{ row.hmId }}</p>
        </template>
      </el-table-column>
      <el-table-column label="使用成员" width="120">
        <template slot-scope="{ row }">
          <p>{{ row.useMember[0].name }}</p>
          <p class="ft-12 phone">15784243524</p>
          <p>
            <el-popover width="200" trigger="click">
              <ul class="useMember-ul">
                <li v-for="(item, index) in row.useMember.slice(1)" :key="index">
                  <p>{{ item.name }}</p>
                  <p class="ft-12 phone">15784243524</p>
                </li>
              </ul>
              <el-button slot="reference" type="text" class="ft-12">查看更多</el-button>
            </el-popover>
          </p>
        </template>
      </el-table-column>
      <el-table-column label="成员所属门店" width="120">
        <template slot-scope="{ row }">
          <p>{{ row.useMember[0].name }}</p>
          <p class="ft-12 phone">15784243524</p>
          <p>
            <el-popover width="200" trigger="click">
              <ul class="useMember-ul">
                <li v-for="(item, index) in row.useMember.slice(1)" :key="index">
                  <p>{{ item.name }}</p>
                  <p class="ft-12 phone">15784243524</p>
                </li>
              </ul>
              <el-button slot="reference" type="text" class="ft-12">查看更多</el-button>
            </el-popover>
          </p>
        </template>
      </el-table-column>
      <el-table-column label="所属分组" width="100">
        <template slot-scope="{ row }">
          <p>{{ row.hmId }}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="100">
        <template slot-scope="{ row }">
          <p>{{ row.creatorName }}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" sortable="custom" width="120">
        <template slot-scope="{ row }">
          <p>{{ row.createTime }}</p>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template slot-scope="{ row }">
          <dm-dropdown :scope-data="row" :configs="operateBtnArr" :max="5" @command="onCommand" />
        </template>
      </el-table-column>
    </el-table>
    <div class="block common-wrap__page text-right m-t-24" v-if="actCodeList.length != 0">
      <dm-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageParam.pageNum" :page-sizes="[20, 40, 60, 80]" :page-size="pageParam.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"> </dm-pagination>
    </div>
    <el-dialog title="选择分组" :visible.sync="dialogGroupFormVisible" width="25%">
      <el-form :model="formGroup">
        <el-form-item label="活动区域" :rules="[{ required: true, message: '请选择分组', trigger: 'blur' }]">
          <el-select v-model="formGroup.groupList" placeholder="选择分组" v-loadmore="onLoadmore" remote multiple filterable :remote-method="remoteMethod" @visible-change="visibleChange">
            <el-option v-for="item in groupList" :key="item.groupId" :label="item.groupName" :value="item.groupId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogGroupFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogGroupFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { actCodeListApi } from '@/api/actCode.js';
// import errMsg from '@/common/js/error';
import { deleteRequest, getRequest } from '@/api/api';
export default {
  name: 'actCodeTable',
  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();
          }
        });
      }
    }
  },
  props: {
    currentGroupId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    let tableMaxHeight = document.body.clientHeight - 312 + 'px';
    return {
      tableMaxHeight: tableMaxHeight,
      searchForm: {
        keyword: '',
        // searchInfo: '',
        statusFlag: '',
        storeSearch: 1,
        hmType: '',
        createTimeStart: '',
        createTimeEnd: ''
      },

      dateTime: [],
      tableData: [],
      total: 1,
      totalCount: 100,
      selectPage: {
        type: 0,
        dataReady: false
      },
      actCodeList: [
        {
          hmId: 1,
          hmType: 1,
          statusFlag: 1,
          useMember: [
            {
              name: 'text'
            },
            {
              name: 'text'
            }
          ]
        },
        {
          hmId: 123132132222222222222,
          hmType: 1,
          statusFlag: 2,
          useMember: [
            {
              name: 'text'
            },
            {
              name: 'text'
            }
          ]
        },
        {
          hmId: 12313213,
          statusFlag: 3,
          useMember: [
            {
              name: 'text'
            },
            {
              name: 'text'
            }
          ]
        },
        {
          hmId: 12313213,
          hmType: 1,
          statusFlag: 1,
          useMember: [
            {
              name: 'text'
            },
            {
              name: 'text'
            }
          ]
        },
        {
          hmId: 12313213,
          statusFlag: 2,
          useMember: [
            {
              name: 'text'
            },
            {
              name: 'text'
            },
            {
              name: 'text'
            },
            {
              name: 'text'
            }
          ]
        },
        {
          hmId: 12313213,
          statusFlag: 2,
          useMember: [
            {
              name: 'text'
            },
            {
              name: 'text'
            },
            {
              name: 'text'
            },
            {
              name: 'text'
            }
          ]
        },
        {
          hmId: 12313213,
          statusFlag: 2,
          useMember: [
            {
              name: 'text'
            },
            {
              name: 'text'
            },
            {
              name: 'text'
            },
            {
              name: 'text'
            }
          ]
        }
      ],
      loadingStatus: false,
      pickerOptions: {
        disabledDate: time => {
          const end = new Date();
          return time.getTime() < end.getTime() - 3600 * 1000 * 24 * 365 || time.getTime() > end.getTime() - 3600 * 1000 * 24;
        }
      },
      operateBtnArr: [
        {
          text: '数据',
          visible: true,
          handler: row => {
            this.$router.push(`/actCodeDetail?hmId=${row.hmId}`);
          }
        },
        {
          text: '详情',
          visible: true,
          handler: row => {
            this.$router.push(`/actCodeDetail?hmId=${row.hmId}`);
          }
        },
        {
          text: '编辑',
          visible: true,
          handler: row => {
            console.log(row, 77);
            this.$router.push(`/actCodeEdit?hmId=${row.hmId}`);
          }
        },
        {
          text: '下载活码',
          visible: true,
          handler: row => {
            console.log(row);
          }
        },
        {
          text: '作废',
          visible: true,
          handler: row => {
            this.$confirm('确认要作废该活码？此操作将永久废弃该活码，请确保不影响其他投放使用!', '作废提示', {
              confirmButtonText: '删除',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              deleteRequest('/hm/qrcode/del', { hmId: row.hmId }).then(res => {});
            });
          }
        }
      ],
      selectLoading: false,
      memberOrShopList: [
        {
          value: 1,
          label: '测试1'
        },
        {
          value: 2,
          label: '测试2'
        }
      ],
      // 分页参数
      pageParam: {
        pageSize: 20,
        pageNum: 1
      },
      sortColumn: '',
      sortType: '',
      multipleSelection: [],
      selectHmIds: [],
      dialogGroupFormVisible: false,
      formGroup: {
        groupList: []
      },
      groupList: [],
      pageParamGroup: {
        search: '',
        pageNum: 1,
        pageSize: 20,
        total: 1
      }
    };
  },
  created() {
    this.getTableList();
    this.searchGroup();
  },
  methods: {
    onLoadmore() {
      if (this.pageParamGroup.pageNum >= this.pageParamGroup.total) return;
      this.pageParamGroup.pageNum++;
      this.searchGroup();
    },
    async searchGroup() {
      if (this.pageParamGroup.pageNum == 1) {
        this.groupList = [];
      }
      await getRequest('/haoban-manage3-web/hm/group/list', this.pageParamGroup).then(res => {
        if (res.data.code == 0) {
          const { result, pages } = res.data.result || {};
          this.pageParamGroup.total = pages;
          // console.log(this.groupList, 'list');
          if (Array.isArray(result)) {
            this.groupList = this.groupList.concat(result);
          }
        }
      });
    },
    // 远程搜索
    remoteMethod(query) {
      if (query !== '') {
        this.pageParamGroup.search = query;
        this.pageParamGroup.pageNum = 1;
        this.groupList = [];
        this.searchGroup();
      } else {
        this.groupList = [];
      }
    },
    visibleChange(e) {
      if (!e) {
        this.remoteMethod();
      }
    },
    // 表格选中事件
    selectTable(selection, row) {
      console.log(selection);
      this.selectHmIds = selection.map(item => {
        return item.hmId;
      });
      console.log(this.selectHmIds, 'iss');
    },
    // 批量分组
    batchGoupEvent() {
      console.log('批量分组');
      this.dialogGroupFormVisible = true;
    },
    onCommand() {
      console.log('hello');
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.pageParam.pageNum = val;
      this.getTableList();
    },
    // 页码
    handleSizeChange(val) {
      this.pageParam.pageNum = 1;
      this.pageParam.pageSize = val;
      this.getTableList();
    },
    remoteMethods(query) {
      console.log(query);
    },
    // 排序
    sortChange(column) {
      // this.pageParam.sortColName = column.prop;
      // if (column.order === 'descending') {
      //   this.pageParam.sortType = 'desc';
      // }
      // if (column.order === 'ascending') {
      //   this.pageParam.sortType = 'asc';
      // }
      const that = this;
      that.sortColumn = column.prop;
      that.sortType = column.order == 'ascending' ? 'asc' : 'desc';
      this.getTableList();
    },
    searchList() {
      this.pageNum = 1;
      this.getTableList();
    },
    getTableList() {
      this.loadingStatus = true;
      if (this.dateTime && this.dateTime.length) {
        this.searchForm.createTimeStart = this.dateTime ? Date.parse(new Date(this.dateTime[0]).toString()) : '';
        this.searchForm.createTimeEnd = this.dateTime ? Date.parse(new Date(this.dateTime[1]).toString()) : '';
      }
      this.searchForm = {
        ...this.searchForm
      };
      if (this.currentGroupId != null) {
        this.searchForm = {
          ...this.searchForm,
          hmGroupId: this.currentGroupId
        };
      }
      // delete this.searchForm.dateTime;
      actCodeListApi(Object.assign({}, this.searchForm, this.pageParam))
        .then(res => {
          // this.totalCount = res.data.result.totalCount || 0;
          // if (res.data.result.result.length && Array.isArray(res.data.result.result)) {
          //   this.tableData = [].concat(res.data.result.result);
          // } else {
          //   this.tableData = [];
          // }
        })
        .finally(_ => {
          this.loadingStatus = false;
        });
    }

    // discardCode(id) {
    // const that = this;
    // that.loading = true;
    // const aa = deleteRequest('/hm/qrcode/del', { hmId: id });
    // return console.log(aa, 'aa');
    // .then(res => {
    //   let resData = res.data;
    //   that.loading = false;
    //   if (resData.errorCode == 1) {
    //     that.getActCodeInfo();
    //     return;
    //   }
    //   errMsg.errorMsg(resData);
    // })
    // .cash(function(error) {
    //   that.$message.error({
    //     duration: 1000,
    //     message: error.message
    //   });
    // });
    // }
  },
  watch: {
    currentGroupId: {
      handler: function(val) {
        if (val != null) {
          this.currentGroupId = val;
          this.pageParam.pageNum = 1;
          this.getTableList();
        }
      },
      immediate: true
    }
  }
};
</script>

<style lang="less" scoped>
.frmbt20 {
  margin-bottom: 20px !important;
  margin-right: 0 !important;
  float: right;
  padding-right: 0 !important;
}
.ml10 {
  margin-left: 10px;
}
.w160 {
  width: 160px;
}
.act-code-table {
  width: 100%;
  max-height: calc(100vh - 312px);
}
.act-code-table /deep/ .table-select-cell .cell {
  padding: 0;
}
.act-code-table /deep/ .table-select-cell .cell .el-dropdown {
  padding: 0;
}
.table-select {
  display: block;
  line-height: 1;
}
.act-code-table /deep/ td:not(.table-header__dropdown) .cell:empty::before {
  content: '' !important;
}
.oneActCode {
  background: #cff2f5;
  border-radius: 2px;
  color: #0faab6;
  font-size: 12px;
}
.moreActCOde {
  background: #dee3fc;
  border-radius: 2px;
  color: #2f54eb;
  font-size: 12px;
}
.toTopTip {
  color: #fa8c16;
  font-size: 12px;
}
.dot {
  display: inline-block;
  position: relative;
  margin-left: 14px;
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: -14px;
    transform: translateY(-50%);
    display: block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
  }
}

.voided::before {
  background: #d9d9d9;
}
.normal::before {
  background: #33af4a;
}
.needSure::before {
  background: #fa8c16;
}
.ft-12 {
  font-size: 12px;
}
.phone {
  color: #606266;
}
.useMember-ul {
  max-height: 230px;
  overflow: auto;
  li {
    height: 50px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border-bottom: 1px solid #dcdfe6;
  }
}
</style>
