<template>
  <div class="app-container">
    <!-- 查询操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.pkSn" clearable class="filter-item" style="width: 150px;" placeholder="请输入券包编号" />
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 160px;" placeholder="请输入用户手机" />
      <el-input v-model="listQuery.pkCode" clearable class="filter-item" style="width: 150px;" placeholder="请输入券包码" />
      <el-select v-model="listQuery.isExchange" clearable style="width: 150px" class="filter-item" placeholder="请选择使用状态">
        <el-option key="0" label="未兑换" value="0" />
        <el-option key="1" label="已兑换" value="1" />
      </el-select>
      <el-date-picker v-model="exchangeTimeArray" type="datetimerange" value-format="yyyy-MM-dd hh:mm" class="filter-item"
        range-separator="至" start-placeholder="兑换开始日期" end-placeholder="兑换结束日期" :picker-options="{}" />

      <el-select v-model="listQuery.isPre" clearable style="width: 150px" class="filter-item" placeholder="请选择预售状态">
        <el-option key="0" label="未预售" value="0" />
        <el-option key="1" label="已预售" value="1" />
      </el-select>
      <el-input v-model="listQuery.preMobile" clearable class="filter-item" style="width: 150px;" placeholder="请输入预售手机" />
      <el-date-picker v-model="timeArray" type="datetimerange" value-format="yyyy-MM-dd hh:mm" class="filter-item"
        range-separator="至" start-placeholder="预售开始日期" end-placeholder="预售结束日期" :picker-options="{}" />

      <el-button v-permission="['GET /admin/couponPackageDetail/list']" class="filter-item" type="primary"
        icon="el-icon-search" @click="handleFilter(false)">查找</el-button>
      <el-button v-permission="['GET /admin/couponPackageDetail/list']" class="filter-item" type="primary"
        icon="el-icon-download" @click="handleFilter(true)">导出</el-button>
      <el-button v-permission="['POST /admin/couponPackageDetail/import']" class="filter-item" type="primary"
        icon="el-icon-upload2" @click="handleImport()">导入预售手机号</el-button>
      <div style="display:inline;color:#09afff;font-size:12px">导入格式：券包名、券包编码、团长手机号、客户手机号;excel第一个sheet的第一行的表头</div>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="客户手机" prop="customer.tel" />
      <el-table-column align="center" label="客户名称" prop="customer.customerName" />
      <el-table-column align="center" label="卡券包" prop="pkName" />
      <el-table-column align="center" label="卡券包兑换码" prop="pkCode" />
      <el-table-column align="center" label="是否已预售" prop="preMobile">
        <template slot-scope="scope">
          <el-tag :type="scope.row.preMobile != null && scope.row.preMobile.length
            ? 'success'
            : ''
            ">{{
    scope.row.preMobile != null && scope.row.preMobile.length > 0
    ? "已预售"
    : "未预售"
  }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="预售手机" prop="preMobile" />
      <el-table-column align="center" label="预售时间" prop="preTime" />
      <el-table-column align="center" label="抖音券号" prop="douyinCode" />

      <el-table-column align="center" label="是否已兑换" prop="isExchange">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isExchange == 0 ? 'success' : 'warning'">
            <span v-if="scope.row.isExchange == 0">否</span>
            <span v-if="scope.row.isExchange == 1">是</span>
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="兑换时间" prop="exchangeTime" />

      <el-table-column align="center" label="有效时间" prop="startTime">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime | formatTime }}到{{
            scope.row.endTime | formatTime
          }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否已作废" prop="deleted">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleted ? 'success' : 'warning'">
            <span v-if="scope.row.deleted == false">有效</span>
            <span v-if="scope.row.deleted">作废</span>
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.deleted == false && scope.row.isExchange == false && scope.row.preMobile == null"
            v-permission="['GET /admin/couponPackageDetail/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.isExchange == false && scope.row.preMobile != null"
            v-permission="['GET /admin/couponPackageDetail/rsend']" style="width:100px" icon="el-icon-refresh-left"
            type="text" size="mini" @click="handleRSend(scope.row)">补发预售短信</el-button>
          <el-button v-if="scope.row.deleted == false" v-permission="['GET /admin/couponPackageDetail/delete']"
            style="width:100px" icon="el-icon-delete" type="text" size="mini"
            @click="handleDelete(scope.row)">券码作废</el-button>
          <el-button v-permission="['GET /admin/couponPackageDetail/read']" type="text" size="mini" icon="el-icon-view"
            @click="handleDetail(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="detailFormVisible" title="详情" width="1000px" center>
      <el-table :data="detail" border>
        <el-table-column align="center" label="优惠券码id" prop="id" />
        <el-table-column align="center" label="优惠券名称" prop="coupon.name" />

        <!-- <el-table-column align="center" label="最低消费" prop="coupon.min">
          <template slot-scope="scope">满{{ scope.row.coupon.min }}元可用</template>
        </el-table-column> -->

        <el-table-column align="center" label="满减金额" prop="coupon.discount">
          <template slot-scope="scope">
            <span v-if="scope.row.coupon.voucherType == 1">减免{{ scope.row.coupon.discount }}元</span>
            <span v-if="scope.row.coupon.voucherType == 2">折扣率{{ scope.row.coupon.discount }}%</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="领取时间" prop="exchangeTime" />

        <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="是否已作废" prop="deleted">
          <template slot-scope="scope">
            <el-tag :type="scope.row.deleted ? 'success' : 'warning'">
              <span v-if="scope.row.deleted == false">有效</span>
              <span v-if="scope.row.deleted">作废</span>
            </el-tag>
          </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">
            <el-button v-if="scope.row.status==0" v-permission="['GET /admin/couponPackageDetail/delete']" style="width:100px" icon="el-icon-delete" type="text" size="mini" @click="handleDelete(scope.row)">券码作废</el-button>
          </template>
        </el-table-column> -->

        <!--  <el-table-column align="center" label="商品使用范围" prop="coupon.goodsType">
          <template slot-scope="scope">{{
            scope.row.coupon.goodsType | formatGoodsType
          }}</template>
        </el-table-column>

        <el-table-column align="center" label="优惠券类型" prop="coupon.type">
          <template>兑换券 </template>
        </el-table-column> 
         <el-table-column align="center" label="有效期" prop="coupon.startTime"> 
          <template slot-scope="scope">{{scope.row.coupon.startTime}}至{{scope.row.coupon.endTime}}</template>
         </el-table-column>
        <el-table-column align="center" label="状态" prop="coupon.status">
          <template slot-scope="scope">{{
            scope.row.coupon.status | formatStatus
          }}</template>
        </el-table-column>  -->
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailFormVisible = false">确定</el-button>
      </div>
    </el-dialog>

    <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" placeholder="请输入接收短信的手机号码" />
        </el-form-item>

        <el-form-item label="抖音券号" prop="douyinCode">
          <el-input v-model="sendForm.douyinCode" type="text" placeholder="请输入抖音原生核销券号" />
        </el-form-item>

        <!-- <el-form-item label="团长" prop="rid">
          <el-select v-model="sendForm.rid" style="width: 100%" class="filter-item" placeholder="请选择团长" filterable="">
            <el-option v-for="item in referees" :key="item.refereeId" :label="item.refereeName" :value="item.refereeId" />
          </el-select>
        </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-920-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 title="预售信息导入" :visible.sync="dialogImportVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataImportForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">

        <el-form-item label="团长" prop="rid">
          <el-select v-model="dataImportForm.rid" style="width: 100%" class="filter-item" placeholder="请选择团长"
            filterable="">
            <el-option v-for="item in referees" :key="item.refereeId" :label="item.refereeName" :value="item.refereeId" />
          </el-select>
        </el-form-item>

        <el-form-item label="excel文件">
          <input type="file" @change="getFile($event)" ref="fileupload" />
        </el-form-item>
      </el-form>

      <el-table :data="importResult" fit highlight-current-row>
        <el-table-column align="center" label="券包名" prop="pkName" />
        <el-table-column align="center" label="团长" prop="rName" />
        <el-table-column align="center" label="团长手机号" prop="rmobile" />
        <el-table-column align="center" label="客户手机号" prop="mobile" />
        <el-table-column align="center" label="分配预售码" prop="coupon" />
        <el-table-column align="center" label="导入结果" prop="remark" />
      </el-table>
      <div style="text-align:right">
        <el-button type="text" icon="el-icon-download" @click="handleDownload()">结果导出</el-button>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
        <el-button icon="el-icon-upload2" type="primary" @click="importConfirm">导入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoots } from "@/api/referee";
import {
  listPackageDetail,
  packageDetailRead,
  packageDetailRSend,
  packageDetailSend,
  listPackageDetailExport,
  packageImport,
  packageDetailDelete,
} from "@/api/couponpackage";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import {
  defaultCouponTypeOptions,
  defaultUseStatusOptions,
  statusMap,
  defaultTypeOptions,
} from "@/api/enumUtils";

export default {
  name: "CouponPackageDetail",
  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 "已下架";
      }
    },

    formatTime(value) {
      if (value == null) return "";
      return value.substring(0, 10);
    },
  },
  data() {
    return {
      typeOptions: Object.assign({}, defaultTypeOptions),
      useStatusOptions: Object.assign({}, defaultUseStatusOptions),
      referees: [],
      timeArray: [],
      exchangeTimeArray: [],
      coupon: {},
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        pkCode: null,
        isExchange: null,
        pkSn: null,
        isPre: "",
        mobile: "",
        status: "",
        isExport: false, //是否导出
        preMobile: "",
        preStart: "",
        preEnd: "",
        exchangeStart: "",
        exchangeEnd: "",
        sort: "create_time",
        order: "desc",
      },
      detailFormVisible: false,
      detail: [],
      downloadLoading: false,
      statusMap: statusMap,
      dialogSendFormVisible: false,
      sendForm: {
        mobile: "",
        packageId: "",
      },
      rules: {
        mobile: [
          { required: true, message: "请输入发送的手机号", trigger: "blur" },
        ],
        douyinCode: [
          { required: true, message: "请输入抖音核销券号", trigger: "blur" },
        ],
      },
      dialogImportVisible: false,
      dataImportForm: {
        file: undefined,
      },
      importResult: [], //导入结果
    };
  },
  created() {
    this.init();
  },
  methods: {
    init: function () {
      if (this.$route.query.pkSn != null)
        this.listQuery.pkSn = this.$route.query.pkSn;
      this.getList();
    },
    getReferee() {
      listRoots().then((res) => {
        this.referees = res.data.data;
      });
    },
    getList() {
      this.listLoading = true;
      if (this.listQuery.isExport == false) {
        listPackageDetail(this.listQuery).then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        });
      } else {
        console.info("listPackageDetailExport");
        listPackageDetailExport(this.listQuery)
          .then((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) {
              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);
            }
            this.listLoading = false;
          })
          .catch(() => {
            this.list = [];
            this.total = 0;
            this.listLoading = false;
          });
      }
    },
    handleImport() {
      this.dialogImportVisible = true;
      if (this.referees.length == 0) {
        this.getReferee();
      }
      this.dataImportForm = {
        couponId: undefined,
        file: undefined,
        rid: "",
      };
      this.importResult = [];
    },
    getFile: function (event) {
      this.dataImportForm.file = event.target.files[0];
      console.log(this.file);
    },
    importConfirm() {
      if (this.dataImportForm.file == "") {
        this.$message.warning("请选择文件！");
        return;
      }
      // console.info(this.dataImportForm.file.name)
      if (this.dataImportForm.file.name.lastIndexOf("xlsx") < 0) {
        this.$message.warning("请选择excel文件！");
        return;
      }
      this.$refs["dataForm"].validate((valid) => {
        if (!valid) {
          return;
        }
      });

      const loading = this.$loading({
        lock: true,
        text: "文件导入中，请耐心等待...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      var formData = new window.FormData(); // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'
      formData.append("file", this.dataImportForm.file);
      formData.append("rid", this.dataImportForm.rid);

      packageImport(formData)
        .then((res) => {
          console.log("导入返回数据", res);
          loading.close();
          if (res.data.errno == 0) {
            this.$message.success(res.data.errmsg);
            if (res.data.data.length >= 1) {
              this.importResult = res.data.data;
            }
          } else {
            this.$message.warning(res.data.errmsg);
          }
        })
        .catch((err) => {
          loading.close();
          this.$message.warning(err.data.errmsg);
        });
    },
    handleDelete(row) {
      //券码作废
      this.$confirm("确定将此码作废？已兑换未使用也将作废").then((res) => {
        packageDetailDelete({ packageId: row.id })
          .then((response) => {
            this.$message.success("作废成功");
            this.getList();
          })
          .catch((response) => {
            this.$message.warning(response.data.errmsg);
          });
      });
    },
    handleSend(row) {
      this.dialogSendFormVisible = true;
      this.sendForm = {
        mobile: "",
        packageId: row.id,
      };
      if (this.referees.length == 0) this.getReferee();
    },
    sendSms() {
      this.$refs["sendForm"].validate((valid) => {
        if (valid) {
          packageDetailSend(this.sendForm).then((res) => {
            if (res.errno == 0) {
              this.dialogSendFormVisible = false;
              this.getList();
              this.$notify.success({
                title: "成功",
                message: "短信发送成功",
              });
            } else {
              this.$message.warning(res.data.errmsg);
            }
          })
            .catch((response) => {
              this.$message.warning(response.data.errmsg);
            });
        }
      });
    },
    handleRSend(row) {
      this.$confirm("确定补发此短信吗？").then((res) => {
        packageDetailRSend({ mobile: row.preMobile, packageId: row.id }).then(
          (res) => {
            if (res.errno == 0) {
              this.getList();
              this.$notify.success({
                title: "成功",
                message: "短信补发成功",
              });
            }
            else  
              this.$message.warning(res.data.errmsg); 
          }
        )
          .catch((response) => {
            this.$message.warning(response.data.errmsg);
          });;
      });
    },
    handleFilter(isExport) {
      this.listQuery.preStart = "";
      this.listQuery.preEnd = "";
      this.listQuery.exchangeStart = "";
      this.listQuery.exchangeEnd = "";
      if (this.timeArray && this.timeArray.length === 2) {
        this.listQuery.preStart = this.timeArray[0];
        this.listQuery.preEnd = this.timeArray[1];
      }
      if (this.exchangeTimeArray && this.exchangeTimeArray.length === 2) {
        this.listQuery.exchangeStart = this.exchangeTimeArray[0];
        this.listQuery.exchangeEnd = this.exchangeTimeArray[1];
      }
      // console.info(this.timeArray)
      // console.info(this.exchangeTimeArray)
      // console.info(this.listQuery)
      this.listQuery.page = 1;
      this.listQuery.isExport = isExport;
      this.getList();
    },
    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 "未知";
      }
    },
    handleDetail(row) {
      packageDetailRead({ packageId: row.id }).then((res) => {
        this.detail = res.data.data;
        this.detailFormVisible = true;
      });
    },
    orderStatusFilter(status) {
      if (status == null) return "";
      return statusMap[status];
    },
    handleDownload() {
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "券包名称",
          "券编号",
          "团长",
          "团长手机",
          "客户手机号",
          "分配的券码",
          "导入结果",
        ];
        const filterVal = [
          "pkName",
          "pkSn",
          "rName",
          "rmobile",
          "mobile",
          "coupon",
          "remark",
        ];
        excel.export_json_to_excel2(
          tHeader,
          this.importResult,
          filterVal,
          "券包导入"
        );
        this.downloadLoading = false;
      });
    },
  },
};
</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>
