<template>
  <section>
    <el-form inline>
      <el-form-item>
        <el-input placeholder="请输入活码ID/名称、创建人" style="width: 300px" @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" v-loadmore="onLoadmoreStore" @change="searchList" style="margin-left: -4px; width:196px;">
          <el-option v-for="item in shopList" :key="item.storeId" :label="item.storeName" :value="item.storeCode"> </el-option>
        </el-select>
        <el-select v-model="inFields.clerkSelect" v-if="storeSelect == 2" filterable remote placeholder="请输入成员名称/code" :loading="selectLoading" @change="searchList" style="margin-left: -4px; width:196px;">
          <el-option v-for="item in memberList" :key="item.clerkId" :label="item.clerkName" :value="item.clerkCode"> </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="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="tableData" class="act-code-table" @sort-change="sortChange" :max-height="tableMaxHeight">
      <!-- @select="selectTable" :max-height="tableMaxHeight" tooltip-effect="dark"-->
      <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.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="活码状态" 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="添加好友人数" prop="addNum" sortable="custom" width="150">
        <template slot-scope="{ row }">
          <p>{{ row.addNum == null ? row.addNum : '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="今日新增人数" prop="addNumT" sortable="custom" width="150">
        <template slot-scope="{ row }">
          <p>{{ row.addNumT == null ? row.addNumT : '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="使用成员" width="120">
        <template slot-scope="{ row }">
          <p>{{ row.clerkName ? row.clerkName : '--' }}</p>
          <p class="ft-12 phone">{{ row.clerkCode == null ? row.clerkCode : '--' }}</p>
          <p>
            <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">{{ 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="成员所属门店" width="120" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <p>{{ row.storeName ? row.storeName : '--' }}</p>
          <p class="ft-12 phone">{{ row.storeCode == null ? row.storeCode : '--' }}</p>
          <p>
            <el-popover width="200" trigger="click">
              <ul class="userMember-ul">
                <li v-for="item in row.clerkList" :key="item.storeId" class="userMemberLi">
                  <p class="ulName">{{ item.storeName }}</p>
                  <p class="ft-12 phone">{{ 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="所属分组" width="100" show-overflow-tooltip>
        <template slot-scope="{ row }">
          <p>{{ row.hmGroupId == null ? row.hmGroupId : '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="100">
        <template slot-scope="{ row }">
          <p>{{ row.creatorName ? row.creatorName : '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" sortable="custom" width="110">
        <template slot-scope="{ row }">
          <p>{{ row.createTime ? row.createTime : '--' }}</p>
        </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.pageNum" 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="25%">
      <el-form :model="formGroup">
        <el-form-item label="活动区域" :rules="[{ required: true, message: '请选择分组', trigger: 'blur' }]">
          <el-select v-model="formGroup.groupId" placeholder="选择分组" v-loadmore="onLoadmore" remote filterable :remote-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" />
  </section>
</template>

<script>
import { actCodeListApi } from '@/api/actCode.js';
import links from '@/components/common/links';
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.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,
      inFields: {
        // hmId: null,
        hmSelect: '',
        statusFlagInt: '',
        storeSelect: '',
        clerkSelect: '',
        hmTypeInt: '',
        startTime: '',
        endTime: '',
        orderByField: 'createTime desc',
        hmGroupId: 0
      },
      storeSelect: 1,
      dateTime: [],
      tableData: [],
      hmUserMember: [
        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        },

        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        },
        {
          name: 'test'
        }
      ],
      total: 1,
      totalCount: 100,
      selectPage: {
        type: 0,
        dataReady: false
      },
      actCodeList: [],
      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?id=${row.hmId}&activeName=second`);
          }
        },
        {
          text: '详情',
          visible: true,
          handler: row => {
            this.$router.push('/actCodeDetail?hmId=' + row.hmId);
          }
        },
        {
          text: '编辑',
          visible: row => {
            if (row.hmType == 1 && row.statusFlag != 2) {
              return true;
            } else {
              return false;
            }
          },
          handler: row => {
            this.$router.push('/actCodeEdit?hmId=' + row.hmId);
          }
        },
        {
          text: '下载活码',
          visible: row => {
            if (row.hmType == 1 || row.statusFlag != 1) {
              return false;
            } else {
              return true;
            }
          },
          handler: row => {
            this.wxQrcode = row.wxQrcode;
            this.imageName = `${row.hmId}_${row.name}`;
            this.show = true;
          }
        },
        {
          text: '作废',
          visible: row => {
            if (row.statusFlag != 2) {
              return true;
            }
          },
          handler: row => {
            this.$confirm('确认要作废该活码？此操作将永久废弃该活码，请确保不影响其他投放使用!', '作废提示', {
              confirmButtonText: '删除',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              deleteRequest('/haoban-manage3-web/hm/qrcode/del', { hmId: row.hmId }).then(res => {
                if (res.data.code == 0) {
                  this.getTableList();
                }
              });
            });
          }
        }
      ],
      selectLoading: false,
      memberList: [],
      shopList: [],
      // 分页参数
      pageParam: {
        pageSize: 20,
        pageNum: 1
      },
      sortColumn: '',
      sortType: '',
      multipleSelection: [],
      selectHmIds: [],
      dialogGroupFormVisible: false,
      formGroup: {
        groupId: []
      },
      groupList: [],
      pageParamGroup: {
        search: '',
        pageNum: 1,
        pageSize: 20,
        total: 1
      },
      name: '1',
      storeParam: {
        searchParam: '',
        pageSize: 20,
        currentPage: 1,
        scenes: 'integral',
        creatorId: '',
        total: 1
      },
      wxQrcode: '',
      show: false
    };
  },
  created() {
    this.getTableList();
    this.searchGroup();
    this.getStraff();
    this.getStore();
  },
  methods: {
    storeMemberSe(e) {
      if (e == 1) {
        this.inFields.clerkSelect = '';
      } else if (e == 2) {
        this.inFields.storeSelect = '';
      }
    },
    onLoadmoreStore() {
      if (this.storeParam.currentPage >= this.storeParam.total) return;
      this.storeParam.currentPage++;
      this.getStore();
    },
    async getStore() {
      await postRequest(`/api/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 = [];
      }
    },
    // 获取导购列表数据
    async getStraff() {
      await postRequest(`/api/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) {
      if (query !== '') {
        this.pageParamGroup.search = query;
        this.pageParamGroup.pageNum = 1;
        this.groupList = [];
        this.searchGroup();
      } else {
        this.groupList = [];
      }
    },
    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;
      }
    },
    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.pageNum = val;
      this.getTableList();
    },
    // 页码
    handleSizeChange(val) {
      this.pageParam.pageNum = 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();
    },
    searchList() {
      this.pageNum = 1;
      this.getTableList();
    },
    getTableList() {
      this.loadingStatus = true;
      if (this.dateTime && this.dateTime.length) {
        this.inFields.startTime = this.dateTime ? Date.parse(new Date(this.dateTime[0]).toString()) : '';
        this.inFields.endTime = this.dateTime ? Date.parse(new Date(this.dateTime[1]).toString()) : '';
      }
      if (this.currentGroupId != null) {
        this.inFields.hmGroupId = Number(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
      };
      actCodeListApi(obj)
        .then(res => {
          if (res.data.code == 0) {
            this.tableData = res.data.result.data || [];
            this.totalCount = res.data.result.page.totalCount;
          }
        })
        .finally(_ => {
          this.loadingStatus = false;
        });
    }
  },
  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;
}
.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;
    // }
  }
}
</style>
