<template>
  <div class="app-container">

    <div class="table-layout">
      <el-row>
        <el-col :span="4" class="table-cell-title">名称</el-col>
        <el-col :span="4" class="table-cell-title">介绍名称</el-col>
        <el-col :span="4" class="table-cell-title">标签</el-col>
        <el-col :span="4" class="table-cell-title">优惠券类型</el-col>
        <el-col :span="4" class="table-cell-title">最低消费</el-col>
        <el-col :span="4" class="table-cell-title">优惠面值</el-col>
      </el-row>
      <el-row>
        <el-col :span="4" class="table-cell">{{ coupon.name }}</el-col>
        <el-col :span="4" class="table-cell">{{ coupon.desc }}</el-col>
        <el-col :span="4" class="table-cell">{{ coupon.tag }}</el-col>
        <el-col :span="4" class="table-cell" style="line-height:20px">{{ coupon.type | formatType }} 使用渠道：{{ formateChannel(coupon.channelId)
          }}</el-col>
        <el-col :span="4" class="table-cell">满{{ coupon.min }}元可用</el-col>
        <el-col :span="4" class="table-cell">
          <span v-if="coupon.voucherType == 1">减免{{ coupon.discount }}元</span>
          <span v-if="coupon.voucherType == 2">折扣率{{ coupon.discount }}%</span>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4" class="table-cell-title">每人限额</el-col>
        <el-col :span="4" class="table-cell-title">当前状态</el-col>
        <el-col :span="4" class="table-cell-title">商品范围</el-col>
        <el-col :span="4" class="table-cell-title">有效期</el-col>
        <!-- <el-col :span="4" class="table-cell-title">优惠兑换码</el-col> -->
        <el-col :span="4" class="table-cell-title">分享二维码</el-col>
        <el-col :span="4" class="table-cell-title">发行数量</el-col>
      </el-row>
      <el-row>
        <el-col :span="4" class="table-cell">{{ coupon.limit }}</el-col>
        <el-col :span="4" class="table-cell">{{ coupon.status | formatStatus }}</el-col>
        <el-col :span="4" class="table-cell" style="line-height:12px">
          {{ coupon.goodsType | formatGoodsType }}
          <span style="color:red;font-size:5px;" v-html="coupon.couponGoodsName"> </span>
        </el-col>
        <el-col :span="4" class="table-cell">{{ getTimeScope() }}</el-col>
        <!-- <el-col :span="4" class="table-cell">{{ coupon.code }}</el-col> -->
        <el-col :span="4" class="table-cell" style="text-align:center;padding-top: 5px;">
          <el-image :preview-src-list="[coupon.qrUrl]" :lazy="true" :src="coupon.qrUrl" style="width:50px"></el-image>
        </el-col>
        <el-col :span="4" class="table-cell">{{ coupon.total === 0 ? "不限" : coupon.total }}</el-col>
      </el-row>
    </div>

    <!-- 查询操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="请输入用户手机" />
      <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" placeholder="请选择使用状态">
        <el-option v-for="type in useStatusOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>
      <el-button v-permission="['GET /admin/coupon/listuser']" class="filter-item" type="primary" icon="el-icon-search"
        @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/coupon/export']" class="filter-item" type="primary" icon="el-icon-download"
        @click="handleExport">导出</el-button>
      <el-button v-permission="['POST /admin/coupon/batchCollection']" class="filter-item" type="primary"
        icon="el-icon-thumb" @click="handleAssignMember">领取</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <!--  <el-table-column align="center" label="用户优惠券ID" prop="id" sortable/>  -->

      <el-table-column align="center" label="用户名称" prop="customer.customerName" />
      <el-table-column align="center" label="优惠券编号" prop="id" />
      <el-table-column align="center" label="订单号" prop="order.orderSn" />
      <el-table-column align="center" label="用户手机" prop="customer.tel" />
      <el-table-column align="center" label="券包兑换码" prop="couponPackage.pkCode">
        <template slot-scope="scope"><span style="color:red" v-if="scope.row.couponPackage">{{
          scope.row.couponPackage.pkCode }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="券包名称" prop="couponPackage.pkName">
        <template slot-scope="scope"><span style="color:red" v-if="scope.row.couponPackage">{{
          scope.row.couponPackage.pkName }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="兑换码" prop="couponCode" />

      <el-table-column align="center" label="预售手机" prop="mobile" />
      <el-table-column align="center" label="预售时间" prop="sendTime" />

      <el-table-column align="center" label="领取时间" prop="addTime" />
      <el-table-column align="center" label="领取状态" prop="id">
        <template slot-scope="scope">{{ scope.row.referenceId ? '已领取' : '未领取' }}</template>
      </el-table-column>
      <el-table-column align="center" label="使用状态" prop="status">
        <template slot-scope="scope">{{ scope.row.status | formatUseStatus }}</template>
      </el-table-column>

      <el-table-column align="center" label="订单ID" prop="orderId" />
      <el-table-column align="center" label="订单状态" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag>{{ orderStatusFilter(scope.row.order == null ? null : scope.row.order.orderStatus) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="使用时间" prop="usedTime" />
      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="!scope.row.couponPackage">
          <el-button
            v-if="scope.row.deleted == false && scope.row.status != 1 && scope.row.status != 3 && scope.row.mobile == null"
            v-permission="['GET /admin/coupon/send']" style="width:100px" icon="el-icon-chat-dot-round" type="text"
            size="mini" @click="handleSend(scope.row)">发送预售短信</el-button>
          <el-button
            v-if="scope.row.deleted == false && scope.row.status != 1 && scope.row.status != 3 && scope.row.mobile != null"
            v-permission="['GET /admin/coupon/rsend']" style="width:100px" icon="el-icon-refresh-left" type="text"
            size="mini" @click="handleRSend(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 title="发送预售短信" :visible.sync="dialogSendFormVisible" width="600px">
      <el-form ref="sendForm" :rules="rules" :model="sendForm" status-icon label-position="left" label-width="100px"
        style="margin-left:20px;">
        <el-form-item label="客户手机号" prop="mobile">
          <el-input v-model="sendForm.mobile" maxlength="11" type="number" />
        </el-form-item>

        <el-form-item label="短信内容" prop="name">
          <el-input type="textarea" rows="5" disabled="disabled"
            value="尊敬的客户：感谢您购买鲸致生活%s，请点击》 https://mall.zhaijieshi.cc/groupon/index.html?coupon=%s，登录官方小程序兑换服务。如有疑问，请致电鲸致生活全国统一客服热线400-921-8987（客服时间7：30-21：30）。祝您生活如意！"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogSendFormVisible = false">取消</el-button>
        <el-button type="primary" @click="sendSms">立即发送</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%" 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>

  </div>
</template>

<script>
import {
  readCoupon,
  listCouponUser,
  exportData,
  batchCollection,
  sendSms,
} from "@/api/coupon";
import {
  defaultCouponTypeOptions,
  defaultUseStatusOptions,
  statusMap,
} from "@/api/enumUtils";
import { refereeSelfList } from "@/api/referee";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { allChannel } from "@/api/channel";

export default {
  name: "CouponDetail",
  components: { Pagination },
  filters: {
    formatType(type) {
      for (let i = 0; i < defaultCouponTypeOptions.length; i++) {
        if (type === defaultCouponTypeOptions[i].value) {
          return defaultCouponTypeOptions[i].label;
        }
      }
      return "";
    },
    formatGoodsType(goodsType) {
      if (goodsType === 0) {
        return "全场通用";
      } else if (goodsType === 1) {
        return "指定分类";
      } else {
        return "指定商品";
      }
    },
    formatStatus(status) {
      if (status === 0) {
        return "正常";
      } else if (status === 1) {
        return "已过期";
      } else {
        return "已下架";
      }
    },
    formatUseStatus(status) {
      if (status === 0) {
        return "未使用";
      } else if (status === 1) {
        return "已使用";
      } else if (status === 3) {
        return "已过期";
      } else if (status === 4) {
        return "已占用";
      } else if (status === 5) {
        return "已注销";
      } else {
        return "已下架";
      }
    },
  },
  data() {
    return {
      typeOptions: Object.assign({}, defaultCouponTypeOptions),
      useStatusOptions: Object.assign({}, defaultUseStatusOptions),
      coupon: {},
      list: [],
      channels: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        couponId: 0,
        mobile: undefined,
        status: undefined,
        sort: "add_time",
        order: "desc",
      },
      downloadLoading: false,
      statusMap: statusMap,
      showAssign: false,
      refereeList: [],
      assignForm: {
        refereeId: "",
        start: null,
        end: null,
      },
      assignFormRule: {
        refereeId: [
          { required: true, message: "引荐人不能为空", trigger: "blur" },
        ],
        start: [
          { required: true, message: "开始编号不能为空", trigger: "blur" },
        ],
        end: [{ required: true, message: "结束编号不能为空", trigger: "blur" }],
      },
      dialogSendFormVisible: false,
      sendForm: {
        mobile: "",
        id: "",
      },
      rules: {
        mobile: [
          { required: true, message: "请输入发送的手机号", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    allChannel().then((res) => {
      this.channels = res.data.data;
    });

    this.init();
    refereeSelfList().then((res) => {
      this.refereeList = res.data.data.list;
    });
  },
  methods: {
    init: function () {
      if (this.$route.query.id == null) {
        return;
      }
      readCoupon(this.$route.query.id).then((response) => {
        this.coupon = response.data.data;
      });
      this.listQuery.couponId = this.$route.query.id;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      listCouponUser(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;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleExport() {
      if (this.coupon.type != 2) {
        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);
        }
      });
    },
    handleSend(row) {
      this.dialogSendFormVisible = true;
      this.sendForm = {
        mobile: "",
        id: row.id,
      };
      if (this.referees.length == 0) this.getReferee();
    },
    sendSms() {
      this.$refs["sendForm"].validate((valid) => {
        if (valid) {
          sendSms(this.sendForm)
            .then((res) => {
              console.info(res);
              this.dialogSendFormVisible = false;
              this.getList();
              this.$notify.success({
                title: "成功",
                message: "短信发送成功",
              });
            })
            .catch((res) => {
              this.$notify.error({
                title: "失败",
                message: res.data.errmsg,
              });
            });
        }
      });
    },
    handleRSend(row) {
      this.$confirm("确定补发此短信吗？").then((res) => {
        sendSms({ mobile: row.mobile, id: row.id })
          .then((res) => {
            this.getList();
            this.$notify.success({
              title: "成功",
              message: "短信补发成功",
            });
          })
          .catch((res) => {
            this.$notify.error({
              title: "失败",
              message: res.data.errmsg,
            });
          });
      });
    },
    getTimeScope() {
      if (this.coupon.timeType === 0) {
        return "领取" + this.coupon.days + "天有效";
      } else if (this.coupon.timeType === 1) {
        return (
          "自" + this.coupon.startTime + "至" + this.coupon.endTime + "有效"
        );
      } else {
        return "未知";
      }
    },
    getGoodsScope() { },
    orderStatusFilter(status) {
      if (status == null) return "";
      return statusMap[status];
    },
    handleAssignMember(row) {
      this.showAssign = true;
      this.assignForm = {
        refereeId: "",
      };
    },
    saveAssign(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.$confirm("确认领取这些优惠券吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            batchCollection({
              referenceId: this.assignForm.refereeId,
              couponStartNo: this.assignForm.start,
              couponEndNo: this.assignForm.end,
              couponId: this.listQuery.couponId,
            }).then((res) => {
              if (res.data.errno == 0 && res.data.data > 0) {
                this.$notify.success({
                  title: "领取",
                  message: "领取成功,实际领取：" + res.data.data + "个",
                });
                this.showAssign = false;
                this.init();
              } else {
                this.$message.error("领取失败");
                this.$notify.error({
                  title: "领取",
                  message: "领取失败",
                });
              }
            });
          });
        }
      });
    },
    formateChannel(channelId) {
      if (channelId == null || channelId == '') {
        return;
      }
      let nm = '';
      this.channels.forEach(f => {
        if (f.id == channelId) {
          nm = f.name;
        }
      })
      return nm;
    },
  },
};
</script>
<style scoped>
.filter-container {
  margin-top: 20px;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
}

.table-cell {
  height: 60px;
  line-height: 40px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  overflow: hidden;
}

.table-cell-title {
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  background: #f2f6fc;
  text-align: center;
  font-size: 14px;
  color: #303133;
}
</style>
