<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="优惠券名称 ">
        <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="优惠券类别">
        <el-select v-model="queryParams.categoryId" placeholder="请选择优惠券类别" clearable @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in couCategoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable @keyup.enter.native="handleQuery">
          <el-option label="生效中" value="1"></el-option>
          <el-option label="未生效" value="2"></el-option>          
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" v-hasPermi="['coupon:coupon:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['coupon:coupon:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="giveClick"
          v-hasPermi="['coupon:coupon:add']">赠送</el-button>
      </el-col>
   </el-row>

    <el-table v-loading="loading" :data="couponList">     
      <el-table-column label="优惠券名称" align="center" prop="name">       
        <template slot-scope="scope">
          <a @click="handleUpdate(scope.row)" style="color: blue">{{ scope.row.name }}</a>
        </template>     
      </el-table-column>
      <el-table-column label="类别" align="center" prop="typeDesc" />
      <el-table-column label="券价值" align="center">
        <template slot-scope="scope">
          {{ scope.row.ruleDesc }}{{scope.row.ruleName}}
        </template> 
      </el-table-column>
      <el-table-column label="使用范围" align="center">
        <template slot-scope="scope">
          <p v-show="scope.row.goodLimitDesc!=''">{{scope.row.goodLimitDesc}}</p>
          <p v-show="scope.row.areaLimitDesc!=''">{{scope.row.areaLimitDesc}}</p>   
        </template>
      </el-table-column>
      <el-table-column label="时效" align="center" width="300">
        <template slot-scope="scope">
          <p>{{formateTime(scope.row.useStartTime)}}—{{formateTime(scope.row.useEndTime)}}</p>
          <p v-show="scope.row.relativeTime!=''">{{scope.row.relativeTime}}日内有效</p>         
        </template>
      </el-table-column>      
      <el-table-column label="状态" align="center" prop="stateDesc"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-show="scope.row.state == 1" size="mini" type="text" icon="el-icon-edit" @click="handleStatus(scope.row,'1')"
            v-hasPermi="['coupon:coupon:restart']">下线</el-button>
          <el-button v-show="scope.row.state == 2" size="mini" type="text" icon="el-icon-edit" @click="handleStatus(scope.row,'2')"
            v-hasPermi="['coupon:coupon:stop']">上线</el-button> 
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['coupon:coupon:remove']">删除</el-button>     
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body class="dialogClass">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-form-item label="优惠券名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入优惠券名称" minlength="1" maxlength="100"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="券类别" prop="categoryId" >
              <el-select v-model="form.categoryId" placeholder="请选择" @change="selectChange" class="width">
                <el-option
                  v-for="item in couCategoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <div style="margin-left: 140px;">
              <el-form-item label="券价值">
                <el-radio-group v-model="type" disabled style="margin-left: 6px;">
                  <el-radio :label="1">抵扣</el-radio>
                  <el-radio :label="2">折扣</el-radio>
                  <el-radio :label="3" style="margin-left: 13px;">免单</el-radio>
                </el-radio-group>
              </el-form-item>
              <div style="margin-left: 73px;">
                <div class="marginLeft10">
                  <span>立减</span><el-input v-model="liJian" class="inputCalss" :disabled="type=='2' || type=='3'"/><span class="spanClass">元</span>
                  <el-radio-group v-model="firstRadioValue" class="marginLeft10">
                    <el-radio :label="1" class="marginLeft10" :disabled="type=='2'">无门槛</el-radio>
                    <el-radio :label="2" :disabled="type=='2'">满<el-input v-model="priceLimit" class="inputCalss" :disabled="type=='2'"/><span class="spanClass">元</span></el-radio>
                  </el-radio-group>
                </div>
                <div style="margin-left: 36px;margin-top: 10px;" >
                  <el-input v-model="jiZhe" class="inputCalss" :disabled="type=='1' || type=='3'"/><span class="spanClass" >折</span>
                  <el-radio-group v-model="twoRadioValue" class="marginLeft10">
                    <el-radio :label="3" class="marginLeft10" :disabled="type=='1'">单杯</el-radio>
                    <el-radio :label="4" style="margin-left: 14px;" :disabled="type=='1' || type=='3'">整单</el-radio>
                  </el-radio-group>
                </div>  
              </div> 
            </div>            
          </el-col>
          <el-col :span="7">
            <el-form-item label="User可领次数" label-width="110px" prop="userNumber" style="margin-left: 15px;">
              <el-radio-group v-model="form.userNumber" >
                <el-radio :label="1" >
                  <span>每</span><el-input class="inputCalss" v-model="form.daysLimit" :disabled="form.userNumber=='2'"/><span class="spanClass">天</span>
                  <el-input class="inputCalss" v-model="form.userLimit" :disabled="form.userNumber=='2'"/><span class="spanClass">次</span>
                </el-radio>
                <el-radio :label="2" style="margin-top: 10px;">无限制</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 8px;">
          <el-col :span="9">
            <el-form-item label="优惠券绝对有效时间" prop="times">
              <el-date-picker
                v-model="form.times"
                type="datetimerange"
                range-separator="至"
                start-placeholder="请选择开始日期"
                end-placeholder="请选择结束日期" value-format="yyyy-MM-dd HH:mm:ss" class="width"/>
            </el-form-item>            
          </el-col>
          <el-col :span="8">
            <el-form-item label="领取后相对有效时间" label-width="190px">
             <el-input class="inputCalss" v-model="form.relativeTime"/><span class="spanClass">天</span>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="优惠券可领取时间" >
              <el-date-picker v-model="form.receivableTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择领取日期" style="width: 205px;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="适用范围">
              <el-cascader :options="shopRangeList" v-model="shopRange" clearable placeholder="请选择使用商品范围" class="width" :props="{ multiple: true}" collapse-tags :show-all-levels="false"/>
              <el-cascader ref="area" :options="shopAreaTreeList" v-model="storesRange" :props="{ multiple: true  }" clearable collapse-tags placeholder="请选择地区门店"  
                :show-all-levels="false" style="margin-left:55px;width:300px;" />
              <el-select v-model="form.weekLimit" placeholder="请选择可用日期" multiple collapse-tags style="margin-left: 130px;width: 328px;" clearable>
                <el-option
                  v-for="item in weekList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="短信通知" prop="sendMsgTag">
          <div style="display: flex;">
            <div>
              <el-radio-group v-model="form.sendMsgTag" @change="changeMsg">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>             
            </div>
            <div style="margin-left: 75px;">
              <el-select v-model="form.msgId" style="width: 1000px;" :disabled="selectMess">
                <el-option value="1" label="模板1" ></el-option>
              </el-select>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-hasPermi="['coupon:coupon:edit']">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <GiveCoupon ref="giveCoupon"></GiveCoupon>
  </div>
</template>

<script>
import {addCoupon,updateCoupon,listCoupon,offlineCoupon,onlineCoupon,delCoupon,getCouponDetail} from "@/api/coupon/coupon";
import {getCouCategoryList} from "@/api/coupon/couponType";
import GiveCoupon from './giveCoupon.vue';
import {listClass} from "@/api/system/category";
import {listSpu} from "@/api/system/goods";
import {listShop,getShopAreaTree} from "@/api/system/shop";
import piovince from '@/utils/piovince'
export default {
  name: "Class",
  components: { GiveCoupon},
  data() {
    return {
      piovince,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        state: null,
        categoryId:null
      },
      // 表单参数
      form: {
        categoryIds:[],
        goodsIds:[],
        sendMsgTag:2,
        shopIds:[],
        area:[],
        city:[],
        province:[]
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        categoryId: [{ required: true, message: "不能为空", trigger: "blur" }],
        userNumber: [{ required: true, message: "不能为空", trigger: "change" }],
        times: [{required: true, message: "不能为空", trigger: "change" }],
        sendMsgTag: [{required: true, message: "不能为空", trigger: "change" }]
      },
      couCategoryList: [],
      weekList:[{
        value: 2,
        label: '星期一'
        }, {
        value: 3,
        label: '星期二'
        }, {
        value: 4,
        label: '星期三'
        }, {
        value: 5,
        label: '星期四'
        }, {
        value: 6,
        label: '星期五'
        }, {
        value: 7,
        label: '星期六'
        }, {
        value: 1,
        label: '星期日'
      }],
      type:"",
      liJian:"",
      firstRadioValue:"",
      twoRadioValue:"",
      priceLimit:"",
      jiZhe:"",
      shopRangeList:[],
      categoryList:[],
      shopList:[],
      shopRange:[],
      cityList:[],
      storesRange:[],
      selectMess:true,
      shopAreaTreeList:[]
    };
  },
  created() {
    this.getList();
    this.getCategoryList();
    this.getcouCategoryList();
    this.getShopList();
    this.getCityList();
  },
  methods: {
    formateTime(val){
      let index =val.lastIndexOf(":");
      val=val.substring(0, index );
      return val;
    },
    /** 查询商品分类列表 */
    getCategoryList() {
      listClass({pageNum: 1,pageSize: 10000,state:1}).then((response) => {
        this.categoryList = response.rows;   
      });
    },
    /** 查询商品列表 */
    getShopList() {
      listSpu({pageNum: 1,pageSize: 10000,state:3}).then((response) => {
        this.shopList = response.rows;
      });
    },
    /** 查询店铺列表 */
    getCityList() {
      listShop({pageNum: 1,pageSize: 10000,state:1}).then((response) => {
        this.cityList = response.rows; 
      });
    },
    // 封装商品范围下拉数据
    getShopRangeList(){
      let catList=[];
      let shList=[];
      if(this.categoryList.length>0){
        for(let i=0;i<this.categoryList.length;i++){
          let categoryObj={}
          categoryObj.value=this.categoryList[i].id;
          categoryObj.label=this.categoryList[i].name;
          catList.push(categoryObj);
        }
      }
      if(this.shopList.length>0){
        for(let i=0;i<this.shopList.length;i++){
          let shObj={}
          shObj.value=this.shopList[i].id;
          shObj.label=this.shopList[i].name;
          shList.push(shObj);
        }
      }      
      this.shopRangeList=[{value:0,label:"全品类"},{value:1,label:"分品类",children:catList},{value:2,label:"分商品",children:shList}]
    },
    //把省市区封装成map集合
    getMap(){
      let list=new Map();
      let piovinceList=this.piovince;      
      for(let i=0;i<piovinceList.length;i++){
        list.set(piovinceList[i].value,piovinceList[i].label);
        if(piovinceList[i].children.length>0){
          let firstList=piovinceList[i].children;
          for(let j=0;j<firstList.length;j++){
            list.set(firstList[j].value,firstList[j].label);
            if(firstList[j].children.length>0){
              let twoList=firstList[j].children;
              for(let t=0;t<twoList.length;t++){
                list.set(twoList[t].value,twoList[t].label);
              }
            }
          }
        }
      }
      return list;
    },
    changeMsg(val){
      this.selectMess=false;
      if(val==1){
        this.selectMess=true;
        this.form.msgId="";
      }
    },
    /** 查询券类别列表 */
    getcouCategoryList() {      
      getCouCategoryList({state:1,pageNum:1,pageSize:10000}).then((response) => {
        this.couCategoryList = response.rows;
      });
    },
    selectChange(val){
      this.liJian="";
      this.firstRadioValue="";
      this.twoRadioValue="";
      this.priceLimit="";
      this.jiZhe="";
      for(let i=0;i<this.couCategoryList.length;i++){
        if(this.couCategoryList[i].id==val){
          this.type=this.couCategoryList[i].type;
          if(this.type=="1"){
            this.firstRadioValue=1;
          }else{
            this.firstRadioValue=1;
            this.twoRadioValue=3; 
          }                  
        }
      }
    },
    giveClick(){
      this.$refs.giveCoupon.getList();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then((response) => {
        if(response.code==200){
          this.couponList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.name=null;
      this.queryParams.state=null;
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.form.sendMsgTag=2
      this.open = true;
      this.title = "新增优惠券";            
      this.getShopRangeList();
      this.getShopAreaTree();
    },
    /** 上线、下线按钮操作 */
    handleStatus(row,tag) {
      let mess="";    
      if(tag=='1'){
        mess="下线";      
      }else if(tag=='2'){
        mess="上线";        
      }
      this.$modal
        .confirm('是否确认' + mess + '该数据项？')
        .then(function () {
          if(tag=="1"){
            return offlineCoupon(row.id);
          }else if(tag=="2"){
            return onlineCoupon(row.id);
          }
        }).then((response) => {
          if(response.code="200"){
            this.getList();
            this.$modal.msgSuccess('' + mess + '成功');
          }          
        })
        .catch(() => { });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getClass(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改优惠券";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if(this.type=="1"){            
            if(this.liJian==""){
              this.$message.error("立减输入框必填!");
              return;
            }            
            this.form.priceDiscount=this.liJian            
          }else if(this.type=="2"){
            if(this.jiZhe==""){
              this.$message.error("折输入框必填!");
              return;
            }
            if(this.twoRadioValue=="3"){
              this.form.orderLimit=true;
            }else{
              this.form.orderLimit=false;
            }
            this.form.priceLimit=this.jiZhe;
          }else if(this.type=="3"){
            if(this.firstRadioValue=="2"){
              if(this.priceLimit==""){
                this.$message.error("满X元输入框必填!");
                return;
              }
            }
            this.form.orderLimit=true;
          }
          if(this.firstRadioValue=="2"){
            if(this.priceLimit==""){
              this.$message.error("满X元输入框必填!");
              return;
            }
            this.form.priceLimit=this.priceLimit;
          }else if(this.firstRadioValue=="1"){
            this.form.priceLimit=0;
          }
          if(this.form.userNumber=="2"){
            this.form.daysLimit=0;
            this.form.userLimit=0;
          }else{            
            this.form.daysLimit="";
            this.form.userLimit="";
          }
          if(this.form.times.length>0){
            this.form.useStartTime=this.form.times[0];
            this.form.useEndTime=this.form.times[1]
          }
          if(this.shopRange.length>0){
            let cateList=[];
            let goodSList=[];
            for(let i=0;i<this.shopRange.length;i++){             
              if(this.shopRange[i][0]==0){
                cateList.push(0);
              }else if(this.shopRange[i][0]==1){                
                cateList.push(this.shopRange[i][1]);                
              }else if(this.shopRange[i][0]==2){
                goodSList.push(this.shopRange[i][1]);
              }
            }
            this.form.categoryIds=cateList;
            this.form.goodsIds=goodSList;            
          }
          if(this.storesRange.length>0){
            let proList=[];
            let shopIdList=[];
            let areaIdList=[];
            let cityIdList=[];
            if(this.storesRange[0][0]==0){
              proList.push(0);
            }else{
              let areaNode=this.$refs["area"].getCheckedNodes();
              areaNode=areaNode.filter(item => !(item.parent && item.parent.checked));               
              for(let j=0;j<areaNode.length;j++){
                if(areaNode[j].level==5){
                  shopIdList.push(areaNode[j].value)
                }else if(areaNode[j].level==4){
                  areaIdList.push(areaNode[j].value);
                }else if(areaNode[j].level==3){
                  cityIdList.push(areaNode[j].value);
                }else if(areaNode[j].level==2){
                  proList.push(areaNode[j].value);
                }else if(areaNode[j].level==1){
                   proList.push(0);
                } 
              } 
            }
            this.form.shopIds=shopIdList;
            this.form.area=areaIdList; 
            this.form.city=cityIdList;
            this.form.province=proList;         
          }
          if(this.form.sendMsgTag==1){
            this.form.sendMsg=true;
          }else if(this.form.sendMsgTag==2){
            this.form.sendMsg=false;
          }
          console.log("this.form",this.form);
          if (this.form.id != null) {            
            updateCoupon(this.form).then((response) => {
              if(response.code==200){
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCoupon(this.form).then((response) => {
              if(response.code==200){
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {  
      this.$modal
        .confirm('是否确定删除?')
        .then(function () {
          return delCoupon(row.id);
        })
        .then((response) => {          
         if(response.code=="200"){
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }
        })
      .catch(() => { });
    },
    //获取省市区门店
    getShopAreaTree(){
      let list=this.getMap();
      getShopAreaTree().then((response) => {
        if(response.code==200){
          let treeList=response.data;          
          //填充省市区的label值
          for(let i=0;i<treeList.length;i++){
            treeList[i].label=list.get(treeList[i].value);
            if(treeList[i].children.length>0){
              let firChildrenList=treeList[i].children;
              for(let j=0;j<firChildrenList.length;j++){
                firChildrenList[j].label=list.get(firChildrenList[j].value);
                if(firChildrenList[j].children.length>0){
                  let childrenList=firChildrenList[j].children;
                  for(let s=0;s<childrenList.length;s++){
                    childrenList[s].label=list.get(childrenList[s].value);
                  }
                }
              }
            }
          }
          this.shopAreaTreeList=[{value:"0",label:"全国通用"},{value:"1",label:"限定区域",children:treeList}]
        }
      });      
    }
  },
};
</script>

<style lang="scss" >
.dialogClass .spanClass{
  margin-left: 6px;
}
.dialogClass .inputCalss{
  width:70px;
  margin-left: 10px;
}
.dialogClass .el-radio__label {
  padding-left: 3px !important;
}
.dialogClass .marginLeft10 {
  padding-left: 10px;
}
.dialogClass .width {
  width: 355px;
}

</style>
