<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.memberName" clearable class="filter-item" style="width: 150px" placeholder="请输入码名称" />
      <el-input v-model="listQuery.batchNo" clearable class="filter-item" style="width: 150px" placeholder="请输入批次号" />
      <el-select v-model="listQuery.channel" clearable style="width: 150px" class="filter-item" placeholder="请选择渠道">
        <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.refereeId" clearable style="width: 160px" filterable="" 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: 120px" 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" style="width:300px" 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/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/memberCoupon/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="clickaddmember">生成兑换码</el-button>
      <el-button v-permission="['POST /admin/memberCoupon/export']" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">导出</el-button>
      <el-button v-permission="['GET /admin/memberCoupon/batchNoAssigned']" class="filter-item" type="primary" icon="el-icon-thumb" @click="handleAssignMember">领取</el-button>
      <el-button v-permission="['GET /admin/memberCoupon/useExplain']" class="filter-item" type="primary" icon="el-icon-message" @click="handleUseExplain">使用备注</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="id" />
      <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="兑换期限" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime|formatTime}}至{{scope.row.endTime|formatTime}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否已兑换">
        <template slot-scope="scope">
          <el-tag>
            <span v-if="scope.row.isExchange==true">已兑换</span>
            <span v-if="scope.row.isExchange==false">未兑换</span>
          </el-tag>
        </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="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/memberCoupon/delete']" style="color:red" type="text" icon="el-icon-close" size="mini" @click="handleDeleteMember(scope.row)">删除</el-button>
          <!-- <el-button v-permission="['POST /admin/memberCoupon/deleteBatchNo']" style="color:red" type="text"  icon="el-icon-delete" @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="120px">
        <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="兑换码数量" 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-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-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="700px" :show-close="false" :close-on-click-modal="false" center>
      <el-form ref="assignForm" :model="assignForm" :rules="assignFormRule" status-icon label-position="left" style="width:600px" label-width="100px">
        <el-form-item label="引荐人" prop="refereeId">
          <el-select v-model="assignForm.refereeId" clearable style="width: 100%" filterable="" 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-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="开始编号" prop="start">
              <el-input v-model="assignForm.start" type="number" placeholder="请输入开始编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截至编号" prop="end">
              <el-input v-model="assignForm.end" type="number" placeholder="请输入截至编号" clearable />
            </el-form-item>
            <span>共预计{{assignForm.end==null?0:(assignForm.end-assignForm.start+1)}}个会员卡</span>
          </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>

    <!---使用备注--->
    <el-dialog :visible.sync="showExplainDialog" title="会员卡使用备注" width="700px" :show-close="false" :close-on-click-modal="false" center>
      <el-form ref="explainForm" :model="explainForm" :rules="explainFormRule" status-icon label-position="left" style="width:600px" label-width="100px">
        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="开始编号" prop="start">
              <el-input v-model="explainForm.start" type="number" placeholder="请输入开始编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截至编号" prop="end">
              <el-input v-model="explainForm.end" type="number" placeholder="请输入截至编号" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="使用说明" prop="explain">
          <el-input v-model="explainForm.explain" type="textarea" rows="8" placeholder="请输入使用说明，如送给哪些人或机构"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showExplainDialog=false">取消</el-button>
        <el-button type="primary" @click="saveUseExplain()">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>
 
<script>
import {
  listMember,
  createPackage,
  deleteData,
  deleteBatchNo,
  exportData,
  batchNoAssigned,
  useExplain,
} from "@/api/member";
import { allChannel } from "@/api/channel";
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 {
      refereeList: [],
      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: [],
      channels: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        memberName: "",
        channel: "",
        batchNo: "",
        isExchange: "",
        refereeId: null,
      },
      showAssign: false,
      batchNo: "",
      assignForm: {
        refereeId: "",
        start: null,
        end: null,
      },
      showExplainDialog: false,
      explainForm: {
        start: null,
        end: null,
        explain: null,
      },
      explainFormRule: {
        explain: [
          { required: true, message: "使用说明不能为空", trigger: "blur" },
        ],
        start: [
          { required: true, message: "开始编号不能为空", trigger: "blur" },
        ],
        end: [{ required: true, message: "结束编号不能为空", trigger: "blur" }],
      },
      assignFormRule: {
        refereeId: [
          { required: true, message: "引荐人不能为空", trigger: "blur" },
        ],
        start: [
          { required: true, message: "开始编号不能为空", trigger: "blur" },
        ],
        end: [{ 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();
    allChannel().then((res) => {
      this.channels = res.data.data;
    });
    refereeRoots().then((res) => {
      this.refereeList = res.data.data;
    });
  },
  methods: {
    saveUseExplain() {
      this.$refs["explainForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认填写此批会员卡使用说明吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            useExplain({
              explain: this.explainForm.explain,
              start: this.explainForm.start,
              end: this.explainForm.end,
            })
              .then((res) => {
                this.$notify.error({
                  title: "填写",
                  message: "填写成功",
                });
                this.showExplainDialog = false;
              })
              .catch((res) => {
                this.$notify.error({
                  title: "失败",
                  message: res.data.errmsg,
                });
              });
          });
        }
      });
    },
    handleUseExplain() {
      this.explainForm = {
        start: null,
        end: null,
        explain: null,
      };
      this.showExplainDialog = true;
    },
    handleAssignMember(row) {
      this.showAssign = true;
      this.assignForm = {
        refereeId: "",
      };
    },
    handleDeleteMember(row) {
      this.$confirm("是否删除兑换码:" + row.memberCode + " ?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteData({ id: row.id }).then((res) => {
          if (res.data.errno == 0) {
            this.$message.success("删除成功");
            this.$notify.error({
              title: "删除",
              message: "删除成功",
            });
            this.getList();
          } else {
            this.$message.error("删除失败");
          }
        });
      });
    },
    handleDeleteBatch(row) {
      this.$confirm("是否删除批次号为:" + row.batchNo + " 的兑换码?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteBatchNo({ batchNo: row.batchNo }).then((res) => {
          if (res.data.errno == 0) {
            this.$notify.error({
              title: "删除",
              message: "删除成功",
            });
            this.getList();
          } else {
            this.$notify.error({
              title: "删除",
              message: "删除失败",
            });
          }
        });
      });
    },
    saveAssign(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.$confirm("确认领取这些会员卡吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            batchNoAssigned({
              refereeId: this.assignForm.refereeId,
              start: this.assignForm.start,
              end: this.assignForm.end,
            }).then((res) => {
              if (res.data.errno == 0) {
                this.$notify.error({
                  title: "领取",
                  message: "领取成功,实际领取：" + res.data.data + "个",
                });
                this.showAssign = false;
                this.getList();
              } else {
                this.$message.error("领取失败");
                this.$notify.error({
                  title: "领取",
                  message: "领取失败",
                });
              }
            });
          });
        }
      });
    },
    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)",
          });
          createPackage(this.addform)
            .then((res) => {
              loading.close();
              if (res.data.errno == 0) {
                this.$notify.error({
                  title: "创建",
                  message: "创建成功",
                });
                this.showadd = false;
                this.getList();
              } else {
                this.$notify.error({
                  title: "创建",
                  message: "创建失败",
                });
              }
            })
            .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: "",
        channelId: "",
      };
    },
    canceladd() {
      this.showadd = false;
    },
    handleExport() {
      if (
        this.listQuery.start == null &&
        this.listQuery.end == null &&
        this.listQuery.refereeId == null &&
        this.listQuery.isExchange == "" &&
        this.listQuery.memberName == "" &&
        this.listQuery.batchNo == "" &&
        this.listQuery.channel == ""
      ) {
        this.$notify.error({
          title: "失败",
          message: "请至少选择一个查询条件",
        });
        return;
      }
      this.listLoading = true;
      exportData(this.listQuery).then((response) => {
        this.listLoading = false;
        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) {
          console.log(2);
          navigator.msSaveBlob(blob, fileName);
        } else {
          console.log(3);
          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;
      }
      listMember(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;
}
.el-button--text {
  padding: 0 !important;
  width: auto !important;
  margin-left: 5px !important;
}
.el-button--text span {
  margin-left: 0px !important;
}
</style>
