//index.js
//获取应用实例
var sever = require("../../api.js").sever;
var sever_url = require("../../api.js").sever_url;
console.log(sever)
var app = getApp()
const Dialog = require('../../bower_components/zanui-weapp/dist/dialog/dialog');
const Toast = require('../../bower_components/zanui-weapp/dist/toast/toast');
const Toptips = require('../../bower_components/zanui-weapp/dist/toptips/toptips');

var urlArr = [];
Page({
  data: {
    is_login:false,
    urlArr: [],
    show: false,
    pic_url: '',
    usercode: '',
    urname: '',
    mobile: '',
    address: '',
    typeid: 0,
    colorid: 0,
    userInfo: {},
    hasUserInfo: false,
    categorys: ['品类1', '品类2', '品类3', '品类4', '品类5'],
    categorysObj: [],
    categoryIndex: 0,
    gtypes: ['种类1', '种类2', '种类3', '种类4', '种类5'],
    gtypesObj: [],
    gtypeIndex: 0,
    gcolors: ['颜色1', '颜色2', '颜色3', '颜色4', '颜色5'],
    gcolorObj: [],
    gcolorIndex: 0,
    lei: '',
    size: '',
    color: '',
    miaoshu: '',
    theimgs: [],
    login: '',
  },
  showpic: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var imgList = event.currentTarget.dataset.list; //获取data-list
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },
  addimg: function() {
    var arr = [];
    var that = this;
    if (that.data.urlArr.length > 2) {
      wx.showToast({
        title: '最多添加3张',
        icon: 'none',
        duration: 1000
      })
      return
    }
    wx.chooseImage({
      count: 3 - that.data.urlArr.length,
      success: function(res) {
        var successUp = 0; //成功个数
        var failUp = 0; //失败个数
        var length = res.tempFilePaths.length; //总共个数
        var i = 0; //第几个
        that.uploadDIY(res.tempFilePaths, successUp, failUp, i, length);
        if (that.data.theimgs.length == 0) {
          that.setData({
            theimgs: arr
          })
        } else if (that.data.theimgs.length < 4) {
          console.log(that.data.theimgs)
          that.data.theimgs.push(arr)
          var the = that.data.theimgs
          console.log(the)
          that.setData({
            theimgs: the
          })
        } else {}
      },
    })
  },
  methods: {
    handleFieldChange(event) {
      console.log(event);
    },

    handleFieldFocus(event) {
      console.log(event);
    },

    handleFieldBlur(event) {
      console.log(event);
    }
  },
  wenti: function(e) {
    this.setData({
      miaoshu: e.detail.value
    })
    console.log(this.data.miaoshu)
  },
  namein: function(e) {
    this.setData({
      urname: e.detail.value
    })
    console.log(this.data.urname)
  },
  mobilein: function(e) {
    this.setData({
      mobile: e.detail.value
    })
    console.log(this.data.mobile)
  },
  addressin: function(e) {
    this.setData({
      address: e.detail.value
    })
    console.log(this.data.address)
  },
  tijiao: function() {
    Toast({
      message: '提交成功',
      icon: 'success',
      selector: '#zan-toast-test'
    });
    wx.navigateTo({
      url: '../infor/infor',
    })
  },
  //事件处理函数
  bindchange: function(t) {
    t.detail.current == this.data.imgUrls.length - 1 ? this.setData({
      show_btn: !0
    }) : this.setData({
      show_btn: !1
    });
  },
  onShow:function(){
    var that = this
    if (wx.getStorageSync('user').wechat_open_id) {
      that.setData({
        is_login:false
      })
    }else{
      that.setData({
        is_login: true
      })
    }
  },
  onLoad: function() {
    var that = this
    // console.log()
    if (wx.getStorageSync('user').wechat_open_id) {
      that.setData({
        is_login:false
      })
      wx.setStorageSync('ma', 0)
      wx.setStorageSync('pa', 0)
      wx.setStorageSync('us', 0)
      // wx.redirectTo({
      //   url: '../manager/manage',
      // })
    }
    app.request({
      url: sever+'getattr',
      data: {
        store_id: app.globalData.store_id
      },
      success: function(res) {
        let goodsinfo = res.data.data
        let arr = []
        let arr1 = []
        for (let i = 0; i < goodsinfo.length; i++) {
          // let obj = {}
          let t = {}
          t.name = goodsinfo[i].name
          t.id = goodsinfo[i].id
          arr.push(t)
          arr1.push(goodsinfo[i].name)
        }
        console.log(arr)
        that.setData({
          categorysObj: [...arr],
          categorys: [...arr1],
          lei: that.data.categorys[0]
        })
        app.request({
          url: sever+'getattr',
          data: {
            store_id: app.globalData.store_id,
            id: that.data.categorysObj[0].id
          },
          success: function(res) {
            let goodsinfo = res.data.data
            let arr = []
            let arr1 = []
            for (let i = 0; i < goodsinfo.length; i++) {
              // let obj = {}
              let t = {}
              t.name = goodsinfo[i].name
              t.id = goodsinfo[i].id
              arr.push(t)
              arr1.push(goodsinfo[i].name)
            }
            console.log(arr)
            that.setData({
              gtypesObj: [...arr],
              gtypes: [...arr1],
              size: that.data.gtypes[0]
            })
            app.request({
              url: sever+'getattr',
              data: {
                store_id: app.globalData.store_id,
                id: that.data.gtypesObj[0].id
              },
              success: function(res) {
                let goodsinfo = res.data.data
                let arr = []
                let arr1 = []
                for (let i = 0; i < goodsinfo.length; i++) {
                  // let obj = {}
                  let t = {}
                  t.name = goodsinfo[i].name
                  t.id = goodsinfo[i].id
                  arr.push(t)
                  arr1.push(goodsinfo[i].name)
                }
                console.log(arr)
                that.setData({
                  gcolorObj: [...arr],
                  gcolors: [...arr1],
                  color: that.data.gcolors[0]
                })
              }
            })
          }
        })
      }
    })

    var a = this;
    wx.getSystemInfo({
      success: function(t) {
        a.setData({
          windowWidth: t.windowWidth,
          windowHeight: t.windowHeight
        });
      }
    })
  },
  backhome: function () {
    wx.reLaunch({
      url: '/page/homePage/homePage',
    })
  },
  orderup: function(e) {
    console.log(urlArr)
    var that = this
    wx.showLoading({
      title: '上传中',
    })
    app.request({
      url: sever+'createorder',
      method: 'post',
      data: {
        store_id: app.globalData.store_id,
        category: that.data.categorys[that.data.categoryIndex],
        type: that.data.gtypes[that.data.gtypeIndex],
        color: that.data.gcolors[that.data.gcolorIndex],
        question: that.data.miaoshu,
        picture: that.data.urlArr,
        customer_name: that.data.urname,
        customer_phone: that.data.mobile,
        customer_address: that.data.address
      },
      success: function(res) {
        wx.hideLoading()
        console.log(res.data)
        if (res.data.status == true) {
          urlArr=[]
          that.setData({
            urname: '',
            mobile: '',
            address: '',
            lei: '',
            size: '',
            color: '',
            miaoshu: '',
            theimgs: [],
            urlArr: [],
            categoryIndex: 0,
            gtypeIndex: 0,
            gcolorIndex: 0,
          })
          
          app.request({
            url: sever+'getorder',
            method: 'get',
            data: {
              store_id: wx.getStorageSync('user').store_id,
              user_id: wx.getStorageSync('user').id,
              status: '0'
            },
            success: function(res) {
              var obj = res.data.data.order.data
              wx.setStorageSync('detail_order_id', obj[0].id)
              wx.setStorageSync('us', 1)
              wx.navigateTo({
                url: '../infor/details',
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },
  close_login:function(){
    this.setData({
      is_login: false
    })
  },
  userLogin: function (e) {
    this.setData({
      is_login: false
    })
    wx.showLoading({
      title: '登录中',
    })
    console.log(e.detail)
    var un = JSON.parse(e.detail.rawData)
    var that = this
    try {
      wx.login({
        success: function (res) {
          let code = res.code
          console.log(code)
          let tx = un.avatarUrl
          let nn = un.nickName
          let iv = e.detail.iv
          let encryptedData = e.detail.encryptedData
          app.request({
            url: sever+'service_login',
            method: 'POST',
            data: {
              code: code,
              avatar: tx,
              nickName: nn,
              store_id: app.globalData.store_id,
              iv: iv,
              encryptData: encryptedData
            },
            success: function (res) {
              console.log(res.data)
              wx.setStorageSync("token", res.data.data.token)
              wx.setStorageSync('key', res.data.data.session_key)
              wx.setStorageSync("user", res.data.data.user);
              wx.setStorageSync('ma', 0)
              wx.setStorageSync('pa', 0)
              wx.setStorageSync('us', 0)
              wx.hideLoading();
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1000,

              })
            }
          })
        }
      })
    } catch (e) {
      console.log(e.message)
    }
  },
  add: function(e) {
    var a = this;
    wx.chooseLocation({
      type: "wgs84",
      success: function(e) {
        e.latitude, e.longitude, e.speed, e.accuracy;
        var t = e.latitude + "," + e.longitude;
        console.log(e.address)
        //console.log(t)
        a.setData({
          address: e.address,
          // coordinates: t
        });
      }
    });
  },
  handleFieldChange(event) {
    console.log(event);
  },
  handleFieldFocus(event) {
    console.log(event);
  },
  handleFieldBlur(event) {
    console.log(event);
  },
  bindCategoryChange(e) {
    var that = this

    console.log('picker batchs 发生选择改变，携带值为', e.detail.value);

    this.setData({
      categoryIndex: parseInt(e.detail.value),
    })
    this.setData({
      category: that.data.categorys[parseInt(e.detail.value)]
    })
    app.request({
      url: sever+'getattr',
      data: {
        store_id: app.globalData.store_id,
        id: that.data.categorysObj[that.data.categoryIndex].id
      },
      success: function(res) {
        let goodsinfo = res.data.data
        let arr = []
        let arr1 = []
        for (let i = 0; i < goodsinfo.length; i++) {
          // let obj = {}
          let t = {}
          t.name = goodsinfo[i].name
          t.id = goodsinfo[i].id
          arr.push(t)
          arr1.push(goodsinfo[i].name)
        }
        console.log(arr)
        that.setData({
          gtypesObj: [...arr],
          gtypes: [...arr1],
          size: that.data.gtypes[0]
        })
        app.request({
          url: sever+'getattr',
          data: {
            store_id: app.globalData.store_id,
            id: that.data.gtypesObj[0].id
          },
          success: function(res) {
            let goodsinfo = res.data.data
            let arr = []
            let arr1 = []
            for (let i = 0; i < goodsinfo.length; i++) {
              // let obj = {}
              let t = {}
              t.name = goodsinfo[i].name
              t.id = goodsinfo[i].id
              arr.push(t)
              arr1.push(goodsinfo[i].name)
            }
            console.log(arr)
            that.setData({
              gcolorObj: [...arr],
              gcolors: [...arr1],
              color: that.data.gcolors[0]
            })
          }
        })
      }
    })
  },
  bindGtypeChange(e) {
    var that = this

    console.log('picker batchs 发生选择改变，携带值为', e.detail.value);

    this.setData({
      gtypeIndex: parseInt(e.detail.value),
    })
    this.setData({
      gtype: that.data.gtypes[parseInt(e.detail.value)]
    })
    app.request({
      url: sever+'getattr',
      data: {
        store_id: app.globalData.store_id,
        id: that.data.gtypesObj[that.data.gtypeIndex].id
      },
      success: function(res) {
        let goodsinfo = res.data.data
        let arr = []
        let arr1 = []
        for (let i = 0; i < goodsinfo.length; i++) {
          // let obj = {}
          let t = {}
          t.name = goodsinfo[i].name
          t.id = goodsinfo[i].id
          arr.push(t)
          arr1.push(goodsinfo[i].name)
        }
        console.log(arr)
        that.setData({
          gcolorObj: [...arr],
          gcolors: [...arr1],
          color: that.data.gcolors[0]
        })
      }
    })
  },
  bindGcolorChange(e) {
    var that = this
    console.log('picker batchs 发生选择改变，携带值为', e.detail.value);

    this.setData({
      gcolorIndex: parseInt(e.detail.value),
    })
    this.setData({
      gcolor: that.data.gcolors[parseInt(e.detail.value)]
    })
  },
  getPhoneNumber: function(e) {
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
    var that = this
    wx.checkSession({
      success:()=>{
        console.log("===")
        app.request({
          url: sever+'getphonenumber',
          data: {
            store_id: '1',
            session_key: wx.getStorageSync('key'),
            iv: e.detail.iv,
            encryptData: e.detail.encryptedData
          },
          method: 'POST',
          success: function (res) {
            console.log(res.data)
            if(res.data.status_code == 0){
              that.setData({
                mobile: res.data.data.decryptedData.phoneNumber
              })
            }else{
              wx.showToast({
                title: '登录过期',
                icon:'none',
                duration:1000,
              })
              that.setData({
                is_login: true
              })
            }
          }
        })
      },
      fail:()=>{
        that.setData({
          is_login:true
        })
      }
    })
  },
  del_pic: function(e) {
    var that = this
    var u = e.target.id
    var index = urlArr.indexOf(u)
    urlArr.splice(index, 1)
    that.setData({
      urlArr: [...urlArr]
    })
  },
  uploadDIY(filePaths, successUp, failUp, i, length) {
    var that = this
    wx.uploadFile({
      url: sever_url+'api/attachment/upload',
      filePath: filePaths[i],
      name: 'file',
      method: 'POST',
      formData: {
        tag: 'avatar',
      },
      success: (resp) => {
        var data = JSON.parse(resp.data)
        urlArr.push(data.data.url)
        that.setData({
          urlArr: [...urlArr]
        })
        if (data.status == true) {
          successUp++;
        } else {
          failUp++;
        }
      },
      fail: (res) => {
        failUp++;
      },
      complete: () => {
        i++;
        if (i == length) {
          // wx.showToast({
          //   title: '总共' + successUp + '张上传成功,' + failUp + '张上传失败！',
          //   icon: 'none',
          //   duration: 1000
          // });
        } else { //递归调用uploadDIY函数
          this.uploadDIY(filePaths, successUp, failUp, i, length);
        }
      },
    });
  },
  upFormID:function(e){
    app.request({
      url:sever+'saveformid',
      method:'post',
      data:{
        store_id:wx.getStorageSync('user').store_id,
        openid: wx.getStorageSync('user').wechat_open_id,
        formid:e.detail.formId
      },
      success:(res)=>{
        console.log(res.data.data.msg)
      }
    })
  },
  goUser:function(){
    wx.redirectTo({
      url: '../infor/infor',
    })
  },
  getWechatAddress: function (t) {
    var i = this;
    wx.chooseAddress({
      success: function (a) {
        if ("chooseAddress:ok" == a.errMsg){
          console.log(a)
          i.setData({
            urname:a.userName,
            mobile:a.telNumber,
            address:a.provinceName+a.cityName+a.countyName+a.detailInfo
          })
        }
      }
    });
  },
})