<template>
  <div class="p_all_20">
    <div>
        <div class="tit">{{isNewCoupon? "新建":"编辑"}}{{typeVal==4?'新品':'单品'}}优惠券</div>
        <el-form
          class="form"
          :model="form"
          label-width="120px"
          ref="ruleForm"
          :rules="rules"
        >
          <el-form-item
            label="优惠券类型："
            prop="actType"
          >
            <el-select
              v-model="form.actType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in couponType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="发放总量："
            prop="totalNum"
          >
          <el-row>
            <el-col :span="5">
                <!-- <el-input
                  v-model="form.totalNum"
                  type="number"
                  placeholder="最大10000"
                ></el-input> -->
                <el-input-number class="input-number" v-model="form.totalNum" :min="1" :max="10000" placeholder="最大10000"></el-input-number>
              </el-col>
              <el-col :span="8">
                &nbsp;张<span class="tips">(最大设置10000张)</span>
              </el-col>
          </el-row>
   

          </el-form-item>

          <el-form-item
            label="品牌"
          >
            <span>{{form.brandName}}</span>
            <!-- <el-select
              v-model="form.brandId"
              placeholder="请选择"
              @change="getList"
            >
              <el-option
                v-for="item in brandList"
                :key="item.brandId"
                :label="item.brandName"
                :value="item.brandId"
              >
              </el-option>
            </el-select> -->
          </el-form-item>

          <el-form-item
            label="适用商品："
            prop="productIds"
          >
            <div>
              <div class="table-tit">选择商品</div>
              <div class="table-box">
                <div class="search-box">
                  <el-col :span="8">
                    <el-input
                      v-model="searchKey"
                      class="search-input"
                      placeholder="请输入商品名称"
                    ></el-input>
                  </el-col>
                  <el-col :span="2">
                    <el-button
                      type="primary"
                      class="search-btn"
                      @click="handleSearch"
                    >搜索</el-button>
                  </el-col>
                </div>
                <div>
                  <template>
                    <el-table
                      :data="tableData"
                      ref="multipleTable"
                      border
                      style="width: 100%"
                      :row-key="getProductId"
                      @select="onSelectOne"
                      @select-all="onSelectAll"
                      @selection-change="handleSelectionChange"
                    >
                      <!-- <%--       prop="available"
                                        reserve-selection="true"
								
                                        v-modle="form.products"--%> -->

                      <el-table-column
                        :reserve-selection="true"
                        type="selection"
                        align="center"
                        width="55"
                      >
                      </el-table-column>
                      <!-- <el-table-column
                                    prop="selected"
                                    
                                    width="">
                                    </el-table-column> -->
                      <el-table-column
                        prop="productImg"
                        align="center"
                        label="主图"
                        width="80"
                      >
                        <template slot-scope="scope">
                          <img
                            :src="scope.row.productImg + '?x-oss-process=image/format,jpg/resize,h_100,w_100'"
                            alt=""
                          >
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="productName"
                        align="center"
                        label="商品名称"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="stock"
                        align="center"
                        label="库存"
                        width="100"
                      >
                      </el-table-column>
                    </el-table>
                  </template>
                  <el-pagination
                    class="page"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal"
                  >
                  </el-pagination>
                </div>
              </div>
            </div>
            <!-- <div
              v-else
              style="color:#ff6600;"
            >请先选择品牌</div> -->
          </el-form-item>

          <el-form-item
            label="优惠力度："
            prop="discount"
          >
            <el-col
              :span="1"
              style="text-align: right"
            >打&nbsp;</el-col>
            <el-col :span="5">
              <!-- <el-input
                v-model="form.discount"
                type="number"
                placeholder="9<=10"
              ></el-input> -->
              <el-input-number class="input-number" v-model="form.discount" :min="9" :max="10" :step="0.1" placeholder="9<=10"></el-input-number>
            </el-col>
            <el-col :span="1">&nbsp;折</el-col>
            <el-col :span="8">
              <span class="tips">(设置范围9 ~ 10折)</span>
            </el-col>
          </el-form-item>
          <!-- <%--<el-form-item label="*是否叠加：">
                    <el-checkbox v-model="form.useVipDiscount" :true-label="1" :false-label="0">可以和铂金商品折扣叠加使用</el-checkbox>                 
                </el-form-item>--%> -->

          <el-form-item
            label="有效期："
            prop="date"
          >
            <!-- <%--//为了解决编辑时，选择日期不会回显出来，重新定义了另一个this.date--%> -->
            <!-- <el-input
              v-model="form.date"
              v-show="false"
            ></el-input> -->
            <el-date-picker
              v-model="date"
              type="daterange"
              range-separator="-"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="dateFocus"
              :clearable="false"
            >
            </el-date-picker>

            <span class="tips">(开始日期大于当前日期，时间跨度小于等于6个月)</span>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="handleAddCoupon('ruleForm')"
            >立即创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
            <el-button @click="goback()">返回</el-button>

          </el-form-item>
        </el-form>
      </div>
    </div>

</template>

<script>
import {  _getStorage } from "@/utils/utils";
export default {
  name: "addcoupon",
  data() {
     var num = (rule, value, callback) => {
    if(!value){
      return callback(new Error('不能为空'));
    }else{
      if (value > 10000) {
        callback("不能大于10000");
      } else if (value < 1) {
        callback("不能小于1");
      } else {
         callback();
      }
    }
      
    };
    var count = (rule, value, callback) => {
      if(!value){
      return callback(new Error('不能为空'));
    }else{
      if (value > 10) {
        callback("不能大于10");
      } else if (value < 7) {
        callback("不能小于9");
      } else {
        return callback();
      }
    }
      
    };
    var dateRule = (rule, value, callback) => {
        if (this.date.length==0) {
          callback(new Error('请选择有效期'));
        } else {
          callback();
        }
      };
    var datePids = (rule, value, callback) => {
        if (this.form.productIds.length==0) {
          callback(new Error('请选择商品'));
        } else {
          callback();
        }
      };
    return {
      searchKey: "",
      couponType: [
        {
          label: "新品券",
          value: 4
        },
        {
          label: "单品券",
          value: 3
        }
      ],
      date: [], //选择日期
      //brandId: '',
      brandList: [],
      form: {
        actType:4,
        // type: 0,
        totalNum: "",
        productIds:[],
        // products: [],
        discount: "",
        useVipDiscount: 0,
        couponEffectDate: "",
        couponExpireDate: "",
        // data:"",
        brandId: "",
        brandName: ""
      },
      tableData: [],
      proed: [], //编辑时默认选中商品id
      proListAll: [], //编辑时获取品牌对应的所有id
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0,
      typeVal: 4,
      isNewCoupon: 1,
      actId: "",
      multipleSelection: [],
      rules: {
        actType: [{ required: true, message: "请选择类型", trigger: "blur" }],
        totalNum: [
          { required: true, message: "发放总量不能为空", trigger: "blur" },
          { validator: num, trigger: "blur" }
        ],
        discount: [
          { required: true, message: "不能为空", trigger: "blur" },

          { validator: count, trigger: "blur" }
        ],
        date: [
          { required: true,validator: dateRule, trigger: 'change'}
        ],
        brandName: [
          { required: true, message: "品牌不能为空11", trigger: "blur" }
        ],
        brandId: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
        productIds: [{  required: true ,validator: datePids, trigger: "change"}]
      }
    };
  },
  mounted() {
    let { brandId,brandName } = _getStorage('info');
    this.form.brandId=brandId;
    this.form.brandName=brandName;
     this.getPublicBrands();
     let id = this.$route.query.actId;
     let typeVal = this.$route.query.typeVal;
     this.form.actType = +typeVal;
     this.typeVal = +typeVal;
  
    if (id) {
      this.isNewCoupon = 0;
      this.actId = id;
    }
    this.getList(id);
    
  },

  methods: {
    goback(){
      this.$router.back()
    },
    getProductId(row) {
      return row.productId;
    },
    onSelectAll(sel) {
      var arr0 = [];
      for (let ii = 0; ii < sel.length; ii++) {
        arr0.push(sel[ii]["productId"]);
      }
      this.proed = arr0;
      this.multipleSelection = arr0;
    },

    onSelectOne(sel, row) {
      var arr0 = [];
      for (let ii = 0; ii < sel.length; ii++) {
        arr0.push(sel[ii]["productId"]);
      }
      this.proed = arr0;
      this.multipleSelection = arr0;
    },
    dateFocus(e) {
      this.form.couponEffectDate =e[0];
      this.form.couponExpireDate =e[1];
    },
    addFormProduct() {
      // this.form.productIds = ["1"]
    },
    getInit() {
      this.proed.forEach((item) => {
        this.$refs.multipleTable.toggleRowSelection(item, true);
      })
      this.proed.forEach((n, nd) => {
        var aaa = [];

        this.proListAll.forEach((x, xd) => {
          if (n.indexOf(x) != -1) {
            aaa.push(xd);
            this.$refs.multipleTable.toggleRowSelection(
              this.tableData[xd],
              true
            );
          }
        });
      });
    },
    getPublicBrands(){
      this.$axios.get("/public/brands",{
        params:{
          type:1
        }
      }).then(res=>{
         if (res.data && res.data.code == 200) {
            this.brandList = res.data.data;
          }
      })
    },
    getEditInfo(id) {
      var that = this;
      var promise = new Promise((resolve, reject) => {
        this.$axios.get("/coupons/queryByActId",{
          params:{
            actId:id
          }
        }).then(res => {
          if (res.data && res.data.code == 200) {
            var res_data = res.data.data;
            this.form = {
              actId: res_data.actId,
              actType: res_data.type,
              brandId: res_data.brandId,
              brandName: res_data.brandName,
              totalNum: res_data.totalNum,
              discount: res_data.discount,
              useVipDiscount: res_data.useVipDiscount,
              couponEffectDate: res_data.couponEffectDate,
              couponExpireDate: res_data.couponExpireDate
            };
            
            // this.form.productIds =[];
            // this.tableData = [];
            this.date = [res_data.couponEffectDate, res_data.couponExpireDate];
            // this.tableData = res_data.products;
            if (res_data.products.length) {
              var arr = [];
              for (let ii = 0; ii < res_data.products.length; ii++) {
                arr.push(res_data.products[ii]["productId"]);
              }
              that.proed = arr;
              // this.multipleSelection = arr;
            }
            this.getInit();
          }
          resolve(res);

          //console.dir(res)
        });
      });
      return promise;
    },

    getList(id) {
      var that = this;
      // that.form.brandId = e ? e : that.form.brandId;
      // if (that.form.brandId && that.actId) {
      //   this.$refs.multipleTable.clearSelection();
      //   this.multipleSelection = [];
      // }

      this.$axios
        .get("/coupons/products", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            productName: this.searchKey,
            brandId: this.form.brandId,
            actId: this.actId
          }
        })
        .then(function(res) {
          // console.dir(res)
          if (res.data && res.data.code == 200) {
            var data = res.data.data;
            that.tableData = data.list;
            that.pageTotal = parseInt(data.total);
            if (that.actId) {
              if (data.list.length) {
                var pro = [];
                for (let ii = 0; ii < data.list.length; ii++) {
                  pro.push(data.list[ii]["productId"]);
                }
                //that.proListAll = that.proListAll ? that.proListAll.concat(pro) : pro
                that.proListAll = pro;
              }
            }
          }
        })
        .then(() => {
          if (id) {
            this.getEditInfo(id)
          }
          
          // if (this.pageNum == 1) {
          //   this.proListAll = [];
          // }
        })
        .catch(function(res) {
          console.log(res);
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$refs.multipleTable.clearSelection();
      this.form.productIds=[];
      this.date = [];
      this.form.couponEffectDate='';
      this.form.couponExpireDate='';
      console.log(this.form)
    },
    handleSearch() {
      this.pageNum = 1;
      this.productName = this.searchKey;
      this.getList();
    },
    handleSizeChange: function(e) {
      var that = this;
      that.pageSize = e;
      that.getList();
    },
    handleCurrentChange: function(e) {
      var that = this;
      that.pageNum = e;
      that.getList();
    },
    handleAddCoupon(ruleForm) {
      var _this = this;
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          if (this.isNewCoupon == 0) {
            // 编辑
            this.$axios
              .put("/coupons/updateCoupon", _this.form)
              .then(res => {
                if (res.data && res.data.code == 200) {
                  this.$message.success(res.data.message);
                     this.$router.push("/marketing/coupon")
                } else {
                  this.$message.error(res.data.message);
                }
              })
              .catch(res => {
                console.log(res);
              });
          } else {
            this.$axios
              .post("/coupons/createCoupon", this.form)
              .then(res => {
                if (res.data && res.data.code == 200) {
                  this.$message.success(res.data.message);
                  this.$router.push("/marketing/coupon")
                } else {
                  this.$message.error(res.data.message);
                }
              })
              .catch(res => {
                console.log(res);
              });
          }
        } else {
          this.$message.error("请正确填写表单信息");
        }
      });
    },

    handleSelectionChange(e) {
      // 选中product id 放入表单
      var arrys = [];
      e.map(i => {
        arrys.push(i.productId);
      });
      if (arrys.length) {
        this.multipleSelection = arrys;
      }
      this.form.productIds = this.multipleSelection;
    }
  },
  components: {
    // 传入组件
  }
};
</script>

<style lang="scss" scoped>
.input-number{
  width: 100%;
}
.big-tit {
  padding: 10px;
  font-size: 16px;
}
.tit {
  // padding: 20px 10px 0 20px;
  font-size: 16px;
  color: #6b6b6b;
  margin-bottom: 20px;
}
.tit:before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 24px;
  background: #FF6800;
  border-radius: 2px;
  vertical-align: middle;
  margin-right: 5px;
}
.table-box {
  border: 1px solid #dadada;
  padding: 10px;
  text-align: center;
}
.table-tit {
  color: #ff6800;
}
.layui-table th {
  text-align: center;
}
.table-box img {
  width: 30px;
  height: 30px;
}
[type="checkbox"] {
  width: 15px;
  height: 15px;
  vertical-align: middle;
}
.layui-input-block span {
  vertical-align: middle;
}
.layui-input-block {
  line-height: 36px;
}
.form {
  width: 900px;
  padding-left: 20px;
}
.search-box {
  margin-bottom: 10px;
  overflow: hidden;
}
.search-input input {
  border: 1px solid #ffebdd;
  // border-radius: 50px 0 0 50px;
}
.search-btn {
  background: #ff6800;
  border: 1px solid #ff6800;
  // border-radius: 0 50px 50px 0;
}
.search-btn:hover {
  background: #f46e11;
  border: 1px solid #f46e11;
}
.page {
  margin-top: 15px;
  text-align: center;
}
.selected {
  background: transparent;
}
.tips {
  color: red;
  padding-left: 10px;
}
</style>
