<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.memberName" clearable class="filter-item" style="width: 200px" placeholder="请输入兑换码名称" />
      <el-select v-model="listQuery.refereeId" clearable style="width: 200px" class="filter-item" placeholder="请选择引荐人">
        <el-option v-for="item in refereeList" :key="item.refereeId" :label="item.refereeName" :value="item.refereeId" />
      </el-select>
      <el-select v-model="listQuery.isExchange" clearable style="width: 200px" class="filter-item" placeholder="是否已兑换">
        <el-option label="是" :value="true" />
        <el-option label="否" :value="false" />
      </el-select>
      <el-date-picker v-model="listQuery.timeArray" type="datetimerange" class="filter-item" range-separator="至" start-placeholder="生成开始日期" end-placeholder="生成结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd hh:mm:ss" />

      <el-button v-permission="['GET /admin/memberCoupon/listcard']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/memberCoupon/createMemberCard']" class="filter-item" type="primary" icon="el-icon-edit" @click="clickaddmember">生成会员卡</el-button>
      <el-button v-permission="['POST /admin/memberCoupon/memberCardExport']" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="生成批次" prop="batchNo" />

      <el-table-column align="center" label="兑换码名称" prop="memberName" />

      <el-table-column align="center" label="兑换码" prop="memberCode" />
      <el-table-column align="center" label="兑换码类型" prop="memberType">
        <template slot-scope="scope">
          <span v-if="scope.row.memberType==1">月卡</span>
          <span v-if="scope.row.memberType==2">年卡</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="兑换期限">
        <template slot-scope="scope">
          <span>
            {{scope.row.startTime}}至
            <br />
            {{scope.row.endTime}}
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否已兑换">
        <template slot-scope="scope">
          <span v-if="scope.row.isExchange==true">已兑换</span>
          <span v-if="scope.row.isExchange==false">未兑换</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否已领取">
        <template slot-scope="scope">
          <span>{{scope.row.refereeId==undefined||scope.row.refereeId==''?'未领取':'已领取'}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="所属渠道" prop="channel">
                <template slot-scope="scope">
                    <span>{{ scope.row.channelId | channelsFilter }}</span>
                </template>
      </el-table-column>-->
      <el-table-column align="center" label="领取人" prop="refereeId">
        <template slot-scope="scope">
          <span>{{ scope.row.refereeId | refereeIdFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="领取时间" prop="assignedTime" />
      <el-table-column align="center" label="生成时间" prop="createTime" />

      <el-table-column align="center" label="操作" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/memberCoupon/batchNoAssigned']" type="primary" size="mini" @click="handleAssignMember(scope.row)" v-if="scope.row.refereeId==undefined||scope.row.refereeId==''">批量领取会员卡</el-button>
          <!-- <el-button v-permission="['POST /admin/memberCoupon/deleteBatchNo']" type="danger" size="small" @click="handleDeleteBatch(scope.row)">删除同批次</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!---添加会员卡--->
    <el-dialog :visible.sync="showadd" title="添加会员卡" width="1000px" :show-close="false" :close-on-click-modal="false" center>
      <el-form ref="addform" :model="addform" :rules="addformRule" status-icon label-position="left" label-width="150px">
        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="会员卡名称" prop="memberName">
              <el-input v-model="addform.memberName" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员卡类型" prop="memberType">
              <el-select v-model="addform.memberType" class="filter-item" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in memberTypeArr" :key="item.type" :label="item.val" :value="item.type" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label-width="150px" label="卡券包有效期-开始" prop="startTime">
              <el-date-picker :picker-options="pickerOptions" v-model="addform.startTime" type="datetime" placeholder="选择开始日期" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="150px" label="卡券包有效期-结束" prop="endTime">
              <el-date-picker :picker-options="pickerOptions" v-model="addform.endTime" type="datetime" placeholder="选择结束日期" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="会员卡数量" prop="number">
              <el-input v-model.number="addform.number" clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
                        <el-form-item label="所属渠道" prop="channel">
                            <el-select v-model="addform.channelId" clearable class="filter-item" placeholder="请选择渠道" style="width: 100%">
                                <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item>
          </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="canceladd">取消</el-button>
        <el-button type="primary" @click="saveMember('addform')">保存</el-button>
      </div>
    </el-dialog>

    <!---领取会员卡--->
    <el-dialog :visible.sync="showAssign" title="批量领取会员卡" width="600px" :show-close="false" :close-on-click-modal="false" center>
      <el-form ref="assignForm" :model="assignForm" :rules="assignFormRule" status-icon label-position="left" label-width="150px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="引荐人" prop="refereeId">
              <el-select v-model="assignForm.refereeId" clearable style="width: 300px" class="filter-item" placeholder="请选择引荐人">
                <el-option v-for="item in refereeList" :key="item.refereeId" :label="item.refereeName" :value="item.refereeId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAssign=false">取消</el-button>
        <el-button type="primary" @click="saveAssign('assignForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
 
<script>
import {
  listCardMember,
  createMemberCard,
  batchNoAssigned,
  deleteBatchNo,
  memberCardExport,
} from "@/api/member";
import { refereeRoots } from "@/api/referee";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

import formatDate from "@/utils/date";
let vm;

export default {
  name: "Coupon",
  components: { Pagination },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      showadd: false,
      memberTypeArr: [
        { type: 1, val: "月卡" },
        { type: 2, val: "年卡" },
      ],
      list: [],
      refereeList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        memberName: "",
        refereeId: "",
        isExchange: "",
      },
      showAssign: false,
      batchNo: "",
      assignForm: {
        refereeId: "",
      },
      assignFormRule: {
        refereeId: [
          {
            required: true,
            message: "引荐人不能为空",
            trigger: "blur",
          },
        ],
      },
      addform: {
        number: 0, //份数
        memberName: "",
        memberType: 1,
        startTime: "",
        endTime: "",
        // channelId: "",
      },
      addformRule: {
        number: [{required: true,message: "会员卡数量不能为空",trigger: "blur",},        ],
        memberName: [{required: true,message: "会员卡名称不能为空",trigger: "blur",},],
        memberType: [{required: true,message: "请选择会员卡类型",trigger: "blur",},],
        startTime: [{required: true,message: "会员卡有效期不能为空",trigger: "blur",},],
        endTime: [{required: true,message: "会员卡有效期不能为空",trigger: "blur",},],
      },
    };
  },
  created() {
    this.getList();
    refereeRoots().then((res) => {
      this.refereeList = res.data.data;
    });
  },
  methods: {
    handleAssignMember(row) {
      this.showAssign = true;
      this.batchNo = row.batchNo;
    },
    handleDeleteBatch(row) {
      this.$confirm("是否删除批次号为:" + row.batchNo + " 的兑换码?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteBatchNo({ batchNo: row.batchNo }).then((res) => {
          if (res.data.errno == 0) {
            this.$message.success("删除成功");
            this.getList();
          } else {
            this.$message.error("删除失败");
          }
        });
      });
    },
    saveAssign(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          batchNoAssigned({
            batchNo: this.batchNo,
            refereeId: this.assignForm.refereeId,
          }).then((res) => {
            if (res.data.errno == 0) {
              this.$message.success("领取成功");
              this.showAssign = false;
              this.getList();
            } else {
              this.$message.error("领取失败");
            }
          });
        }
      });
    },

    saveMember(form) {
      if (this.addform.number < 1) {
        this.$message.error("兑换码数量必须大于0");
        return false;
      }
      console.log(this.addform);
      this.$refs[form].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "正在保存数据，请稍后...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.5)",
          });
          createMemberCard(this.addform)
            .then((res) => {
              loading.close();
              if (res.data.errno == 0) {
                this.$message.success("创建成功");
                this.showadd = false;
                this.getList();
              } else {
                this.$message.error("创建失败");
              }
            })
            .catch((response) => {
              loading.close();
              this.$notify.error({
                title: "操作失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },
    clickaddmember() {
      this.showadd = true;
      this.addform = {
        number: 0, //份数
        memberName: "",
        memberType: 1,
        startTime: "",
        endTime: "",
      };
    },
    canceladd() {
      this.showadd = false;
    },
    handleExport() {
      /**
             * {
                channel: this.listQuery.channel,
                batchNo: this.listQuery.batchNo,
            }
             */
      if (this.listQuery.refereeId == "") {
        this.$message.warning("引荐人不能为空，请先选择引荐人");
        return false;
      }
      this.listLoading = true;
      memberCardExport({ refereeId: this.listQuery.refereeId }).then(
        (response) => {
          this.listLoading = false;
          console.log(response);
          let blob = new Blob([response.data], {
            type: "application/vnd.ms-excel",
          });
          console.log(blob);
          let fileName = Date.parse(new Date()) + ".xlsx";
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName);
          } else {
            var link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            //释放内存
            window.URL.revokeObjectURL(link.href);
          }
        }
      );
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      if (this.listQuery.timeArray && this.listQuery.timeArray.length === 2) {
        this.listQuery.start = this.listQuery.timeArray[0];
        this.listQuery.end = this.listQuery.timeArray[1];
      } else {
        this.listQuery.start = null;
        this.listQuery.end = null;
      }
      listCardMember(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
  },
  beforeCreate() {
    vm = this;
  },
  filters: {
    channelsFilter(value) {
      const rs = vm.channels.filter((item) => {
        return item.id === value;
      });
      if (rs != null && rs.length > 0) {
        return rs[0].name;
      }
    },
    refereeIdFilter(value) {
      const rs = vm.refereeList.filter((item) => {
        return item.refereeId === value;
      });
      if (rs != null && rs.length > 0) {
        return rs[0].refereeName;
      }
    },

    formatTime(value) {
      if (value == null) return "";
      return value.substring(0, 10);
    },
  },
};
</script>
<style>
.el-form-item {
  margin-bottom: 18px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.fixed-width .el-button--mini {
  width: auto;
}
</style>
