var util = require('../../utils/util.js');
var app = getApp()

Page({
  data: {
    navState: 0,
    is_first: 1,
    show_add_address: false,
    region: ['省', '市', '区'],
    address: {},
    theme_type: '',
    loadover: false,
    ssvoucher_list: [],
    addressState: false,
    tips: '有什么想对商家说的可以写在这里哦~',
    goods: {},
    buy_type: '',
    pickname: '请选择自提点',
    ck_yupay: 0,
    is_yue_open: 0,
    comment: '',
    can_sub: 1,
    pay_str: '立即支付',
    tab_index: 1,
    total_free: 0,
    is_ziti: 0,
    pick_up_id: 0,
    hide_quan: true,
    dispatching: 'express',
    pick_up_arr: 0,
    focus_name: false,
    seller_chose_id: 0,
    focus_mobile: false,
    seller_chose_store_id: 0,
    voucher_id_arr: [],
    yupay: 0,
    yu_money: 0,
    ziti_name: '',
    add_mo: 0,
    ziti_mobile: '',
    skustate: 0
  },
  onLoad: function (options) {
    var that = this;
    var token = wx.getStorageSync('token');

    this.setData({
      buy_type: options.type
    })
    wx.showLoading({
    })
    
    wx.hideLoading();
    wx.closeSocket();


    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'car.checkout',
        'token': token,
        "buy_type": options.type
      },
      dataType: 'json',
      method: 'POST',
      success: function (res) {
        var addres = 0;
        

        if (res.data.address != null && res.data.address != false) {
          addres = 1;
        }
        console.log(addres);

        var seller_chose_id = 0;
        var seller_chose_store_id = 0;
        var seller_goods = res.data.seller_goodss;

        for (var i in seller_goods) {
          if (seller_goods[i].show_voucher == 1) {
            seller_chose_id = seller_goods[i].chose_vouche.id;
            seller_chose_store_id = seller_goods[i].chose_vouche.store_id;
          }
          for (var j in seller_goods[i].goods) {
            if (seller_goods[i].goods[j].header_disc > 0 && seller_goods[i].goods[j].header_disc < 100) {
              seller_goods[i].goods[j].header_disc = (seller_goods[i].goods[j].header_disc / 10).toFixed(1);
            }
          }
        }

        that.setData({
          loadover:true
        })
        if (addres == 1) {

          that.setData({
            address: {
              provinceName: res.data.address.province_name,
              cityName: res.data.address.city_name,
              countyName: res.data.address.country_name,
              detailInfo: res.data.address.address,
              telNumber: res.data.address.telephone,
              userName: res.data.address.name,
            },
            addressState: true,
            is_integer: res.data.is_integer,
            ziti_name: res.data.ziti_name,
            ziti_mobile: res.data.ziti_mobile,
            is_ziti: res.data.is_ziti,
            pick_up_arr: res.data.pick_up_arr,
            seller_goodss: res.data.seller_goodss,
            seller_chose_id: seller_chose_id,
            seller_chose_store_id: seller_chose_store_id,
            goods: res.data.goods,
            buy_type: res.data.buy_type,
            yupay: res.data.can_yupay,
            is_yue_open: res.data.is_yue_open,
            yu_money: res.data.yu_money,
            total_free: res.data.total_free
          })


        } else {
          that.setData({
            is_integer: res.data.is_integer,
            addressState: false,
            goods: res.data.goods,
            is_ziti: res.data.is_ziti,
            pick_up_arr: res.data.pick_up_arr,
            seller_goodss: res.data.seller_goodss,
            seller_chose_id: seller_chose_id,
            seller_chose_store_id: seller_chose_store_id,
            buy_type: res.data.buy_type,
            yupay: res.data.can_yupay,
            is_yue_open: res.data.is_yue_open,
            yu_money: res.data.yu_money,
            ziti_name: res.data.ziti_name,
            ziti_mobile: res.data.ziti_mobile,
            total_free: res.data.total_free
          })
        }
        
      }
    })



  },
  onShow: function () {
    var _isfirst = this.data.is_first;
    if (_isfirst == 0) {
      console.log('show_on');
      this.load_new_func();
    } else {
      this.setData({
        is_first: 0
      })
    }
  },
  chooseAddress_list: function () {
    var s_type = this.data.buy_type;

    var url = "/pages/dan/address_list?is_direct=1&buy_type=" + s_type;
    var pages_all = getCurrentPages();
    if (pages_all.length > 3) {
      wx.redirectTo({
        url: url
      })
    } else {
      wx.navigateTo({
        url: url
      })
    }
  },
  navShow: function () {
    this.setData({
      navState: 1
    })
  },
  goOrderfrom: function (e) {
    var from_id = e.detail.formId;
    var token = wx.getStorageSync('token');


    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'user.get_member_form_id',
        'token': token,
        "from_id": from_id
      },
      dataType: 'json',
      success: function (res) {
      }
    })

    this.setOrder();

  },
  ck_wxpays: function () {
    this.setData({
      ck_yupay: 0
    })
  },
  tabchange: function (e) {
    var index = e.currentTarget.dataset.index;
    if (index == 2) {
      this.setData({
        dispatching: 'pickup',
        tips: '',
        tab_index: index
      })
      this.load_new_price();
    } else {

      this.setData({
        dispatching: 'express',
        skustate: 0,
        tab_index: index,
        tips: '有什么想对商家说的可以写在这里哦~'
      })
      this.load_new_price();
    }

  },
  ck_yupays: function () {
    var yupay = this.data.yupay;
    if (yupay == 0) {
      wx.showToast({
        title: '余额不足',
      })
      return false;
    }
    var ck_yupay = this.data.ck_yupay;
    if (ck_yupay == 1) {
      this.setData({
        ck_yupay: 0
      })
    } else {
      this.setData({
        ck_yupay: 1
      })
    }

  },
  navHide: function () {
    this.setData({
      navState: 0
    })
  },
  click_hide_dialog: function () {
    this.setData({
      skustate: 0
    })
  },
  load_new_price: function () {
    // dispatching:'express',
    var that = this;
    var token = wx.getStorageSync('token');
    var buy_type = this.data.buy_type;
    var dispatching = this.data.dispatching;

    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'car.checkout',
        'token': token,
        "buy_type": buy_type,
        "dispatching": dispatching
      },
      dataType: 'json',
      method: 'POST',
      success: function (res) {
        //addressState:true,dispatching
        var t_addressState = false;

        if (res.data.address != null || dispatching == 'pickup') {
          t_addressState = true;
        }
        //console.log(res.data.address);
        //console.log(dispatching);
        //console.log(t_addressState);
        if (res.data.address != null) {
          that.setData({
            address: {
              provinceName: res.data.address.province_name,
              cityName: res.data.address.city_name,
              countyName: res.data.address.country_name,
              detailInfo: res.data.address.address,
              telNumber: res.data.address.telephone,
              userName: res.data.address.name,
            },
            addressState: t_addressState,
            goods: res.data.goods,
            buy_type: res.data.buy_type,
            total_free: res.data.total_free
          })
        } else {
          that.setData({
            addressState: t_addressState,
            goods: res.data.goods,
            buy_type: res.data.buy_type,
            total_free: res.data.total_free
          })
        }
      }
    })

  },
  show_voucher: function (event) {
    var that = this;
    var serller_id = event.currentTarget.dataset.seller_id;
    var voucher_list = [];
    var seller_chose_id = this.data.seller_chose_id;
    var seller_chose_store_id = this.data.seller_chose_store_id;
    var seller_goods = this.data.seller_goodss;
    for (var i in seller_goods) {

      var s_id = seller_goods[i].store_info.s_id;
      if (s_id == serller_id) {
        voucher_list = seller_goods[i].voucher_list;
        if (seller_chose_id == 0) {
          seller_chose_id = seller_goods[i].chose_vouche.id;
          seller_chose_store_id = seller_goods[i].chose_vouche.store_id;
        }
      }
    }

    that.setData({
      ssvoucher_list: voucher_list,
      voucher_serller_id: serller_id,
      seller_chose_id: seller_chose_id,
      seller_chose_store_id: seller_chose_store_id,
      hide_quan: false
    })

    // seller_goodss: res.data.seller_goodss,

  },
  close_voucher: function () {
    this.setData({
      hide_quan: true
    })
  },
  chose_voucher_id: function (event) {
    var voucher_id = event.currentTarget.dataset.voucher_id;
    var seller_id = event.currentTarget.dataset.seller_id;



    var that = this;
    var token = wx.getStorageSync('token');
    var buy_type = that.data.buy_type;
    var use_quan_str = seller_id + "_" + voucher_id;

    app.util.request({
      'url': 'entry/wxapp/index',
      'data': { controller: 'car.checkout', token: token, 
        buy_type: buy_type, voucher_id: voucher_id, use_quan_str: use_quan_str},
      dataType: 'json',
      success: function (res) {
        var addres = 0;
        if (res.data.address != null) {
          addres = 1;
        }
        var seller_chose_id = 0;
        if (res.data.seller_goodss.show_voucher == 1) {
          seller_chose_id = res.data.seller_goodss.show_voucher.id
        }

        if (addres == 1) {

          that.setData({
            address: {
              provinceName: res.data.address.province_name,
              cityName: res.data.address.city_name,
              countyName: res.data.address.country_name,
              detailInfo: res.data.address.address,
              telNumber: res.data.address.telephone,
              userName: res.data.address.name,
            },
            addressState: true,
            seller_goodss: res.data.seller_goodss,
            seller_chose_id: voucher_id,
            seller_chose_store_id: seller_id,
            hide_quan: true,
            goods: res.data.goods,
            buy_type: res.data.buy_type,
            yupay: res.data.can_yupay,
            is_yue_open: res.data.is_yue_open,
            total_free: res.data.total_free
          })


        } else {
          that.setData({

            addressState: false,
            goods: res.data.goods,
            seller_goodss: res.data.seller_goodss,
            seller_chose_id: voucher_id,
            seller_chose_store_id: seller_id,
            hide_quan: true,
            buy_type: res.data.buy_type,
            yupay: res.data.can_yupay,
            is_yue_open: res.data.is_yue_open,
            total_free: res.data.total_free
          })
        }

      }
    })

    //voucher_id voucher_id_arr 

  },
  chooseZiti: function () {
    this.setData({
      skustate: 1,
      tips: '',
    })
  },
  bindNameInput: function (e) {
    this.setData({
      ziti_name: e.detail.value
    })
  },
  bindAddrdetailInput: function (e) {
    this.setData({
      addr_detail: e.detail.value
    })
  },
  bindAddrtelInput: function (e) {
    this.setData({
      addr_tel: e.detail.value
    })
  },
  bindAddrnameInput: function (e) {
    this.setData({
      addr_name: e.detail.value
    })
  },
  bindMobileInput: function (e) {
    this.setData({
      ziti_mobile: e.detail.value
    })
  },
  bindRegionChange: function (e) {

    this.setData({
      region: e.detail.value
    })
  },
  textarea_input: function (event) {
    var val = event.detail.value;
    this.setData({
      comment: val
    })
  },
  chose_mendian: function (e) {
    let men_id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    this.load_new_price();
    this.setData({
      pick_up_id: men_id,
      skustate: 0,
      tips: '有什么想对商家说的可以写在这里哦~',
      dispatching: 'pickup',
      addressState: true,
      pickname: name
    })
  },
  load_wx_add: function () {
    var that = this;

    wx.chooseAddress({
      success: function (res) {
        var token = wx.getStorageSync('token');
        
        res.controller = 'user.add_weixinaddress';
        res.token = token;

        app.util.request({
          'url': 'entry/wxapp/user',
          'data': res,
          dataType: 'json',
          method: 'POST',
          success: function (msg) {
            var buy_type = that.data.buy_type;

            app.util.request({
              'url': 'entry/wxapp/user',
              'data': {
                controller:'car.checkout',
                token: token,
                buy_type: buy_type
              },
              dataType: 'json',
              method: 'POST',
              success: function (res) {
                var seller_chose_id = 0;
                if (res.data.seller_goodss.show_voucher == 1) {
                  seller_chose_id = res.data.seller_goodss.show_voucher.id
                }

                that.setData({
                  address: {
                    provinceName: res.data.address.province_name,
                    cityName: res.data.address.city_name,
                    countyName: res.data.address.country_name,
                    detailInfo: res.data.address.address,
                    telNumber: res.data.address.telephone,
                    userName: res.data.address.name,
                  },
                  seller_chose_id: seller_chose_id,
                  seller_goodss: res.data.seller_goodss,
                  addressState: true,
                  goods: res.data.goods,
                  buy_type: res.data.buy_type,
                  yupay: res.data.can_yupay,
                  is_yue_open: res.data.is_yue_open,
                  total_free: res.data.total_free
                })
              }
            })

          }
        })

      }
    })
  },
  chooseAddress: function () {
    var add_mo = this.data.add_mo;
    var that = this;
    wx.getSetting({
      success: function (res) {

        var add_scope = res.authSetting;
        that.load_wx_add();
        that.setData({
          add_mo: 1
        })

      }
    })
  },
  goLink: function (event) {
    let link = event.currentTarget.dataset.link;
    wx.redirectTo({
      url: link
    })
  },
  setOrder: function () {
    var that = this;
    var token = wx.getStorageSync('token');
    var addressState = this.data.addressState;
    var voucher_id = this.data.seller_chose_id;
    var is_ziti = this.data.is_ziti;
    var seller_chose_store_id = this.data.seller_chose_store_id;
    var ck_yupay = this.data.ck_yupay;
    var dispatching = this.data.dispatching;
    var can_sub = this.data.can_sub;

    if (is_ziti == 2) {
      addressState = true;
      dispatching = 'pickup';
    }

    var comment = this.data.comment;
    // addressState: false,
    if (!addressState) {
      wx.showToast({
        title: '请选择收货地址',
      })
      return false;
    }

    var t_ziti_name = this.data.ziti_name;
    var t_ziti_mobile = this.data.ziti_mobile;
    var quan_arr = [];

    if (voucher_id > 0) {
      var t_tmp = seller_chose_store_id + '_' + voucher_id;
      quan_arr.push(t_tmp);
    }
    var pick_up_id = that.data.pick_up_id;
    if (dispatching == 'pickup') {
      if (t_ziti_name == '') {
        this.setData({
          focus_name: true
        })
        wx.showToast({
          title: '请填写联系人',
        })
        return false;
      }
      if (t_ziti_mobile == '') {
        this.setData({
          focus_mobile: true
        })
        wx.showToast({
          title: '请填写联系方式',
        })
        return false;
      }
      if (pick_up_id == 0) {
        this.setData({
          skustate: 1
        })
        wx.showToast({
          title: '请选择自提点',
        })
        return false;
      }
    }

    if (can_sub != 1) {
      return false;
    }
    this.setData({
      can_sub: 0
    })
    this.setData({
      pay_str: '支付中..'
    })

    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'car.sub_order',
        'token': token,
        pay_method: 'wxpay',
        buy_type: that.data.buy_type,
        pick_up_id: that.data.pick_up_id,
        dispatching: that.data.dispatching,
        ziti_name: t_ziti_name,
        quan_arr: quan_arr,
        comment: comment,
        ziti_mobile: t_ziti_mobile,
        ck_yupay: ck_yupay
      },
      dataType: 'json',
      method: 'POST',
      success: function (res) {
        //has_yupay
        if (res.data.has_yupay == 1) {
          var order_id = res.data.order_id;
          //buytype
          if (that.data.buy_type == 'pin' && res.data.is_integral == 0 && res.data.is_spike == 0) {
            wx.redirectTo({
              url: '/Snailfish_shop/pages/share/index?id=' + res.data.order_id + '&is_show=1'
            })
          } else {
            wx.redirectTo({
              url: '/Snailfish_shop/pages/order/order?id=' + res.data.order_id + '&is_show=1'
            })
          }

        } else {
          var order_id = res.data.order_id;
          wx.requestPayment({
            "appId": res.data.appId,
            "timeStamp": res.data.timeStamp,
            "nonceStr": res.data.nonceStr,
            "package": res.data.package,
            "signType": res.data.signType,
            "paySign": res.data.paySign,
            'success': function (wxres) {

              //buytype
              if (that.data.buy_type == 'pin' && res.data.is_spike == 0) {
                wx.redirectTo({
                  url: '/Snailfish_shop/pages/share/index?id=' + res.data.order_id + '&is_show=1'
                })
              } else {
                wx.redirectTo({
                  url: '/Snailfish_shop/pages/order/order?id=' + res.data.order_id + '&is_show=1'
                })
              }

            },
            'fail': function (res) {
              //console.log(res);

              wx.redirectTo({
                url: '/pages/order/order?id=' + order_id
              })

            }
          })
        }

      }
    })
    
  },
  show_add_selfaddress: function () {
    this.setData({
      show_add_address: true
    })
  },
  close_address_dialog: function () {
    this.setData({
      show_add_address: false
    })
  },
  chose_location: function () {
    var that = this;
    wx.chooseLocation({
      success: function (e) {

        var path = e.address;
        var s_region = that.data.region;
        var dol_path = '';


        var str = path;
        var patt = new RegExp("(.*?省)(.*?市)(.*?区)", "g");
        var result = patt.exec(str);
        if (result == null) {
          patt = new RegExp("(.*?省)(.*?市)(.*?市)", "g");
          result = patt.exec(str);
          if (result == null) {
            patt = new RegExp("(.*?省)(.*?市)(.*县)", "g");
            result = patt.exec(str);
            if (result == null) {
            } else {
              if (s_region[0] != result[1] || s_region[1] != result[2] || s_region[2] != result[3]) {
                wx.showToast({
                  title: '省市区信息已同步修改',
                  icon: 'none',
                })
              }
              s_region[0] = result[1];
              s_region[1] = result[2];
              s_region[2] = result[3];
              dol_path = path.replace(result[0], '');
            }
          } else {
            if (s_region[0] != result[1] || s_region[1] != result[2] || s_region[2] != result[3]) {
              wx.showToast({
                title: '省市区信息已同步修改',
                icon: 'none',
              })
            }
            s_region[0] = result[1];
            s_region[1] = result[2];
            s_region[2] = result[3];
            dol_path = path.replace(result[0], '');
          }
        } else {
          if (s_region[0] != result[1] || s_region[1] != result[2] || s_region[2] != result[3]) {
            wx.showToast({
              title: '省市区信息已同步修改',
              icon: 'none',
            })
          }
          s_region[0] = result[1];
          s_region[1] = result[2];
          s_region[2] = result[3];

          dol_path = path.replace(result[0], '');
        }
        if (s_region[0] == '省') {
          wx.showToast({
            title: '请重新选择省市区',
            icon: 'none',
          })
        }
        var filename = dol_path + e.name;

        that.setData({
          region: s_region,
          addr_detail: filename
        })
      }
    })
  },
  sub_address_do: function () {

    var token = wx.getStorageSync('token');
    var addr_name = this.data.addr_name;
    var addr_tel = this.data.addr_tel;
    var province_name = this.data.region[0];
    var city_name = this.data.region[1];
    var area_name = this.data.region[2];
    var addr_detail = this.data.addr_detail;
    var that = this;

    if (addr_name == '') {
      wx.showToast({
        title: '请填写姓名',
      })
      return false;
    }
    if (addr_tel == '') {
      wx.showToast({
        title: '请填写电话',
      })
      return false;
    }

    if (province_name == '省' && city_name == '市' && area_name == '区') {
      wx.showToast({
        title: '请选择地区',
      })
      return false;
    }

    if (addr_detail == '') {
      wx.showToast({
        title: '请填写详细地址',
      })
      return false;
    }

    var res = { province_name: province_name, city_name: city_name, area_name: area_name, addr_tel: addr_tel, addr_detail: addr_detail, addr_name: addr_name };

    wx.request({
      url: util.api() + 'index.php?s=/Apicheckout/add_weixin_selftaddress/token/' + token,
      data: res,
      method: 'POST',
      success: function (msg) {
        that.close_address_dialog();

        var buy_type = that.data.buy_type;
        wx.request({
          url: util.api() + 'index.php?s=/Apicart/checkout/token/' + token + '/buy_type/' + buy_type,
          success: function (res) {


            var seller_chose_id = 0;
            if (res.data.seller_goodss.show_voucher == 1) {
              seller_chose_id = res.data.seller_goodss.show_voucher.id
            }

            that.setData({
              address: {
                provinceName: res.data.address.province_name,
                cityName: res.data.address.city_name,
                countyName: res.data.address.country_name,
                detailInfo: res.data.address.address,
                telNumber: res.data.address.telephone,
                userName: res.data.address.name,
              },
              seller_chose_id: seller_chose_id,
              seller_goodss: res.data.seller_goodss,
              addressState: true,
              goods: res.data.goods,
              buy_type: res.data.buy_type,
              total_free: res.data.total_free
            })

          }
        })
      }
    })

  },
  load_new_func: function () {
    var token = wx.getStorageSync('token');
    var that = this;
    var buy_type = that.data.buy_type;

    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'car.checkout',
        'token': token,
        "buy_type": buy_type
      },
      dataType: 'json',
      method: 'POST',
      success: function (res) {
        var seller_chose_id = 0;
        if (res.data.seller_goodss.show_voucher == 1) {
          seller_chose_id = res.data.seller_goodss.show_voucher.id
        }
        console.log(res.data.address);
        if (res.data.address == null) {
          that.setData({
            addressState: false,
            seller_chose_id: seller_chose_id,
            seller_goodss: res.data.seller_goodss,
            goods: res.data.goods,
            buy_type: res.data.buy_type,
            total_free: res.data.total_free
          })
        } else {
          
          that.setData({
            address: {
              provinceName: res.data.address.province_name,
              cityName: res.data.address.city_name,
              countyName: res.data.address.country_name,
              detailInfo: res.data.address.address,
              telNumber: res.data.address.telephone,
              userName: res.data.address.name,
            },
            seller_chose_id: seller_chose_id,
            seller_goodss: res.data.seller_goodss,
            addressState: true,
            goods: res.data.goods,
            buy_type: res.data.buy_type,
            total_free: res.data.total_free
          })
        }
      }
    })

    
  }

})