var app = getApp()
var network = require("../../../utils/net.js")
var dateTimePicker = require('../../../utils/dateTimePicker.js');
var utilll = require('../../../utils/util.js');

var getAccountingUnit = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetAccountingUnit";
var getCustomer = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetCustomer";
var getDept = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetDepartment";
var getGoods = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetGoodsWithUnitPrice";
var getSaleKind = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetSaleKind"
var insert = '/MainSystem/B3MiniProgramRpc/XuRpcs/Employee/SaleForecastRpc/Insert';

function GetAccountingUnit(that, inputValue) {
  let method = getAccountingUnit;
  let params = [{
    "InputValue": inputValue,
    "PageIndex": 0,
    "PageSize": 100
  }];
  network.transfer_request(method, params, function(res) {
    that.setData({
      currency: res.result,
      unit: res.result
    })
  })
  that.setData({
    which: "会计部门"
  })
}

function GetDepartment(that, inputValue) {
  let method = getDept;
  let params = [{
    "InputValue": inputValue,
    "PageIndex": 0,
    "PageSize": 100
  }];
  network.transfer_request(method, params, function(res) {
    that.setData({
      currency: res.result,
      department: res.result
    })
  })
  that.setData({
    which: "部门"
  })
}

function GetSaleKind(that, v) {
  let method = getSaleKind;
  let params = [{
    "InputValue": v,
    "PageIndex": 0,
    "PageSize": 100
  }];
  network.transfer_request(method, params, function(res) {
    that.setData({
      currency: res.result,
      saletype: res.result
    })
  })
  that.setData({
    which: "销售类型"
  })
}

function GetGoodsWithUnitPrice(that, v, date) {
  let unitID = that.data.unit[that.data.isUnit].ID;
  let customerID = that.data.customer[that.data.customerIndex].ID;
  let method = getGoods;
  let params = [{
    "Input": v,
    "PageIndex": 0,
    "PageSize": 100,
    "Customer_ID": customerID,
    "AccountingUnit_ID": unitID,
    "Date": date
  }];
  network.transfer_request(method, params, function(res) {
    that.setData({
      goods: res.result,
    })
  })
}

Page({

  data: {
    which: "",
    winHeight: app.globalData.winHeight,

    // 从哪个页面返回当前页面
    backPage: "",

    // tab切换
    currentTab: 0,
    // 存货数组
    obj: [],
    goods: [],
    idx: 0,
    currency: [],
    saletypeIndex: 0,
    saletype: [{
      ID: 0,
      Name: "请选择销售类型"
    }],
    departmentIndex: 0,
    department: [{
      ID: 0,
      Name: "请选择销售部门"
    }],
    customerIndex: 0,
    customer: [{
      ID: 0,
      Name: "请选择客户"
    }],
    isUnit: 0,
    unit: [{
      ID: 0,
      Name: "请选择会计单位"
    }],
    addrs: "",
    dateTimeArray: null,
    dateTime: null,
    dateTimeArray1: null,
    dateTime1: null,
    startYear: 2018,
    endYear: 2030
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;

    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    var lastArray = obj1.dateTimeArray.pop();
    var lastTime = obj1.dateTime.pop();

    this.setData({
      dateTimeArray: obj1.dateTimeArray,
      dateTime: obj1.dateTime,
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime
    });

  },

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

    if (that.data.backPage == "customerChoosePage") {
      // 返回的用户只能是一条，所以index只能为0
      var customerArr = app.globalData.customerArray;
      if (customerArr.length > 0) {
        that.setData({
          customer: customerArr,
          customerIndex: 0,
        })
      }
    }

    if (that.data.backPage == "goodsNameChoosePage") {
      // 获取存货 加载完成后计算价格政策
      var goodsArr = app.globalData.goodsNameArray;
      if (goodsArr.length > 0) {
        let backGoodsArr = [];
        for (var i = 0; i < goodsArr.length; i++) {

          var name = goodsArr[i].Goods_Name;
          var id = goodsArr[i].SaleGoods_ID;
          var pp = goodsArr[i].PolicyPrice;
          var price = goodsArr[i].Price;
          var mainUnitRatio = goodsArr[i].Goods_MainUnitRatio;
          var secondUnitRatio = goodsArr[i].Goods_SecondUnitRatio;
          var unitConvertDirection = goodsArr[i].Goods_UnitConvertDirection;
          var rightRatio = goodsArr[i].RightRatio;
          var leftRatio = goodsArr[i].LeftRatio;

          if (pp == null) {
            pp = Number(0);
          }
          if (rightRatio == null) {
            rightRatio = Number(1);
          }
          if (leftRatio == null) {
            leftRatio = Number(1);
          }

          let goodsNameObj = {
            Goods_MainUnitRatio: Number(mainUnitRatio),
            Goods_SecondUnitRatio: Number(secondUnitRatio),
            SaleGoods_ID: Number(id),
            Goods_Name: name,
            Price: Number(price),
            PolicyPrice: Number(pp),
            Goods_UnitConvertDirection: Number(unitConvertDirection),
            RightRatio: rightRatio,
            LeftRatio: leftRatio,
          }
          backGoodsArr.push(goodsNameObj)
        }

        that.setData({
          obj: backGoodsArr,
        })
      }
    }

  },

  // 原有请求客户的方法，已经废弃
  GetCustomer: function() {
    wx.navigateTo({
      url: '../../customerChooseTemplate/customerChooseTemplate?fromePage=newForecast',
    })
    // let method = getCustomer;
    // let params = [{
    //   "InputValue": inputValue,
    //   "PageIndex": 0,
    //   "PageSize": 100
    // }];
    // network.transfer_request(method, params, function(res) {
    //   that.setData({
    //     currency: res.result,
    //     customer: res.result
    //   })
    // })
    // that.setData({
    //   which: "购货客户"
    // })
  },



  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    app.globalData.goodsNameArray = [];
    app.globalData.customerArray = [];
  },

  /**
   * 滑动切换tab
   */
  bindChange: function(e) {

    var that = this;
    that.setData({
      currentTab: e.detail.current
    });

  },
  /**
   * 点击tab切换
   */
  swichNav: function(e) {

    var that = this;

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

  // 添加地址
  getAddrs: function(e) {
    this.data.addrs = e.detail.value;
  },

  // 添加存货 跳转存货选择页面
  add: function(e) {
    var that = this;
    let unitID = that.data.unit[that.data.isUnit].ID;
    let customerID = that.data.customer[that.data.customerIndex].ID;
    if (unitID && customerID) {
      wx.navigateTo({
        url: '../../goodaNameChooseTemplate/goodaNameChooseTemplate?unitID=' + unitID + '&customerID' + customerID,
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请先选择客户及会计单位',
      })
    }
  },

  // 添加购货客户 跳转客户选择页面
  getCustomerItem: function() {
    wx.navigateTo({
      url: '../../customerChooseTemplate/customerChooseTemplate?fromePage=newForecast',
    })
  },

  deleteItem: function(e) {
    let idx = e.target.dataset.idx;
    let deleteobj = this.data.obj;
    deleteobj.splice(idx, 1)
    this.setData({
      obj: deleteobj
    })
  },

  getGoodsNum: function(e) {
    //值：
    //e.detail.value
    //设置的id
    //e.target.dataset.index
    let value = e.detail.value;
    let idx = e.target.dataset.idx;

    let end = value.charAt(value.length - 1)
    if (end != ".") {

      this.data.obj[idx].goodsNum = Number(value);

      let Goods_MainUnitRatio = this.data.obj[idx].Goods_MainUnitRatio
      let Goods_SecondUnitRatio = this.data.obj[idx].Goods_SecondUnitRatio
      let Goods_UnitConvertDirection = this.data.obj[idx].Goods_UnitConvertDirection
      let RightRatio = this.data.obj[idx].RightRatio
      let LeftRatio = this.data.obj[idx].LeftRatio

      var numberNumber = Number(value) / RightRatio * LeftRatio;
      if (Goods_UnitConvertDirection == 0 || Goods_UnitConvertDirection == 1) {
        let secondNumber = numberNumber / (Goods_MainUnitRatio) * (Goods_SecondUnitRatio);
        this.data.obj[idx].goodsSecondNum = Number(secondNumber)
        this.setData({
          obj: this.data.obj
        })
      }
    }

  },
  getSecondNum: function(e) {
    let value = e.detail.value;
    let idx = e.target.dataset.idx;

    let end = value.charAt(value.length - 1)
    if (end != ".") {
      this.data.obj[idx].goodsSecondNum = Number(value);

      let Goods_MainUnitRatio = this.data.obj[idx].Goods_MainUnitRatio
      let Goods_SecondUnitRatio = this.data.obj[idx].Goods_SecondUnitRatio
      let Goods_UnitConvertDirection = this.data.obj[idx].Goods_UnitConvertDirection
      let RightRatio = this.data.obj[idx].RightRatio
      let LeftRatio = this.data.obj[idx].LeftRatio

      var numberNumber = Number(value) / LeftRatio * RightRatio;
      if (Goods_UnitConvertDirection == 0 || Goods_UnitConvertDirection == 2) {
        let unitnumber = numberNumber / (Goods_SecondUnitRatio) * (Goods_MainUnitRatio);
        this.data.obj[idx].goodsNum = Number(unitnumber)
        this.setData({
          obj: this.data.obj
        })
      }
    }
  },
  getPrice: function(e) {
    let value = e.detail.value;
    let idx = e.target.dataset.idx;
    this.data.obj[idx].Price = Number(value);
  },
  powerDrawer: function(e) {
    let that = this;
    let x = e.currentTarget.dataset.x;
    if (x == "会计部门") {
      GetAccountingUnit(that, "")
    } else if (x == "购货客户") {
      GetCustomer(that, "")
    } else if (x == "部门") {
      GetDepartment(that, "")
    } else if (x == "销售类型") {
      GetSaleKind(that, "")
    }
    let currentStatu = e.currentTarget.dataset.statu;
    // if (e.currentTarget.dataset.idx != null) {
    //   let idxx = e.currentTarget.dataset.idx;
    //   this.setData({
    //     idx: idxx
    //   })
    // }
    this.util(currentStatu)
  },
  powerDrawer1: function(e) {
    let that = this;
    let currentStatu = e.currentTarget.dataset.statu;

    let timestamp = Date.parse(new Date());
    let date = "/Date(" + timestamp + "+0800)/";
    GetGoodsWithUnitPrice(that, "", date)

    if (e.currentTarget.dataset.idx != null) {
      let idxx = e.currentTarget.dataset.idx;
      this.setData({
        idx: idxx
      })
    }
    this.util1(currentStatu)

  },
  itemclick: function(e) {
    var that = this;
    var name = e.currentTarget.dataset.name;
    var id = e.currentTarget.dataset.id;
    var which = e.currentTarget.dataset.item;
    var idx = e.currentTarget.dataset.idx;

    if (which == "会计部门") {
      that.setData({
        isUnit: idx
      })
    } else if (which == "购货客户") {
      that.setData({
        customerIndex: idx
      })
    } else if (which == "部门") {
      that.setData({
        departmentIndex: idx
      })
    } else if (which == "销售类型") {
      that.setData({
        saletypeIndex: idx
      })
    }

    this.setData({
      showModalStatus: false,
    })
  },
  // 选取货物后进行价格计算
  itemclick1: function(e) {
    var that = this;
    var name = e.currentTarget.dataset.name;
    var id = e.currentTarget.dataset.data.SaleGoods_ID;
    var pp = e.currentTarget.dataset.PolicyPrice;
    var price = e.currentTarget.dataset.data.Price;
    var Goods_MainUnitRatio = e.currentTarget.dataset.data.Goods_MainUnitRatio
    var Goods_SecondUnitRatio = e.currentTarget.dataset.data.Goods_SecondUnitRatio
    var Goods_UnitConvertDirection = e.currentTarget.dataset.data.Goods_UnitConvertDirection

    if (e.currentTarget.dataset.data.RightRatio == null) {
      this.data.obj[this.data.idx].RightRatio = Number(1)
    }
    if (e.currentTarget.dataset.data.LeftRatio == null) {
      this.data.obj[this.data.idx].LeftRatio = Number(1)
    }
    this.data.obj[this.data.idx].Goods_MainUnitRatio = Number(Goods_MainUnitRatio)
    this.data.obj[this.data.idx].Goods_SecondUnitRatio = Number(Goods_SecondUnitRatio)
    this.data.obj[this.data.idx].SaleGoods_ID = Number(id);
    this.data.obj[this.data.idx].Goods_Name = name;
    this.data.obj[this.data.idx].Price = Number(price)
    this.data.obj[this.data.idx].PolicyPrice = Number(pp);
    this.data.obj[this.data.idx].Goods_UnitConvertDirection = Number(Goods_UnitConvertDirection)
    this.setData({
      showModalStatus1: false,
      obj: that.data.obj
    })
  },

  select: function(e) {
    var that = this;
    var which = e.currentTarget.dataset.item;
    var value = e.detail.value;
    if (which == "会计部门") {
      GetAccountingUnit(that, value)
    } else if (which == "购货客户") {
      GetCustomer(that, value)
    } else if (which == "部门") {
      GetDepartment(that, value)
    } else if (which == "销售类型") {
      GetSaleKind(that, value)
    }
  },
  select1: function(e) {
    var that = this;
    var value = e.detail.value;
    let timestamp = Date.parse(new Date());
    let date = "/Date(" + timestamp + "+0800)/";
    GetGoodsWithUnitPrice(that, value, date)
  },
  submitForm: function() {
    let unitID = this.data.unit[this.data.isUnit].ID;
    let customerID = this.data.customer[this.data.customerIndex].ID;
    let departmentID = this.data.department[this.data.departmentIndex].ID;
    let saletypeID = this.data.saletype[this.data.saletypeIndex].ID;

    let year = this.data.dateTimeArray1[0][this.data.dateTime1[0]]
    let month = this.data.dateTimeArray1[1][this.data.dateTime1[1]]
    let date = this.data.dateTimeArray1[2][this.data.dateTime1[2]]
    let hour = this.data.dateTimeArray1[3][this.data.dateTime1[3]]
    let minu = this.data.dateTimeArray1[4][this.data.dateTime1[4]]

    let stringTime = year + "/" + month + "/" + date + " " + hour + ":" + minu + ":00"
    let timestamp2 = Date.parse(new Date(stringTime));
    let update = "/Date(" + timestamp2 + "+0800)/";

    if (customerID == 0) {
      wx.showToast({
        title: '请选择购货客户'
      })
      return;
    }
    if (unitID == 0) {
      wx.showToast({
        title: '请选择会计单位'
      })
      return;
    }

    if (departmentID == 0) {
      wx.showToast({
        title: '请选择销售部门',
      })
      return;
    }

    if (saletypeID == 0) {
      wx.showToast({
        title: '请选择销售类型',
      })
      return;
    }
    if (this.data.addrs == "") {
      wx.showToast({
        title: '请填写送货地址',
      })
      return;
    }

    let detailsArray = [];

    for (var i = 0; i < this.data.obj.length; i++) {
      if (this.data.obj[i].Goods_Name == "请选择存货") {
        wx.showToast({
          title: '存货不能为空',
        })
        return;
      }
      if (this.data.obj[i].goodsNum == null) {
        wx.showToast({
          title: '报货数量不能为空',
        })
        return;
      }
      if (this.data.obj[i].goodsSecondNum == null) {
        wx.showToast({
          title: '辅数量不能为空',
        })
        return;
      }
      var dmo = {
        SaleGoods_ID: this.data.obj[i].SaleGoods_ID,
        UnitNum: this.data.obj[i].goodsNum,
        SecondNumber: this.data.obj[i].goodsSecondNum,
        Price: this.data.obj[i].Price,
        PolicyPrice: this.data.obj[i].PolicyPrice
        // PolicyPrice: 10
      }
      detailsArray.push(dmo)
    }


    let method = insert;
    let params = [{
      "Customer_ID": customerID,
      // "LoadTime": update,
      "Date": update,
      "DeliveryTime": update,
      "AccountingUnit_ID": unitID,
      "Department_ID": departmentID,
      "SaleKind_ID": saletypeID,
      "DeliverAddress": this.data.addrs,
      "Details": detailsArray

    }];
    network.transfer_request(method, params, function(res) {
      if (res.result != null) {
        wx.showModal({
          title: '新建订单No.' + res.result,
          content: '新建成功,是否返回上级列表',
          success: function(res) {
            if (res.cancel) {} else {
              wx.navigateBack({
                delta: 1
              })
            }
          },
          fail: function(res) {}
        })
      }
    })

  },
  changeDateTime1(e) {
    this.setData({
      dateTime1: e.detail.value
    });

  },
  util: function(currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function() {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false,
        });
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      // 调用函数时，传入new Date()参数，返回值是日期和时间
      // var timet = utilll.formatTime(new Date());
      // 再通过setData更改Page()里面的data，动态更新页面的数据
      this.setData({
        // time: timet,
        showModalStatus: true,
      });
    }
  },
  util1: function(currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function() {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showModalStatus1: false
        });
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      // 调用函数时，传入new Date()参数，返回值是日期和时间
      // var timet = utilll.formatTime(new Date());
      // 再通过setData更改Page()里面的data，动态更新页面的数据
      this.setData({
        // time: timet,
        showModalStatus1: true
      });
    }
  }
})