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

    <!-- 查询和其他操作 -->
    <div class="filter-container"> 
      <el-select v-model="listQuery.couponId" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券">
        <el-option v-for="type in coupons" :key="type.id" :label="type.name" :value="type.id" />
      </el-select>
      
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="请输入预售手机号" />
       <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/spdBank/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/spdBank/import']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">导入预售手机号</el-button> 
      <!-- <el-button v-permission="['POST /admin/spdBank/cancel']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleCancel">导入注销券</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="customer.customerName" />
      <el-table-column align="center" label="用户手机" prop="customer.tel" /> 
      <el-table-column align="center" label="券名称" prop="coupon.name" /> 
      <el-table-column align="center" label="券对应商品" prop="coupon.couponGoodsName" /> 
      <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="exchangeTime" /> 
      <el-table-column align="center" label="使用状态" prop="status">
        <template slot-scope="scope">
          <el-tag>  {{ scope.row.status | formatUseStatus }}</el-tag>
            </template>
      </el-table-column>

      <el-table-column align="center" label="有效期" prop="startTime" >
           <template slot-scope="scope">
               {{formatTime(scope.row.startTime,'yyyy-MM-dd')}} 到 {{formatTime(scope.row.endTime,'yyyy-MM-dd')}}
           </template>
      </el-table-column>

      <el-table-column align="center" label="订单号" prop="order.orderSn" /> 
      <el-table-column align="center" label="使用时间" prop="usedTime" />
       
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.mobile!=null" v-permission="['GET /admin/spdBank/send']" type="primary" size="mini" @click="handleSMS(scope.row)">发送短信</el-button> 
          <el-button v-else v-permission="['GET /admin/spdBank/bind']" type="primary" size="mini" @click="handleBind(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="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
       
        <el-form-item label="优惠券" prop="couponId">
          <el-select v-model="dataForm.couponId" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券">
            <el-option v-for="type in coupons" :key="type.id" :label="type.name" :value="type.id" />
          </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="mobile" />
            <el-table-column align="center" label="分配预售码" prop="couponCode" />
            <el-table-column align="center" label="导入结果" prop="remark" />
        </el-table> 

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button icon="el-icon-upload2" type="primary" @click="importConfirm">导入</el-button> 
      </div>
    </el-dialog>

     <!-- 手动绑定 -->
    <el-dialog  title="手工绑定预售手机" :visible.sync="dialogBindFormVisible" width="600px">
      <el-form ref="dataBindForm" :rules="rules" :model="dataBindForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
       
      <el-form-item label="预售手机号" prop="mobile">
        <el-input minlength="11" maxlength="11"  v-model="dataBindForm.mobile" type="number" />
        </el-form-item>  
      </el-form>
 
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBindFormVisible = false">关闭</el-button>
        <el-button icon="el-icon-upload2" type="primary" @click="bindConfirm">预售绑定</el-button> 
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listSpdBank, importBooking,spdCoupon,sendSms,bind } from '@/api/spdBank'  
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination 
import { formatDate } from "@/utils/date";
let vm

export default {
  name: 'spdBank',
  components: { Pagination },
  filters: { 
    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 {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        couponId: undefined, 
        timeArray: [],
        mobile:'',
        page: 1,
        limit: 20,
        sort: 'add_time',
        order: 'desc'
      },
      importResult:[],
      coupons: [],
      dataForm: { 
        couponId: undefined, 
        file: undefined,
        shopChannel: undefined
      }, 
      dialogBindFormVisible:false,
      dataBindForm:{
        id:0,
        mobile:null
      },
      deletedOptions: [{
        value: false,
        label: '正常'
      }, {
        value: true,
        label: '删除'
      }],
      
      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]);
            }
          }
        ]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        shopNo: [{ required: true, message: '编号不能为空', trigger: 'blur' }], 
        couponId: [{ required: true, message: '优惠券不能为空', trigger: 'blur' }], 
        mobile: [{ required: true, message: '预售手机号不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  beforeCreate() {
    vm = this
  },
  created() {
    this.getList()
    spdCoupon().then(res => {
      this.coupons = res.data.data
    }) 
  },
  methods: {
    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;
      }
      listSpdBank(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()
    },
    resetForm() {
      this.dataForm = { 
        couponId: undefined, 
        file:undefined
      } 
      // refs 操作
     let input = this.$refs.fileupload
      if (input) { 
      	input.value = ''
      }

      this.importResult=[];
    },
    handleImport(){
        this.resetForm();
        this.dialogFormVisible=true
    },
    handleSMS(row){//手动触发短信 
     this.$confirm("确定发送短信再次提醒用户吗?", "提示", {
        confirmButtonText: "发送",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
       sendSms({mobile:row.mobile,coupon:row.couponCode}).then(res=>{
         console.info(res)
           this.$notify.success({
                title: '成功',
                message: '短信发送成功'
              })
       }).catch(res=>{

       })
      }
    ) 
    },
    handleBind(row){
      this.dialogBindFormVisible=true
      this.dataBindForm.id=row.id

    },
    bindConfirm(){//手动绑定
    
      this.$refs['dataBindForm'].validate(valid => {
        if (valid) {
     this.$confirm("确定绑定此手机号码吗?", "提示", {
        confirmButtonText: "绑定并发送短信",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
       bind(this.dataBindForm).then(res=>{
         console.info(res)
         this.dialogBindFormVisible=false
         this.getList();
           this.$notify.success({
                title: '成功',
                message: '绑定成功'
              })
       }).catch(res=>{

       })
      }
    ) 
        }
      })
    },
    formatTime(time) {
      if (time == null || time === "") {
        return "";
      }
      const date = new Date(time);
      return formatDate(date, "yyyy-MM-dd");
    },
    //获取上传文件
    getFile: function(event) {
      this.dataForm.file = event.target.files[0];
      console.log(this.file);
    },
    importConfirm() { 
      if (this.dataForm.file == "") {
        this.$message.warning("请选择文件！");
        return;
      }
      console.info(this.dataForm.file.name)
      if(this.dataForm.file.name.lastIndexOf("xlsx")<0){
        this.$message.warning("请选择excel文件！");
        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.dataForm.file); 
      formData.append("couponId", this.dataForm.couponId); 
     
      importBooking(formData)
        .then(res => {
          console.log("导入返回数据", res);
          loading.close();
          if (res.data.errno == 0) {
            this.$message.success(res.data.errmsg); 
               console.info(res.data.data)
             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);
        });
    }
  }
}
</script>
