// pages/order/detail/detail.js
var app = getApp()
var network = require("../../../utils/net.js")
var dateTimePicker = require('../../../utils/dateTimePicker.js');
var utilll = require('../../../utils/util.js');
var timechage = require("../../../utils/dateTimeUtil.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/GetGoods";
var getSaleKind = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetSaleKind";
var getEmployee = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetEmployee";
var getStore = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetStore"
var getTakeGoodsType = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetTakeGoods_Type"
var getGoodsDetail = "/MainSystem/B3MiniProgramRpc/Rpcs/BaseInfoRpc/GetGoodsDetailWithPrice"
var getCustomerInfo = "/MainSystem/B3MiniProgramRpc/XuRpcs/Employee/OrderRpc/GetCustomerRefDto"
let insert = '/MainSystem/B3MiniProgramRpc/XuRpcs/Employee/OrderRpc/Insert'
var getUserPrifile = "/MainSystem/B3MiniProgramRpc/XuRpcs/Employee/AccountRpc/GetUserPrifile"
var getEmployeePrifile = "/MainSystem/B3MiniProgramRpc/XuRpcs/Customer/AccountRpc/GetEmployeePrifile"
// 获取完整的年月日 时分秒，以及默认显示的数组'
function setTime(that) {
  // 精确到分的处理，将数组的秒去掉
  var obj1 = dateTimePicker.dateTimePicker(2018, 2030);
  var lastArray = obj1.dateTimeArray.pop();
  var lastTime = obj1.dateTime.pop();

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

  that.timeConversion();
}

function GetBaseInfoList(that, method, params) {
  network.transfer_request(method, params, function(res) {
    that.setData({
      currency: res.result
    });
  });
}

function GetGoodsInfo(that, dmo, detail) {
  var params = [{
    "Goods_ID": detail.SaleGoods_ID,
    "Customer_ID": dmo.Customer_ID,
    "AccountingUnit_ID": dmo.AccountingUnit_ID,
    "Date": dmo.LoadTime,
  }]
  network.transfer_request(getGoodsDetail, params, function(res) {
    detail.Goods_SecondUnit = res.result.Goods_SecondUnit;
    detail.Goods_UnitConvertDirection = res.result.Goods_UnitConvertDirection;
    detail.Goods_MainUnitRatio = res.result.Goods_MainUnitRatio;
    detail.Goods_SecondUnitRatio = res.result.Goods_SecondUnitRatio;
    detail.Unit = res.result.Unit;
    detail.LeftRatio = res.result.LeftRatio;
    detail.RightRatio = res.result.RightRatio;
    if (res.result.RightRatio == null) {
      detail.RightRatio = Number(1)
    }
    if (res.result.LeftRatio == null) {
      detail.LeftRatio = Number(1)
    }
    detail.Price = res.result.Price;
    detail.PolicyPrice = res.result.PolicyPrice;
    that.setData({
      dmo: dmo
    });
  });
}

function GetCustomerInfo(that, dmo, succession) {
  var params = [app.globalData.userID, ["Name", "Department_ID", "Department_Name", "Employee_ID", "Employee_Name", "AccountingUnit_ID", "AccountingUnit_Name", "TakeGoods_Type", "Address","CheckOutManner_ID"]]
  network.transfer_request(getCustomerInfo, params, function(res) {
    var obj = JSON.parse(res.result);
    dmo.Customer_ID = app.globalData.userID;
    dmo.Customer_Name = obj.Name;
    dmo.CheckOutManner_ID = obj.CheckOutManner_ID;
    dmo.Department_ID = obj.Department_ID;
    dmo.Department_Name = obj.Department_Name;
    dmo.Employee_ID = obj.Employee_ID;
    dmo.Employee_Name = obj.Employee_Name;
    dmo.AccountingUnit_ID = obj.AccountingUnit_ID;
    dmo.AccountingUnit_Name = obj.AccountingUnit_Name;
    if (obj.TakeGoods_Type != null)
      dmo.TakeGoods_Type = obj.TakeGoods_Type.Name;
    else
      dmo.TakeGoods_Type = "";
    dmo.DeliverAddress = obj.Address;
    that.setData({
      dmo: dmo
    });
    succession();
  });
}

Page({

  data: {
    currentTab: 0,
    winHeight: app.globalData.winHeight,
    which: '',
    rowIdx: -1,
    dmo: {
      Details: [],
    },
    dateTimeArray1: null,
    dateTime1: null,
    backPage: "",
  },

  onLoad: function(options) {
    var that = this;
    var dmo = this.data.dmo;
    setTime(that);
    GetCustomerInfo(that, dmo, function(res) {
      that.getEmployeePrifile();
    });
  },

  getEmployeePrifile: function() {
    var that = this;
    network.transfer_request(getEmployeePrifile, [this.data.dmo.Employee_ID], function(res) {
      that.data.dmo.SaleKind_ID = res.result.Order_SaleKind_ID;
      that.data.dmo.SaleKind_Name = res.result.Order_SaleKind_Name;
      that.data.dmo.Store_ID = res.result.Order_Store_ID;
      that.data.dmo.Store_Name = res.result.Order_Store_Name;
      that.setData({
        dmo: that.data.dmo
      });
    });
  },

  onShow: function() {
    var that = this;
    if (this.data.backPage == "goodsNameChoosePage") {
      var goodsArr = app.globalData.goodsNameArray;
      app.globalData.goodsNameArray = [];
      if (goodsArr.length > 0) {
        // 在此添加货品价格的请求        
        for (var i = 0; i < goodsArr.length; i++) {
          let newobj = {};
          this.data.dmo.Details.push(newobj);
          var itemIndex = this.data.dmo.Details.length - 1;
          var detail = this.data.dmo.Details[itemIndex];
          detail.SaleGoods_ID = goodsArr[i].SaleGoods_ID;
          detail.Goods_Name = goodsArr[i].Goods_Name;
          GetGoodsInfo(this, this.data.dmo, detail);
        }
      }
    }
  },

  /**
   * 滑动切换tab
   */
  bindChange: function(e) {
    this.setData({
      currentTab: e.detail.current
    });
  },
  /**
   * 点击tab切换
   */
  swichNav: function(e) {
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

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

  // 添加一个时间转换
  timeConversion: function() {
    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 timestamp = Date.parse(new Date(stringTime));
    let loadTime = "/Date(" + timestamp + "+0800)/";
    this.data.dmo.LoadTime = loadTime;
    this.setData({
      dmo: this.data.dmo,
    })
  },
  getAddrs: function(e) {
    this.data.dmo.DeliverAddress = e.detail.value;
    this.setData({
      dmo: this.data.dmo
    });
  },

  getRemark: function(e) {
    this.data.dmo.Remark = e.detail.value;
    this.setData({
      dmo: this.data.dmo
    });
  },

  powerDrawer: function(e) {
    let x = e.currentTarget.dataset.x;
    if (x == "存货") {
      var dmo = this.data.dmo;
      if (dmo.AccountingUnit_ID == null || dmo.Customer_ID == null || dmo.LoadTime == null) {
        wx.showModal({
          title: '提示',
          content: '请先选择客户及会计单位',
        });
        return;
      }
    }
    let idx = e.currentTarget.dataset.idx;
    if (idx == undefined)
      idx = -1;
    this.showDialog(x, '');
    this.setData({
      which: x,
      rowIdx: idx
    });
    this.util();
  },

  // 遮罩存货输入框
  select: function(e) {
    var value = e.detail.value;
    var x = this.data.which;
    this.showDialog(x, value);
  },

  showDialog: function(x, value) {
    var method = null;
    let params = [{
      "InputValue": value,
      "PageIndex": 0,
      "PageSize": 100
    }];
    switch (x) {
      case "购货客户":
        method = getCustomer;
        break;
      case "会计部门":
        method = getAccountingUnit;
        break;
      case "部门":
        method = getDept;
        break;
      case "销售类型":
        method = getSaleKind;
        break;
      case "业务员":
        method = getEmployee;
        break;
      case "仓库":
        method = getStore;
        break;
      case "配送方式":
        method = getTakeGoodsType;
        params = [];
        break;
      case "存货":
        method = getGoods;
        break;
    }
    GetBaseInfoList(this, method, params);
  },

  dialogClose: function(e) {
    this.util();
  },

  itemclick: function(e) {
    var flag = true;
    var x = this.data.which;
    var item = e.currentTarget.dataset.item;
    var dmo = this.data.dmo;
    switch (x) {
      case "购货客户":
        dmo.Customer_ID = item.ID;
        dmo.Customer_Name = item.Name;
        flag = false;
        GetCustomerInfo(this, dmo);
        break;
      case "会计部门":
        dmo.AccountingUnit_ID = item.ID;
        dmo.AccountingUnit_Name = item.Name;
        break;
      case "部门":
        dmo.Department_ID = item.ID;
        dmo.Department_Name = item.Name;
        break;
      case "销售类型":
        dmo.SaleKind_ID = item.ID;
        dmo.SaleKind_Name = item.Name;
        break;
      case "业务员":
        dmo.Employee_ID = item.ID;
        dmo.Employee_Name = item.Name;
        break;
      case "仓库":
        dmo.Store_ID = item.ID;
        dmo.Store_Name = item.Name;
        break;
      case "配送方式":
        dmo.TakeGoods_Type = item.Name;
        break;
      case "存货":
        var idx = this.data.rowIdx;
        var detail = dmo.Details[idx];
        detail.SaleGoods_ID = item.ID;
        detail.Goods_Name = item.Name;
        flag = false;
        GetGoodsInfo(this, dmo, detail);
        break;
    }
    if (flag) {
      this.setData({
        dmo: dmo
      });
    }
    this.util();
  },

  getGoodsNum: function(e) {
    let idx = e.target.dataset.idx;
    var detail = this.data.dmo.Details[idx];
    let value = Number(e.detail.value);
    if (isNaN(value)) {
      wx.showModal({
        title: '提示',
        content: '输入格式不正确',
      });
    } else {
      detail.UnitNum = value;

      var numberNumber = detail.UnitNum / detail.RightRatio * detail.LeftRatio;
      if (detail.Goods_UnitConvertDirection == 0 || detail.Goods_UnitConvertDirection == 1) {
        detail.SecondNumber = numberNumber / (detail.Goods_MainUnitRatio) * (detail.Goods_SecondUnitRatio);
      }
    }
    this.setData({
      dmo: this.data.dmo
    })
  },

  getSecondNum: function(e) {
    let idx = e.target.dataset.idx;
    var detail = this.data.dmo.Details[idx];
    let value = Number(e.detail.value);
    if (isNaN(value)) {
      wx.showModal({
        title: '提示',
        content: '输入格式不正确',
      });
    } else {
      detail.SecondNumber = value;

      var numberNumber = detail.SecondNumber / detail.LeftRatio * detail.RightRatio;
      if (detail.Goods_UnitConvertDirection == 0 || detail.Goods_UnitConvertDirection == 2) {
        detail.UnitNum = numberNumber / (Goods_SecondUnitRatio) * (Goods_MainUnitRatio);
      }
    }
    this.setData({
      dmo: this.data.dmo
    })
  },

  // 
  getPrice: function(e) {
    let idx = e.target.dataset.idx;
    let value = Number(e.detail.value);
    if (isNaN(value)) {
      wx.showToast({
        title: '提示',
        content: '输入格式不正确',
      })
    } else
      this.data.dmo.Details[idx].Price = value;
    this.setData({
      dmo: this.data.dmo
    })
  },

  // 删除
  deleteItem: function(e) {
    let idx = e.target.dataset.idx;
    this.data.dmo.Details.splice(idx, 1)
    this.setData({
      dmo: this.data.dmo
    })
  },

  // 点击添加存货
  add: function(e) {
    // 新增获取存货
    var dmo = this.data.dmo;
    if (dmo.Customer_ID == null) {
      wx.showToast({
        title: '请选择购货客户'
      })
      return;
    }
    if (dmo.AccountingUnit_ID == null) {
      wx.showToast({
        title: '请选择会计单位'
      })
      return;
    }
    wx.navigateTo({
      url: '../../goodaNameChooseTemplate/goodaNameChooseTemplate?unitID=' + dmo.AccountingUnit_ID + '&customerID' + dmo.Customer_ID,
    })
  },

  // 提交
  submitForm: function() {
    var dmo = this.data.dmo;
    if (dmo.Customer_ID == null) {
      wx.showToast({
        title: '个人信息获取不完善'
      })
      return;
    }
    /*
    if (dmo.AccountingUnit_ID == null) {
      wx.showToast({
        title: '请选择会计单位'
      })
      return;
    }

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

    if (dmo.Employee_ID == null) {
      wx.showToast({
        title: '请选择业务员',
      })
      return;
    }

    if (dmo.Store_ID == null) {
      wx.showToast({
        title: '请选择仓库',
      })
      return;
    }

    if (dmo.SaleKind_ID == null) {
      wx.showToast({
        title: '请选择销售类型',
      })
      return;
    }

    if (dmo.TakeGoods_Type == "") {
      wx.showToast({
        title: '请选择配送方式',
      })
      return;
    }
   */

    // if (dmo.DeliverAddress == "") {
    //   wx.showToast({
    //     title: '请填写送货地址',
    //   })
    //   return;
    // }

    if (dmo.Details.length <= 0) {
      wx.showToast({
        title: '存货不能为空',
      })
      return;
    }

    for (var i = 0; i < dmo.Details.length; i++) {
      if (dmo.Details[i].SaleGoods_ID == null) {
        wx.showToast({
          title: '存货不能为空',
        })
        return;
      }
      if (dmo.Details[i].UnitNum == null && dmo.Details[i].SecondNumber == null) {
        wx.showToast({
          title: '请输入报货数量/重量',
        })
        return;
      }

    }

    let method = insert;
    let params = [{
      "Customer_ID": dmo.Customer_ID,
      "LoadTime": dmo.LoadTime,
      "AccountingUnit_ID": dmo.AccountingUnit_ID,
      "Department_ID": dmo.Department_ID,
      "SaleKind_ID": dmo.SaleKind_ID,
      "Employee_ID": dmo.Employee_ID,
      "Store_ID": dmo.Store_ID,
      "TakeGoods_Type": dmo.TakeGoods_Type,
      "DeliverAddress": dmo.DeliverAddress,
      "Remark": dmo.Remark,
      "Details": dmo.Details,
      "CheckOutManner_ID": dmo.CheckOutManner_ID,
      "ID": dmo.ID
    }];

    network.transfer_request(method, params, function(res) {
      if (res.result != null) {
        wx.showModal({
          title: '新建订单No.' + res.result,
          content: '新建成功,是否返回首页',
          success: function(res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1
              })
            }
          },
          fail: function(res) {}
        })
      }
    })
  },

  util: function() {
    /* 动画部分 */
    // 第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
      })

      //关闭  
      this.setData({
        showModalStatus: !this.data.showModalStatus,
      });
    }.bind(this), 200)

  },
})