<template>
  <div class="app-container">
 
   <el-tabs v-model="action">
      <el-tab-pane label="上汽员工" name="1" >
          <!-- 查询和其他操作 -->
    <div v-if="action=='1'">
    <div class="filter-container">  
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="请输入员工手机号" />
      <el-input v-model="listQuery.sNo" clearable class="filter-item" style="width: 200px;" placeholder="请输入员工号" />
        
      <el-button v-permission="['GET /admin/saicgroup/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/saicgroup/import']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">导入上汽员工</el-button> 
      <el-button v-permission="['POST /admin/saicgroup/createConfig']" class="filter-item" type="primary" icon="el-icon-setting" @click="handleConfig">优惠券设置</el-button> 
    </div>

    <!-- 查询结果 -->
    <el-table  id="list" :ref="list" v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row> 
    <el-table-column type="expand">
        <template slot-scope="props"> 
        <el-table :data="props.row.coupons" border> 
          <el-table-column align="center" label="券码" prop="couponCode" /> 
          <el-table-column align="center" label="券名称" prop="couponName" /> 
          <el-table-column align="center" label="领取时间" prop="createTime" /> 
          <el-table-column align="center" label="兑换时间" prop="exchangeTime" /> 
          <el-table-column align="center" label="是否已使用" prop="isUsed" >
             <template slot-scope="scope">
               <el-tag>{{scope.row.isUsed?'是':'否'}}</el-tag>
             </template>
          </el-table-column> 
        </el-table>
        </template>
    </el-table-column>
      <el-table-column align="center" label="员工手机" prop="mobile" /> 
      <el-table-column align="center" label="员工号" prop="sNo" /> 
      <el-table-column align="center" label="导入时间" prop="createTime" />    
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
      </el-tab-pane>
      <el-tab-pane label="上汽优惠券" name="2" > 

          <!-- 上汽优惠券信息 -->
   <div v-if="action=='2'">
   <div class="filter-container">  
       <el-select v-model="listCouponsQuery.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="listCouponsQuery.couponCode" clearable class="filter-item" style="width: 200px;" placeholder="请输入券码" /> 
      <el-input v-model="listCouponsQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="请输入预售手机号" /> 
      <el-button v-permission="['GET /admin/saicgroup/listCoupons']" class="filter-item" type="primary" icon="el-icon-search" @click="handleCouponsFilter">查找</el-button>
     </div>
     <el-table id="coupons" v-loading="listLoading" :data="listCoupons" element-loading-text="正在查询中。。。" border fit highlight-current-row>   
          <el-table-column align="center" label="券名称" prop="coupon.name" /> 
          <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="createTime" /> 
          <el-table-column align="center" label="兑换时间" prop="exchangeTime" /> 
          <el-table-column align="center" label="是否已使用" prop="status" >
             <template slot-scope="scope">
               <el-tag :type="scope.row.status==1?'error':scope.row.status==2?'success':'info'">{{ scope.row.status | formatStatus }}</el-tag>
             </template>
          </el-table-column>  
          
          <el-table-column align="center" label="订单id" prop="orderId" /> 
         <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
         <template slot-scope="scope">
          <el-button v-if="scope.row.mobile==null&&scope.row.status==0" v-permission="['GET /admin/saicgroup/bind']" type="primary" size="mini" @click="handleBind(scope.row)">预售</el-button>
          </template>
      </el-table-column>
    </el-table>

    <pagination v-show="couponsTotal>0" :total="couponsTotal" :page.sync="listCouponsQuery.page" :limit.sync="listCouponsQuery.limit" @pagination="getListCoupons" />
   </div>

      </el-tab-pane>
    </el-tabs>

   
  

    <!-- 添加或修改对话框 -->
    <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="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="sno" />
            <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="configFormVisible" width="600px">
      <el-form ref="configForm" :rules="rules" :model="configForm" status-icon label-position="left" label-width="150px" style="width: 300px; margin-left:50px;">
      
        <el-form-item label="119元保洁优惠券"> 
         <el-select v-model="configForm.couponId1" clearable style="width: 200px" class="filter-item" placeholder="请选择119元保洁优惠券">
            <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="144元品类优惠券"> 
         <el-select v-model="configForm.couponId2" clearable style="width: 200px" class="filter-item" placeholder="请选择144元品类优惠券">
            <el-option v-for="type in coupons" :key="type.id" :label="type.name" :value="type.id" />
          </el-select>
        </el-form-item> 
      </el-form> 

      <div slot="footer" class="dialog-footer">
        <el-button @click="configFormVisible = false">关闭</el-button>
        <el-button  type="primary" @click="createConfig">确定</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 { listSaicgroup, listCoupons,importStaff,saicCoupon,createSaicgroupConfig,getSaicgroupConfig,bind } from '@/api/saicgroup'  
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination 
import { formatDate } from "@/utils/date"; 

export default {
  name: 'saicgroup',
  components: { Pagination },
  filters: {  
    formatStatus(status) {
      if (status === 0) {
        return '未使用'
      } else if (status === 1) {
        return '已使用'
      } else if (status === 2){
        return '已过期'
      }
      else if (status === 4){
        return '预占'
      }
    }
  },
  data() {
    return {
      dialogBindFormVisible:false,
      dataBindForm:{
        mobile:''
      },
      listCoupons:[],
      couponsTotal:0,
      listCouponsQuery: {   
        page: 1,
        limit: 20,
        sort: 'id',
        order: 'desc'
      },
      action:"1",
      list: null,
      total: 0,
      listLoading: true,
      listQuery: { 
        mobile:'',
        page: 1,
        limit: 20,
        sort: 'create_time',
        order: 'desc'
      },
      importResult:[], 
      dataForm: {  
        file: undefined 
      }, 
      coupons:[],
      configForm:{
           couponId1:null, 
            couponId2:null 
      },
      configFormVisible:false,
      deletedOptions: [{
        value: false,
        label: '正常'
      }, {
        value: true,
        label: '删除'
      }], 
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: { 
        couponId: [{ required: true, message: '优惠券不能为空', trigger: 'blur' }],
        couponId1: [{ required: true, message: '优惠券不能为空', trigger: 'blur' }],
        couponId2: [{ required: true, message: '优惠券不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  }, 
  created() {
    this.getList() 
    saicCoupon().then(res=>{
    this.coupons = res.data.data 
    })
    //获取优惠券设置
    getSaicgroupConfig().then(res=>{ 
        if(res.data.errno==0){
            res.data.data.forEach(element => { 
                if(element.type==0) this.configForm.couponId1=element.couponId;
                if(element.type==1) this.configForm.couponId2=element.couponId;
            });
        }
         
    })
  },
  methods: {
    getList() {
      this.listLoading = true 
      listSaicgroup(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
      })
    },
    getListCoupons(){//获取上汽优惠券列表

    this.listLoading = true 
      listCoupons(this.listCouponsQuery).then(response => {
        this.listCoupons = response.data.data.list
        this.couponsTotal = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.listCoupons = []
        this.couponsTotal = 0
        this.listLoading = false
      })
    },
    handleCouponsFilter(){
      this.listCouponsQuery.page=1;
      this.getListCoupons(); 
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    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.getListCoupons();
           this.$notify.success({
                title: '成功',
                message: '绑定成功'
              })
       }).catch(res=>{

       })
      }
    ) 
        }
      })
    },
    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
    },
     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);  
     
      importStaff(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);
        });
    },
    handleConfig(){
        this.configFormVisible=true
    },
    createConfig(){
       this.$refs['configForm'].validate(valid => {
        if (valid) {
            createSaicgroupConfig(this.configForm).then(res=>{
                this.configFormVisible=false
              this.$notify.success({
                title: '成功',
                message: '优惠券设置成功'
              })

            }).catch(res=>{
                this.$notify.error({
                title: '失败',
                message: res.data.errmsg
              })
            })

        }
      })

        //createSaicgroupConfig

    }
  },
  handleTabClick(e){

  }
}
</script>
