<template>
  <div style="width:100%;">
    <el-form inline>
      <el-form-item>
        <el-input placeholder="请输入活码ID/名称、创建人" style="width: 260px" @change="searchList" v-model="inFields.hmSelect" clearable>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="storeSelect" placeholder="请选择" style="width: 128px" @change="storeMemberSe">
          <el-option label="成员所属门店" :value="1"></el-option>
          <el-option label="关联导购" :value="2"></el-option>
        </el-select>
        <el-select v-model="inFields.storeSelect" v-if="storeSelect == 1" filterable remote placeholder="请输入门店名称/code" :remote-method="remoteMethods" :loading="selectLoading" @change="searchList" style="margin-left: -4px; width:196px;" clearable v-loadmore="onLoadmoreStore" popper-class="s-select" @clear="searchListShop">
          <el-option v-for="item in shopList" :key="item.storeId" :label="item.storeName" :value="item.storeId">
            <p class="sname">{{ item.storeName }}</p>
            <p class="scode">code：{{ item.storeCode }}</p>
          </el-option>
        </el-select>
        <el-select v-model="inFields.clerkSelect" v-if="storeSelect == 2" filterable remote placeholder="请输入成员名称/code" :remote-method="remoteMethodShop" :loading="selectLoading" @change="searchList" style="margin-left: -4px; width:196px;" clearable popper-class="s-select">
          <el-option v-for="item in memberList" :key="item.clerkId" :label="item.clerkName" :value="item.clerkId">
            <p class="sname">{{ item.clerkName }}</p>
            <p class="scode">code：{{ item.clerkCode }}</p>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="inFields.statusFlagInt" 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="inFields.hmTypeInt" placeholder="全部类型" clearable class="w160" @change="searchList">
          <el-option :key="1" label="单人活码" :value="1"> </el-option>
          <el-option :key="2" label="多人活码" :value="2"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="dateTime" @change="searchList" :editable="false" :value-format="'yyyy-MM-dd'" type="daterange" align="right" :picker-options="pickerOptions" range-separator="至" start-placeholder="创建开始日期" end-placeholder="创建结束日期"> </el-date-picker>
      </el-form-item>
      <el-form-item class="frmbt20">
        <el-button @click="batchGoupEvent" v-if="$getButtonLimit($buttonCode.batchGroup)" :limit-code="$buttonCode.batchGroup">批量分组</el-button>
        <el-button type="primary" class="ghost-btn " @click="$router.push('/actCodeBatch')" v-if="$getButtonLimit($buttonCode.batchActCode)" :limit-code="$buttonCode.batchActCode">批量创建活码</el-button>
        <el-button type="primary" @click="$router.push('/actCodeAdd')" v-if="$getButtonLimit($buttonCode.addActCode)" :limit-code="$buttonCode.addActCode">新增活码</el-button>
        <!-- <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="tableData" class="act-code-table" @sort-change="sortChange" :max-height="tableMaxHeight" @selection-change="handleSelectionChange">
      <!-- @select="selectTable"  tooltip-effect="dark"-->
      <el-table-column type="selection" min-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="tableData" :total="totalCount" @change="t => (selectPage.type = t)" @selection-change="handleSelectionChange"></dm-table-select-page>
        </template>
      </el-table-column> -->
      <el-table-column label="活码ID" fixed min-width="110">
        <template slot-scope="{ row }">
          <p>{{ row.hmCode }}</p>
        </template>
      </el-table-column>
      <el-table-column label="活码信息" min-width="120">
        <template slot-scope="{ row }">
          <p class="overflow-ellipsis" :title="row.hmName">{{ row.hmName ? row.hmName : '--' }}</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="活码状态" min-width="110">
        <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.overFlag == 1">(今日已达上限)</p>
        </template>
      </el-table-column>
      <el-table-column label="添加好友人数" prop="addNumT" sortable="custom" min-width="120">
        <template slot-scope="{ row }">
          <p>{{ row.addNumT ? row.addNumT : '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="今日新增人数" prop="addNum" sortable="custom" min-width="120">
        <template slot-scope="{ row }">
          <p>{{ row.addNum ? row.addNum : '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="关联导购" min-width="130" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <p class="overflow-ellipsis">{{ row.clerkList[0] ? row.clerkList[0].clerkName : '--' }}</p>
          <p class="ft-12 phone overflow-ellipsis">{{ row.clerkList[0] ? `code：${row.clerkList[0].clerkCode}` : '--' }}</p>
          <p v-if="row.clerkList && row.clerkList.length > 1">
            <el-popover width="200" trigger="click">
              <ul class="userMember-ul">
                <li v-for="item in row.clerkList" :key="item.clerkId" class="userMemberLi">
                  <p class="ulName">{{ item.clerkName }}</p>
                  <p class="ft-12 phone">code：{{ item.clerkCode }}</p>
                </li>
              </ul>
              <el-button class="ft-12" type="text" slot="reference">查看更多</el-button>
            </el-popover>
          </p>
        </template>
      </el-table-column>
      <el-table-column label="成员所属门店" min-width="150" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <p class="overflow-ellipsis">{{ row.storeList[0] ? row.storeList[0].storeName : '--' }}</p>
          <p class="ft-12 phone overflow-ellipsis">{{ row.storeList[0] ? `code：${row.storeList[0].storeCode}` : '--' }}</p>
          <p v-if="row.storeList && row.storeList.length > 1">
            <el-popover width="200" trigger="click">
              <ul class="userMember-ul">
                <li v-for="item in row.storeList" :key="item.storeId" class="userMemberLi">
                  <p class="ulName">{{ item.storeName }}</p>
                  <p class="ft-12 phone">code：{{ item.storeCode }}</p>
                </li>
              </ul>
              <el-button class="ft-12" type="text" slot="reference">查看更多</el-button>
            </el-popover>
          </p>
        </template>
      </el-table-column>
      <el-table-column label="所属分组" min-width="120" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <p class="overflow-ellipsis">{{ row.hmGroupName ? row.hmGroupName : '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建人" min-width="100" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <p class="overflow-ellipsis">{{ row.creatorName ? row.creatorName : '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" sortable="custom" min-width="110">
        <template slot-scope="{ row }" v-if="row.createTime">
          <div>{{ row.createTime | timeStampToYmd }}</div>
          <div>{{ row.createTime | timeStampToHms }}</div>
        </template>
        <template v-else>--</template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template slot-scope="{ row }">
          <dm-dropdown :scope-data="row" :max="3" :configs="operateBtnArr" />
        </template>
      </el-table-column>
    </el-table>
    <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-size.sync="pageParam.pageSize" :current-page.sync="pageParam.pageNo" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[20, 40, 60, 80]" :total="totalCount"> </el-pagination>
    </div>
    <el-dialog title="选择分组" :visible.sync="dialogGroupFormVisible" width="500px">
      <el-form :model="formGroup">
        <el-form-item label="活码分组" :rules="[{ required: true, message: '请选择分组', trigger: 'blur' }]">
          <el-select class="chooseGroup" v-model="formGroup.groupId" placeholder="选择分组" v-loadmore="onLoadmore" filterable :filter-method="remoteMethod" @visible-change="visibleChange" clearable>
            <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="batchOK">确 定</el-button>
      </div>
    </el-dialog>
    <links :src="wxQrcode" :show.sync="show" :imageName="imageName" :sourceType="false" />
  </div>
</template>

<script>
import { actCodeListApi } from '@/api/actCode.js';
import links from '@/components/common/links';
// import { _debounce } from '@/common/js/public';
import { deleteRequest, getRequest, postRequest, postJsonRequest } from '@/api/api';
export default {
  name: 'actCodeTable',
  components: {
    links
  },
  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.clientHeight + this.scrollTop + 20 >= this.scrollHeight;
          if (CONDITION) {
            binding.value();
          }
        });
      }
    }
  },
  props: {
    currentGroupId: {
      type: [Number, String],
      default: -1
    }
  },
  data() {
    let tableMaxHeight = document.body.clientHeight - 312 + 'px';
    return {
      tableMaxHeight: tableMaxHeight,
      inFields: {
        // hmId: null,
        hmSelect: '',
        statusFlagInt: '',
        storeSelect: '',
        clerkSelect: '',
        hmTypeInt: '',
        startTime: '',
        endTime: '',
        orderByField: 'createTime desc',
        hmGroupId: '-1'
      },
      storeSelect: 1,
      dateTime: [],
      tableData: [],
      total: 1,
      totalCount: 100,
      selectPage: {
        type: 0,
        dataReady: false
      },
      actCodeList: [],
      loadingStatus: false,
      pickerOptions: {
        disabledDate: time => {
          const end = new Date();
          return time.getTime() > end.getTime();
        }
      },
      operateBtnArr: [
        {
          text: '数据',
          visible: row => {
            if (this.$getButtonLimit(this.$buttonCode.dataActCode)) {
              return true;
            }
          },
          props: {
            limitCode: this.$buttonCode.dataActCode
          },
          handler: row => {
            this.$router.push(`/actCodeDetail?hmId=${row.hmId}&activeName=second`);
          }
        },
        {
          text: '详情',
          visible: row => {
            if (this.$getButtonLimit(this.$buttonCode.infoActCode)) {
              return true;
            }
          },
          props: {
            limitCode: this.$buttonCode.infoActCode
          },
          handler: row => {
            this.$router.push('/actCodeDetails?hmId=' + row.hmId);
          }
        },
        {
          text: '编辑',
          visible: row => {
            if (!this.$getButtonLimit(this.$buttonCode.editActCode) || row.statusFlag == 2) {
              return false;
            } else {
              return true;
            }
          },
          props: {
            limitCode: this.$buttonCode.editActCode
          },
          handler: row => {
            this.$router.push('/actCodeEdit?hmId=' + row.hmId);
          }
        },
        {
          text: '下载活码',
          visible: row => {
            if (!this.$getButtonLimit(this.$buttonCode.downActCode) || row.hmType == 1 || row.statusFlag != 1) {
              return false;
            } else {
              return true;
            }
          },
          props: {
            limitCode: this.$buttonCode.downActCode
          },
          handler: row => {
            // this.wxQrcode = row.wxQrcode;
            // this.imageName = `${row.hmId}_${row.hmName}`;
            // this.show = true;
            const downloadFile = (fileName, content) => {
              const url = content;
              const x = new XMLHttpRequest();
              x.open('GET', url, true);
              x.responseType = 'blob';
              x.onload = function(e) {
                const blob = new Blob([x.response]);
                let url = window.URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.href = url;
                a.download = fileName + '.png';
                a.click();
              };
              x.send();
            };
            downloadFile(row.hmCode + '_' + row.hmName, row.wxQrcode);
          }
        },
        {
          text: '作废',
          visible: row => {
            // if (this.$getButtonLimit(this.$buttonCode.delActCode) && row.statusFlag != 2 && row.hmType == 2 && row.clerkCode == '') {
            //   return true;
            // }
            if (this.$getButtonLimit(this.$buttonCode.delActCode) && row.statusFlag != 2) {
              return true;
            }
          },
          props: {
            limitCode: this.$buttonCode.delActCode
          },
          handler: row => {
            this.$confirm('此操作将永久废弃该活码，请确保不影响其他投放使用!', '确认要作废该活码？', {
              confirmButtonText: '作废',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.loadingStatus = true;
              deleteRequest('/haoban-manage3-web/hm/qrcode/del', { hmId: row.hmId }).then(res => {
                if (res.data.code == 0) {
                  setTimeout(() => {
                    this.getTableList();
                    this.loadingStatus = false;
                  }, 1000);
                }
              });
            });
          }
        }
      ],
      selectLoading: false,
      memberList: [],
      shopList: [],
      // 分页参数
      pageParam: {
        pageSize: 20,
        pageNo: 1
      },
      sortColumn: '',
      sortType: '',
      multipleSelection: [],
      selectHmIds: [],
      dialogGroupFormVisible: false,
      formGroup: {
        groupId: []
      },
      groupList: [],
      pageParamGroup: {
        groupName: '',
        pageNum: 1,
        pageSize: 20,
        total: 1
      },
      name: '',
      // 门店
      storeParam: {
        searchParam: '',
        pageSize: 20,
        currentPage: 1,
        scenes: 'integral',
        creatorId: '',
        total: 1
      },
      wxQrcode: '',
      show: false
    };
  },
  created() {
    this.searchGroup();
    this.getTableList();
  },
  activated() {
    this.searchGroup();
    this.getTableList();
  },
  methods: {
    // toInput: _debounce(function(e, value) {
    //   this.getStore();
    // }, 500),
    // toInputs: _debounce(function(e, value) {
    //   this.getStraff();
    // }, 500),
    storeMemberSe(e) {
      if (e == 1) {
        this.inFields.clerkSelect = '';
        this.memberList = [];
      } else if (e == 2) {
        this.inFields.storeSelect = '';
        this.shopList = [];
      }
    },
    onLoadmoreStore() {
      if (this.storeParam.currentPage >= this.storeParam.total) return;
      this.storeParam.currentPage++;
      this.getStore();
    },
    async getStore() {
      await postRequest(`/api-plug/query-store-by-code-name-new?requestProject=haoban-manage-web`, this.storeParam).then(res => {
        if (res.data.errorCode == 0) {
          this.storeParam.total = res.data.totalCount;
          if (Array.isArray(res.data.result.result)) {
            this.shopList = this.shopList.concat(res.data.result.result);
          }
        }
      });
    },
    // 门店远程搜索
    remoteMethods(query) {
      if (query !== '') {
        this.storeParam.searchParam = query;
        this.storeParam.currentPage = 1;
        this.shopList = [];
        this.getStore();
      } else {
        this.shopList = [];
      }
    },
    // 导购
    remoteMethodShop(query) {
      if (query !== '') {
        this.name = query;
        this.memberList = [];
        this.getStraff();
      } else {
        this.memberList = [];
      }
    },
    // 获取导购列表数据
    async getStraff() {
      await postRequest(`/api-plug/search-clerk?type=2`, { name: this.name }).then(res => {
        if (res.data.errorCode == 0) {
          this.memberList = res.data.result || [];
        }
      });
    },
    // 分组加载更多
    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;
          if (Array.isArray(result)) {
            this.groupList = this.groupList.concat(result);
          }
        }
      });
    },
    // 远程搜索
    remoteMethod(query) {
      this.pageParamGroup.groupName = query;
      this.pageParamGroup.pageNum = 1;
      this.groupList = [];
      this.searchGroup();
    },
    visibleChange(e) {
      if (!e) {
        this.remoteMethod();
      }
    },
    // 表格选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.selectHmIds = val.map(item => {
        return item.hmId;
      });
    },
    // 批量分组
    batchGoupEvent() {
      if (this.selectHmIds.length == 0) {
        return this.$message({ message: '请先选择活码', type: 'warning' });
      } else {
        this.dialogGroupFormVisible = true;
        this.searchGroup();
      }
    },
    async batchOK() {
      const obj = {
        hmIds: this.selectHmIds,
        groupId: this.formGroup.groupId
      };
      await postJsonRequest('/haoban-manage3-web/hm/qrcode/update/qrcode/group', obj).then(res => {
        if (res.data.code == 0) {
          this.dialogGroupFormVisible = false;
          this.$router.go(0);
        }
      });
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.pageParam.pageNo = val;
      this.getTableList();
    },
    // 页码
    handleSizeChange(val) {
      this.pageParam.pageNo = 1;
      this.pageParam.pageSize = val;
      this.getTableList();
    },
    // 排序
    sortChange(column) {
      this.sortColumn = column.prop;
      this.sortType = column.order == 'ascending' ? 'asc' : 'desc';
      this.inFields.orderByField = `${this.sortColumn} ${this.sortType}`;
      this.getTableList();
    },
    searchListShop() {
      this.shopList = [];
    },
    searchList(e) {
      this.pageParam.pageNo = 1;
      this.getTableList();
    },
    getTableList() {
      this.loadingStatus = true;
      if (this.dateTime && this.dateTime.length) {
        this.inFields.startTime = this.dateTime ? this.dateTime[0] + ' 00:00:00' : '';
        this.inFields.endTime = this.dateTime ? this.dateTime[1] + ' 23:59:59' : '';
        this.inFields.startTime = Date.parse(new Date(this.inFields.startTime).toString());
        this.inFields.endTime = Date.parse(new Date(this.inFields.endTime).toString());
      } else {
        this.inFields.startTime = '';
        this.inFields.endTime = '';
      }
      if (this.currentGroupId) {
        this.inFields.hmGroupId = this.currentGroupId;
      }
      if (this.inFields.hmSelect == '') {
        delete this.inFields.hmSelect;
      }
      if (this.inFields.storeSelect == '') {
        delete this.inFields.storeSelect;
      }
      if (this.inFields.clerkSelect == '') {
        delete this.inFields.clerkSelect;
      }
      if (this.inFields.startTime == '') {
        delete this.inFields.startTime;
      }
      if (this.inFields.endTime == '') {
        delete this.inFields.endTime;
      }
      const obj = {
        inFields: this.inFields,
        ...this.pageParam
      };
      this.selectPage.dataReady = false;
      actCodeListApi(obj)
        .then(res => {
          if (res.data.code == 0) {
            this.tableData = res.data.result.data || [];
            this.totalCount = res.data.result.page.totalCount;
          }
          this.selectPage.dataReady = true;
        })
        .finally(_ => {
          this.loadingStatus = false;
        });
    }
  },
  watch: {
    currentGroupId: {
      handler: function(val) {
        if (val) {
          this.currentGroupId = val;
          this.pageParam.pageNo = 1;
          this.getTableList();
        }
      },
      immediate: true
    }
  }
};
</script>

<style>
.el-button--text + .el-dropdown {
  margin-left: 15px !important;
}
</style>

<style lang="less" scoped>
.chooseGroup {
  width: 452px;
}
.el-form--inline .el-form-item {
  margin-right: 5px !important;
}

.damolish .el-form-item {
  margin-bottom: 16px !important;
  .frmbt20 {
    margin-bottom: 20px !important;
    margin-right: 0 !important;
    float: right;
    padding-right: 0 !important;
  }
}
.frmbt20 {
  float: right;
}

.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 {
  height: 18px;
  padding: 2px 4px;
  background: #cff2f5;
  border-radius: 2px;
  color: #0faab6;
  font-size: 12px;
}
.moreActCOde {
  height: 18px;
  padding: 2px 4px;
  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;
}
.userMember-ul {
  max-height: 230px;
  overflow: auto;
  li {
    height: 50px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border-bottom: 1px dashed #dcdfe6;
    // .ulName {
    //   font: 14px;
    //   color: #303133;
    // }
  }
}
.s-select {
  width: 196px;
  .el-select-dropdown__item {
    height: 57px;
    padding-top: 9px;
    .sname {
      margin-bottom: 3px;
      line-height: 20px;
      font-size: 14px;
    }
    .scode {
      line-height: 17px;
      font-size: 12px;
    }
  }
}
</style>
