// 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"

var load = "/MainSystem/B3MiniProgramRpc/XuRpcs/Employee/OrderRpc/Load";
let update = '/MainSystem/B3MiniProgramRpc/XuRpcs/Employee/OrderRpc/Update';

function setTime(that) {
  // 获取完整的年月日 时分秒，以及默认显示的数组
  var obj1 = dateTimePicker.dateTimePicker(2018, 2030, that.data.dmo.LoadTime);
  // 精确到分的处理，将数组的秒去掉
  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) {
  var params = [dmo.Customer_ID, ["Department_ID", "Department_Name", "Employee_ID", "Employee_Name", "TakeGoods_Type", "Address"]]
  network.transfer_request(getCustomerInfo, params, function(res) {
    var obj = JSON.parse(res.result);
    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.TakeGoods_Type = obj.TakeGoods_Type;
    dmo.DeliverAddress = obj.Address;
    that.setData({
      dmo: dmo
    });
  });
}

Page({

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

  onLoad: function(options) {
    //正常登录流程进入值为0，分享页面直接进入值为1
    if (app.globalData.shareInState == 1) {
      return;
    }

    if (app.globalData.shareInParameter.id) {
      var detailItemID = parseInt(app.globalData.shareInParameter.id);
      // wx.showModal({
      //   title: '看下ID值',
      //   content: '+++' + detailItemID + '+++',
      // })
      // detailItemType = app.globalData.shareInParameter.detailItemType;
    } else {
      var detailItemID = parseInt(options.ID);
      // detailItemType = options.detailItemType;
      // var detailItemState = options.detailItemState;
      // if (detailItemState == "true") {
      //   that.setData({
      //     showBottomView: true,
      //   });
      // } else {
      //   that.setData({
      //     showBottomView: false,
      //   });
      // }
    }

    var that = this;
    // Number(options.ID)
    network.transfer_request(load, [detailItemID], function(res) {
      app.globalData.shareInParameter = {};
      res.result.LoadTime = timechage.formatTimeTwo(res.result.LoadTime.substring(6, 19), 'Y-M-D h:m');
      console.log(res.result);
      that.setData({
        dmo: res.result
      });
      setTime(that);
    })
  },

  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: function(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();
  },

  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)

  },

  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 = e.detail.value;
    let end = value.charAt(value.length - 1)
    if (end != ".") {
      detail.UnitNum = Number(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 = e.detail.value;
    let end = value.charAt(value.length - 1)
    if (end != ".") {
      detail.SecondNumber = Number(value);

      var numberNumber = detail.SecondNumber / detail.LeftRatio * detail.RightRatio;
      if (detail.Goods_UnitConvertDirection == 0 || detail.Goods_UnitConvertDirection == 2) {
        detail.UnitNum = numberNumber / (detail.Goods_SecondUnitRatio) * (detail.Goods_MainUnitRatio);
      }

      this.setData({
        dmo: this.data.dmo
      })
    }
  },

  getPrice: function (e) {
    let idx = e.target.dataset.idx;
    let value = e.detail.value;
    let end = value.charAt(value.length - 1)
    if (end != ".") {
      this.data.dmo.Details[idx].Price = Number(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) {
    // let newobj = {};
    // this.data.dmo.Details.push(newobj);
    // this.setData({
    //   dmo: this.data.dmo
    // })
    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,
    })
  },

  // 存货明细页面更多按钮
  moreBtnClick: function (e) {
    var that = this;
    var itemList = [
      "审核",
      "撤销"
    ];
    wx.showActionSheet({
      itemList: itemList,
      itemColor: "#2689f8",
      success: function (res) {
        // res.cancel 用户是不是点击了取消按钮
        // res.tapIndex 数组元素的序号，从0开始
        that.moreBtnClickedDetailInfo(itemList[res.tapIndex]);
      }
    })
  },

  // 更多 -> 撤销 -> 审核
  moreBtnClickedDetailInfo: function (item) {
    if (item == "审核") {
      wx.showModal({
        title: "提示",
        content: "++++" + item + "++++",
      })
    } else {
      wx.showModal({
        title: "提示",
        content: "++++" + item + "++++",
      })
    }
  },

  // 保存
  submitForm: function() {
    var dmo = this.data.dmo;
    if (dmo.Customer_ID == null) {
      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 = update;
    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: '提示',
          content: '修改成功,是否返回上级列表',
          success: function(res) {
            if (res.cancel) {} else {
              wx.navigateBack({
                delta: 1
              })
            }
          },
          fail: function(res) {}
        })
      }
    })

  },
})