// packageA/hotel/HotelGoodsOrder/HotelGoodsOrder.js
var app = getApp();
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    start: "",
    end: "",
    total: 1,
    order_info: {},
    start_time: "",
    end_time: "",
    night_day: "",
    name: "",
    mobil: "",
    isInvoice: false,
    invoice_type: "1",
    el_invoice: "1",
    fp_tt: "",
    company_name: "",
    sbxd: "",
    // bz: "",
    title: "",
    ORDER_URL: "plugin.hotel.frontend.hotel.goods-buy",
    SUBMIT_URL: 'plugin.hotel.frontend.hotel.create',
    id: '',
    language: '',
    //优惠券
    isShowCoupon: true,//是否显示优惠券
    popupCouponSpecs: false,
    checkCouponList: [],
    coupon_size: 0,
    use_coupon_size: 0,
    coupons: [],
    //优惠券标识
    cup_notice: true,

    checkDeductionList:[],

    // 自定义表单
    hasGoodOpenDF: false,
    orders_goods: [],
    diyShow: false,
    diyform: {
      form_id: "",
      diyform_data_id: "",
      pre_id: "",
    },
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if (options.end) {
      this.setData({
        end: options.end
      });
    }
    if (options.start) {
      this.setData({
        start: options.start
      });
    }
    if (options.id) {
      this.setData({
        id: options.id
      });
    }
    if (options.goods_id) {
      this.setData({
        goods_id: options.goods_id
      });
    }
    this.getOrerData();
    this.getCustomizeHotelHead();
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  showDiy(e) {
    if (this._findDiyForm(e.currentTarget.dataset.preid)) {
      let diyform_data_id = this._findDiyForm(e.currentTarget.dataset.preid);
      this.setData({
        "diyform.diyform_data_id": diyform_data_id,
      });
    }
    this.setData({
      diyShow: true,
    });
  },
  showDiyClose() {
    this.setData({
      diyShow: false,
    });
  },
  _initDiyForm() {
    let orders_goods = {};
    for (let j = 0; j < this.data.order_info.orders.length; j++) {
      for (let i = 0; i < this.data.order_info.orders[j].order_goods.length; i++) {
        if (this.data.order_info.orders[j].order_goods[i].diy_form) {
          let model = {};
          model.pre_id = this.data.order_info.orders[j].order_goods[i].pre_id;
          model.diyform_data_id = "";
          orders_goods[model.pre_id] = model;
        }
      }
    }
    this.setData({
      orders_goods: orders_goods,
    });
  },
  findGoodOpen() {
    for (let j = 0; j < this.data.order_info.orders.length; j++) {
      for (let i = 0; i < this.data.order_info.orders[j].order_goods.length; i++) {
        if (this.data.order_info.orders[j].order_goods[i].diy_form) {
          this.setData({
            "diyform.form_id": this.data.order_info.orders[j].order_goods[i].diy_form.form_id,
            "diyform.pre_id": this.data.order_info.orders[j].order_goods[i].pre_id,
            hasGoodOpenDF: true,
          });
          console.log("有商品开启自定义表单！！！");
        }
      }
    }
  },
  traCheckedData(data) {
    this._setDiyForm(data.detail.pre_id, data.detail.diyform_data_id);
    this.showDiyClose();
  },
  _checkDiyForm() {
    for (let i in this.data.orders_goods) {
      if (!this.data.orders_goods[i].diyform_data_id) {
        return false;
      }
    }
    return true;
  },
  _setDiyForm(pre_id, diyform_data_id) {
    for (let i in this.data.orders_goods) {
      if (this.data.orders_goods[i].pre_id == pre_id) {
        this.data.orders_goods[i].diyform_data_id = diyform_data_id;
        this.setData({
          orders_goods: this.data.orders_goods,
          "diyform.diyform_data_id": diyform_data_id,
        });
        return;
      }
    }
  },
  _findDiyForm(pre_id) {
    for (let i in this.data.orders_goods) {
      if (this.data.orders_goods[i].pre_id == pre_id) {
        return this.data.orders_goods[i].diyform_data_id;
      }
    }
    return false;
  },
  _assembleDiyForm() {
    let orders_goods = [];
    for (let i in this.data.orders_goods) {
      orders_goods.push(this.data.orders_goods[i]);
    }
    return orders_goods;
  },
  getOrerData() {
    let that = this;
    let urlStr = app.getNetAddresss(that.data.ORDER_URL);
    urlStr += '&enter_at=' + this.data.start;
    urlStr += '&leave_at=' + this.data.end;
    urlStr += '&hotel_id=' + this.data.id;
    urlStr += '&goods_id=' + this.data.goods_id;
    urlStr += '&goods_option_id=';
    urlStr += '&total=' + this.data.total;
    urlStr += '&dispatch_type_id=' + 4;
    urlStr += '&member_coupon_ids=' + this.assembleCoupons();
    urlStr += "&orders=" + JSON.stringify(this._assembleDeduction());

    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            order_info: res.data,
            title: res.data.orders[0].order_goods[0].title,
          });
          that._initDiyForm();
          that.findGoodOpen(); // 循环订单列表是否开启表单
          
          that.getTime(res.data.orders[0].hotel_order);
          that.initCoupon(res.data.discount); // 设置优惠券信息
          that.setData({
            cup_notice: true
          });
        } else {
          that.setData({
            btn_applyShow: true,
            cup_notice: true
          });
        }
      },
      fail: function(res) {
        console.log(res.msg);
      }
    });
  },
  getTime(obj) {
    let start = obj.enter_at.split(" ");
    let end = obj.leave_at.split(" ");
    let s = start[0].split("-");
    let e = end[0].split("-");
    this.setData({
      start_time: `${s[1]}月${s[2]}日`,
      end_time: `${e[1]}月${e[2]}日`
    });
    this.getDays(start[0], end[0]);
  },
  getDays(strDateStart, strDateEnd) {
    let strSeparator = "-"; //日期分隔符
    let oDate1, oDate2, iDays;
    oDate1 = strDateStart.split(strSeparator);
    oDate2 = strDateEnd.split(strSeparator);
    let strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
    let strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
    iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
    this.setData({
      night_day: iDays
    });
  },
  //获取酒店自定义字段
  getCustomizeHotelHead() {
    let that = this;
    let isQuestHotel = "";
    try {
      const value = wx.getStorageSync('customizeHotelHead');
      if (value) {
        isQuestHotel = value;
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
    if (!app._isTextEmpty(isQuestHotel)) {
      this.setData({
        PageNameList: JSON.parse(isQuestHotel)
      });
      wx.setNavigationBarTitle({
        title: this.data.PageNameList.goods_details
      });
    } else {
      let urlStr = app.getNetAddresss("plugin.hotel.frontend.hotel.get-hotel-info.get-custom-name");
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              PageNameList: res.data
            });
            wx.setNavigationBarTitle({
              title: res.data.goods_details ? res.data.goods_details : ''
            });
            try {
              wx.setStorageSync('customizeHotelHead', JSON.stringify(res.data));
            } catch (e) {console.log(e);}
          }

        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  },
  invoiceChange(e) {
    let bol = e.detail;
    this.setData({
      isInvoice: bol
    });
  },
  addTotal(e) {
    let num = e.detail;
    this.setData({
      total: num
    });
    this.getOrerData();
  },
  nameinp(e) {
    let val = e.detail.value;
    this.setData({
      name: val
    });
  },
  mobilinp(e) {
    let val = e.detail.value;
    this.setData({
      mobil: val
    });
  },
  eInvoiceChange(e) {
    let val = e.detail;
    this.setData({
      el_invoice: val
    });
  },
  typeChange(e) {
    let val = e.detail;
    this.setData({
      invoice_type: val
    });
  },
  fp_ttinp(e) {
    let val = e.detail.value;
    this.setData({
      fp_tt: val
    });
  },
  company_nameinp(e) {
    let val = e.detail.value;
    this.setData({
      company_name: val
    });
  },
  sbxdinp(e) {
    let val = e.detail.value;
    this.setData({
      sbxd: val
    });
  },
  // bzinp(e) {
  //   let val = e.detail.value;
  //   this.setData({
  //     bz: val
  //   });
  // },
  submit() {
    if (app._isTextEmpty(this.data.name)) {
      wx.showToast({
        icon: 'none',
        title: '请填写入住人',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.mobil)) {
      wx.showToast({
        icon: 'none',
        title: '请填写电话号码',
        duration: 1500
      });
      return;
    }
    if (this.data.isInvoice) {
      if (this.data.invoice_type == "1") {
        if (app._isTextEmpty(this.data.fp_tt)) {
          wx.showToast({
            icon: 'none',
            title: '请输入发票抬头',
            duration: 1500
          });
          return;
        }
      }
      if (this.data.invoice_type == "2") {
        if (app._isTextEmpty(this.data.company_name)) {
          wx.showToast({
            icon: 'none',
            title: '请填写单位名称',
            duration: 1500
          });
          return;
        }
        if (app._isTextEmpty(this.data.sbxd)) {
          wx.showToast({
            icon: 'none',
            title: '请填写纳税人识别向导',
            duration: 1500
          });
          return;
        }
      }
    }

    if (this.data.hasGoodOpenDF && !this._checkDiyForm()) {
      wx.showToast({
        icon: "none",
        title: "请先填写表单",
        duration: 1500,
      });
      return;
    }
    let that = this;
    let urlStr = app.getNetAddresss(that.data.SUBMIT_URL);
    urlStr += '&enter_at=' + this.data.start;
    urlStr += '&leave_at=' + this.data.end;
    urlStr += '&hotel_id=' + this.data.id;
    urlStr += '&dispatch_type_id=4';
    urlStr += '&member_coupon_ids=' + JSON.stringify(this.assembleCoupons());
    urlStr += '&goods=' + JSON.stringify([{
      goods_id: this.data.goods_id,
      goods_option_id: "",
      total: this.data.total
    }]);
    urlStr += '&address=' + JSON.stringify({});
    urlStr += '&orders=' + JSON.stringify(this._assembleDeduction());
    urlStr += '&mobile=' + this.data.mobil;
    urlStr += '&realname=' + this.data.name;
    urlStr += '&invoice_type=' + (Number(this.data.el_invoice == 1?'0':'1'));
    urlStr += '&rise_type=' + (Number(this.data.invoice_type == 1?'1':'0'));
    urlStr += '&call=' + (this.data.invoice_type == "1" ? this.data.fp_tt : this.data.company_name);
    urlStr += '&company_number=' + this.data.sbxd;
    if (this.data.hasGoodOpenDF) {
      //有商品开启自定义表单
      urlStr += "&order_goods=" + JSON.stringify(this._assembleDiyForm());
    }
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.navigateTo({
            url: '/packageD/buy/orderPay/orderPay?status=1&order_id=' + res.data.order_ids
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }

      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //初始化优惠券
  initCoupon(data) {
    this.setData({
      isShowCoupon: data.whether_show_coupon == '1' ? true : false
    });
    let coupon = data.member_coupons;
    if (coupon != undefined && coupon != "" && coupon != null) {
      this.setData({
        coupon_size: coupon.length
      });
    }
    this.setData({
      coupons: coupon
    });
  },
  //优惠券
  showCoupon() {
    if (this.data.coupon_size == 0) {
      wx.showToast({
        icon: 'none',
        title: '暂无优惠券使用',
        duration: 1500
      });
      return;
    }
    this.setData({
      popupCouponSpecs: true
    });
  },
  //关闭优惠卷
  couponclose() {
    this.setData({
      popupCouponSpecs: false
    });
  },
  //选择优惠券
  selectCoupon(e) {
    let couponBol = e.detail;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    this.setData({
      ["coupons[" + index + "].checked"]: couponBol
    });
    this.screenCoupon(couponBol, item);
    this.setData({
      use_coupon_size: this.data.checkCouponList.length
    });
    // 重新计算
    this.getOrerData();
  },
  //筛选数据优惠券状态
  screenCoupon(couponBol, valObj) {
    var tarValue = valObj;
    if (couponBol) { //选中添加
      this.setData({
        cup_notice: false
      });
      if (this.data.checkCouponList.length > 0) {
        for (let i = 0; i < this.data.checkCouponList.length; i++) {
          if (this.data.checkCouponList[i].id == tarValue.id) {
            let checkCouponList = this.data.checkCouponList;
            checkCouponList.splice(i, 1);
            this.setData({
              checkCouponList: checkCouponList
            });
          }
        }
        let checkCouponList = this.data.checkCouponList;
        checkCouponList.push(tarValue);
        this.setData({
          checkCouponList: checkCouponList
        });
      } else {
        let checkCouponList = this.data.checkCouponList;
        checkCouponList.push(tarValue);
        this.setData({
          checkCouponList: checkCouponList
        });
      }
    } else { //取消选中
      this.setData({
        cup_notice: true
      });
      if (this.data.checkCouponList.length > 0) {
        for (let i = 0; i < this.data.checkCouponList.length; i++) {
          if (this.data.checkCouponList[i].id == tarValue.id) {
            let checkCouponList = this.data.checkCouponList;
            checkCouponList.splice(i, 1);
            this.setData({
              checkCouponList: checkCouponList
            });
          }
        }
      }
    }
  },
  //组装优惠券json信息
  assembleCoupons() {
    let coupons = [];
    for (let i = 0; i < this.data.checkCouponList.length; i++) {
      coupons.push(this.data.checkCouponList[i].id);
    }
    return coupons;
  },
  //抵扣选择响应
  discountHandle(e) {
    let dischecked = e.detail;
    let dindex = e.currentTarget.dataset.dindex;
    let orindex = 0;

    if (Object.prototype.toString.call(this.data.order_info.orders[orindex].order_deductions) == '[object Object]') {
      this.setData({
        ["order_info.orders[" + orindex + "]" + ".order_deductions." + dindex + ".checked"]: dischecked
      });
    } else if (Object.prototype.toString.call(this.data.order_info.orders[orindex].order_deductions) == '[object Array]') {
      this.setData({
        ["order_info.orders[" + orindex + "]" + ".order_deductions[" + dindex + "]checked"]: dischecked
      });
    }
    this._screenDiscount(this.data.order_info.orders[orindex], this.data.order_info.orders[orindex].order_deductions[dindex]);
    //重新计算
    this.getOrerData();
  },
  //筛选抵扣
  _screenDiscount(item, value) {
    //临时数据
    let _deductionItem = {};
    let tempDeduction_ids = [];
    let checkDeductionList = [];
    if (value.checked) {
      //选中添加
      if (this.data.checkDeductionList.length > 0) {
        for (let i = 0; i < this.data.checkDeductionList.length; i++) {
          if (this.data.checkDeductionList[i].pre_id == item.pre_id) {
            //先获取回来
            if (app._isTextEmpty(this.data.checkDeductionList[i].deduction_ids)) {
              tempDeduction_ids = [];
            } else {
              tempDeduction_ids = this.data.checkDeductionList[i].deduction_ids;
            }
            checkDeductionList = this.data.checkDeductionList;
            checkDeductionList.splice(i, 1);
            this.setData({
              checkDeductionList: checkDeductionList
            });
            break;
          }
        }

        if (tempDeduction_ids.length > 0) {

          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }

          tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });

        } else {

          tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });


        }


      } else {

        if (tempDeduction_ids.length > 0) {
          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }

          tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });

        } else {
          tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });

        }

      }

    } else { //取消选中
      if (this.data.checkDeductionList.length > 0) {
        for (let i = 0; i < this.data.checkDeductionList.length; i++) {
          if (this.data.checkDeductionList[i].pre_id == item.pre_id) {
            //先获取回来
            if (app._isTextEmpty(this.data.checkDeductionList[i].deduction_ids)) {
              tempDeduction_ids = [];
            } else {
              tempDeduction_ids = this.data.checkDeductionList[i].deduction_ids;
            }
            let checkDeductionList = this.data.checkDeductionList;
            checkDeductionList.splice(i, 1);
            this.setData({
              checkDeductionList: checkDeductionList
            });
            break;
          }
        }


        if (tempDeduction_ids.length > 0) {
          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });

        } else {
          //tempDeduction_ids.push(value.code);
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        }

      } else {
        if (tempDeduction_ids.length > 0) {
          for (let j = 0; j < tempDeduction_ids.length; j++) {
            if (tempDeduction_ids[j] == value.code) {
              tempDeduction_ids.splice(j, 1);
            }
          }

          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        } else {
          _deductionItem.deduction_ids = tempDeduction_ids;
          _deductionItem.pre_id = item.pre_id;
          checkDeductionList.push(_deductionItem);
          this.setData({
            checkDeductionList: checkDeductionList
          });
        }

      }
    }

  },
  //组装优惠抵扣信息
  _assembleDeduction() {
    let deductions = [];
    for (let i = 0; i < this.data.checkDeductionList.length; i++) {
      deductions.push(this.data.checkDeductionList[i]);
    }
    return deductions;
  },
});
