import { areaList } from '../../data/index';
const app = getApp()
let util = require('../../../../utils/util')
const apiArr = require('../../../../api/water_filter')
let PayJs = require('../../../../api/pay')

const __staticUrl = require('../../../../config/env.js').static_url
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked:false,
    areaList,
    show:false, //弹出层
    name:"",
    phone:"",
    area:"",
    region:"",
    address:"",
    message:"",
    tabIndex:1,

    flag:false,
    page_size:10,
    page_num:1,
    
    option2: [
    { text: '默认排序', value: 'a' },
    { text: '好评排序', value: 'b' },
    { text: '销量排序', value: 'c' },
    ],
    value2: 'a',
    buyProductList:[],

    price:0,
    deviceList:[],  
    orderMsg:"",
    GoodsMsg:"",
    delId:"",
  },

  iptMt(e){
      let that =this
      that.setData({
          delId:e.detail.value,
          page_num:1,
          flag:false,
          buyProductList:[]
      })
      that.getBuyProList()
  },

  //进货记录
  getBuyProList(){
      let that =this
      wx.showLoading({
        title: '加载中...',
        mask:true
      })
      util.postUrl(apiArr.buyProductList,{
        dealer_id:wx.getStorageSync('dealer_id'),
        order_no:that.data.delId,
        page_num:that.data.page_num,
        page_size:that.data.page_size
      },res=>{
          console.log(res);
          wx.hideLoading()
          if( res.rows){
              let flag = false
            if(res.rows.length == that.data.page_size){
                flag = true
            }else{
                flag = false
            }
           
            that.setData({
                flag,
                page_num:that.data.page_num +1,
                buyProductList:that.data.buyProductList.concat(res.rows || [])
            })
          }

      })
  },

  changeTab(e){
    console.log('e111', e);
    let that = this
    that.setData({
        tabIndex:e.currentTarget.dataset.index,
        flag:false,
        page_num:1,
        buyProductList:[]
    })
    if (e.currentTarget.dataset.index === '1') {
        console.log(123);
        that.getBuyProList()
    }
  },

  ipt1(e){
    let that = this
    that.setData({
        name:e.detail.value
    })
},
  ipt2(e){
    let that = this
    that.setData({
        phone:e.detail.value
    })
  },
  ipt3(e){
    let that = this
    that.setData({
        address:e.detail.value
    })
  },
  ipt4(e){
      let that = this
    that.setData({
        message:e.detail.value
    })
},
  account(){
      wx.navigateTo({
        url: '../payList/payList',
      })
  },

  onClose(e){
    let that = this
    that.setData({
      show:false
    })
  },

  changeShow(){
    let that = this
    that.setData({
      show:true
    })

  },

  //选择地区
  AreaConfirm(e){
    let that = this
    let region = ''
    let area = ''
    if(e.detail.values[0].name == e.detail.values[1].name){
      area = e.detail.values[1].name +  e.detail.values[2].name
      region = e.detail.values[1].name +"/" +  e.detail.values[2].name
    }else{
      area = e.detail.values[0].name +  e.detail.values[1].name +  e.detail.values[2].name
      region = e.detail.values[0].name +"/" +  e.detail.values[1].name +"/" +  e.detail.values[2].name
    }

    that.setData({
      show:false,
      area,
      region
    })
    

  },
  //取消
  cancel(e){
    let that = this
    that.setData({
      show:false
    })
  },

  onChange(e){
    let that = this
    let item = e.currentTarget.dataset.item
    let deviceList = that.data.deviceList
    deviceList.forEach(items=>{
        if(item.product_id == items.product_id){
            items.num = e.detail
        }
    })
    that.setData({
        deviceList
    })

    let price = Number(0)

    that.data.deviceList.forEach(item=>{
        if(item.num != 0){
            // price  +=  util.floatCalculate(item.num,item.suggested_price,'*')
            let currentMony = util.floatCalculate(item.num,item.suggested_price,'*')
            price  =  util.floatCalculate(price,currentMony,'+=')
        }
    })
    that.setData({
        price
    })

  },

  //设备列表
  getProductList(){
    let that =this
    util.postUrl(apiArr.getProduct,{
        dealer_id:wx.getStorageSync('dealer_id'),
        page_num:that.data.page_num,
        page_size:that.data.page_size,
        status:1,
    },res=>{
        if(res.rows){
            let flag  =false
            if(res.rows.length == that.data.page_size){
                flag = true
            }else{
                flag = false
            }
            res.rows.forEach(item=>{
                item.num = 0
                item.product_icon = util.img_url + item.product_icon
            })
            that.setData({
                deviceList:that.data.deviceList.concat(res.rows || []),
                flag,
                page_num:that.data.page_num + 1
            })
        }
    })
  },

  //创建进货订单
  createOrder(){
    let that =this
    let products = []
    that.data.deviceList.forEach(item=>{
        if(item.num > 0){
            products.push({
                number:item.num,
                product_id:item.product_id
            })
        }
    })

    if(products.length == 0){
        wx.showToast({
          title: '请选择进货设备',
          icon:"none"
        })
        return
    }
    if(!that.data.name){
        wx.showToast({
            title: '请填写收货人',
            icon:"none"
          })
          return
    }
    if(!that.data.phone){
        wx.showToast({
            title: '请填写收货人联系方式',
            icon:"none"
          })
          return
    }
    if(!util.isPhone(that.data.phone)){
        wx.showToast({
            title: '请填写正确联系方式',
            icon:"none"
          })
          return
    }
    if(!that.data.region){
        wx.showToast({
            title: '请选择所在地区',
            icon:"none"
          })
          return
    }
    if(!that.data.address){
        wx.showToast({
            title: '请填写详细地址',
            icon:"none"
          })
          return
    }
    
    wx.showLoading({
      title: '加载中...',
      mask:true
    })

    util.postUrl(apiArr.createPartnerOrder,{
        address:that.data.address,
        dealer_id:wx.getStorageSync('dealer_id'),
        mobile:that.data.phone,
        name:that.data.name,
        region:that.data.region,
        products,
        total_price:Number(that.data.price)
    },res=>{
        that.setData({
            orderMsg:res
        })
        that.getGoodsMsg()
    })
  },

  getGoodsMsg(){
    let that = this
    util.postUrl(apiArr.getCurrentShopMsg,{
        dealer_id:Number(that.data.orderMsg.dealer_id)
    },res=>{
        that.setData({
            GoodsMsg:res
        })
        that.pay()
    })
  },

pay(){
    let that = this
    util.postUrl2(PayJs.pay,{
        address:that.data.area + that.data.address,
        goods_id:String(that.data.orderMsg.order_id),
        merchant_no:that.data.GoodsMsg.merchant_no,
        out_trade_no:that.data.orderMsg.order_no,
        quantity:1,
        remark:that.data.message,
        subject:that.data.orderMsg.order_name,
        term_no:that.data.GoodsMsg.term_no,
        total_amount:String(that.data.price * 100),
        // total_amount:String(1),
        user:String(wx.getStorageSync('userId')),
        user_id:wx.getStorageSync('openId')
    },res=>{
        const {resp_data,msg} = res.data.data
        wx.hideLoading()
        if(msg == '成功'){
            wx.requestPayment({
            timeStamp:String(resp_data.acc_resp_fields.time_stamp),
            nonceStr:String(resp_data.acc_resp_fields.nonce_str),
            package:String(resp_data.acc_resp_fields.package),
            signType:String(resp_data.acc_resp_fields.sign_type),
            paySign:String(resp_data.acc_resp_fields.pay_sign),
            success(res){
                that.queryPay() 
            },
            fail(fal){
                console.log(fal);
            }
            })
        }
    })
},

queryPay(){
    let that = this
    util.postUrl2(PayJs.queryPay,{
        merchant_no:that.data.GoodsMsg.merchant_no,
        term_no:that.data.GoodsMsg.term_no,
        out_trade_no:that.data.orderMsg.order_no
    },res=>{
        console.log(res,23);
        if(res.statusCode == '200'){
            wx.showToast({
                title: '支付成功！',
            })
            setTimeout(()=>{
                that.getBuyProList()
            },1500)
        }else{
            wx.showToast({
                title: res.msg,
            })
        }
    })
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    that.getBuyProList()
    that.getProductList()
    wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(){
    return {
        title: '人人爱净水',  // 分享卡片标题（必填）
        path: '/pages/water_filter/water_filter',  // 用户点击后跳转的路径（可选，默认当前页）
        imageUrl: (__staticUrl + '/share.png')  // 自定义图片（可选，比例建议 5:4）
      }
},
onShareTimeline() {
    return {
        title: '人人爱净水', // 自定义标题
        query: '', // 自定义页面路径中的参数
        imageUrl: (__staticUrl + '/share.png') // 自定义分享图片路径
    }
},
})