// pages/create-order/index.js
import http from '../../utils/http'
import util from '../../utils/util'
import api from '../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['设备租赁订单', '租赁设备添加'],
    tabIndex: 1,
    work_points: [],
    pointIndex: -1,
    id: -1,
    project: null,
    remark: '',
    devices: [],
    showAdd: false,
    device_types: [],
    rent_types: [],
    typeIndex: -1,
    nameIndex: -1,
    specIndex: -1,
    rentIndex: -1,
    selectName: '',
    selectSepc: '',
    selectRent: '',
    customName: false,
    customSpec: false,
    customRent: false,
    customNameVal: '',
    customNameSpecVal: '',
    customRentVal: '',
    device_name: '',
    device_quantity: '',
    device_price: '',
    showDate: false,
    start_date: '',
    end_date: '',
    order_id: '',
    // create/edit
    type: 'create',
    order: {},
    selectIndex: -1,
    // create/edit
    dialog_type: 'create',
    default_dates: [],
    device_total: 0,
    device_money: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id ? options.id : 1
    var type = options.type ? options.type : 'create'
    var order_id = options.order_id ? options.order_id : ''
    var that = this
    this.setData({
      id,
      type,
      order_id
    })
    api.getProject(this)
    api.getByName(this, 'work-points/get', 'work_points', { project_id: id });
    api.getByName(this, 'devices/getThreeLevel', 'device_types');
    api.getByName(this, 'rent-types/get', 'rent_types');
    if (order_id) {
      api.getByName(this, 'orders/detail', 'order', { id: order_id }, function (res) {
        that.initData()
      });
      wx.setNavigationBarTitle({
        title: '修订订单',
      })
    }
  },
  closeshow() {
    this.setData({
      showAdd: false
    })
  },
  selectDevice: function (e) {
    var newIndex = e.currentTarget.dataset.index == this.data.selectIndex ? -1 : e.currentTarget.dataset.index
    this.setData({
      selectIndex: newIndex
    })
  },

  initData: function () {
    var order = this.data.order,
      work_points = this.data.work_points,
      pointIndex = this.data.pointIndex

    for (var i = 0; i < work_points.length; ++i) {
      if (work_points[i].id == order.work_point_id) {
        pointIndex = i;
        break;
      }
    }
    var devices = order.order_devices
    var local_devices = []
    for (var i = 0; i < devices.length; ++i) {
      var device = devices[i]
      local_devices.push({
        type_name: device.device_type ? device.device_type.name : '',
        type_id: device.device_type ? device.device_type.id : '',
        name: device.device_name ? device.device_name.name : '',
        spec: device.spec ? device.spec.name : '',
        rent: device.rent_type ? device.rent_type.name : '',
        quantity: device.quantity,
        price: device.price / 100,
        start_date: device.start_date,
        end_date: device.end_date
      })
    }
    this.setData({
      pointIndex,
      remark: order.remark,
      devices: local_devices
    })
    this.updateDeviceStat()
  },

  submit: function (e) {
    var type = e.currentTarget.dataset.type
    var is_draft = type == 'draft' ? 1 : 2
    var submit_type = this.data.type
    if (this.data.pointIndex < 0) {
      util.error('需求工点必填');
      return false;
    }
    if (this.data.devices.length <= 0) {
      util.error('请选择租赁设备');
      return false;
    }
    var work_point = this.data.work_points[this.data.pointIndex]
    var url = submit_type == 'create' ? 'orders/create' : 'orders/update'
    var that = this
    http({
      url: url,
      data: {
        id: this.data.order_id,
        project_id: this.data.id,
        work_point_id: work_point.id,
        remark: this.data.remark,
        devices: this.data.devices,
        is_draft: is_draft
      },
      success: function (res) {
        if (res.code == 0) {
          util.success('操作成功')
          setTimeout(function () {
            var url = '/pages/order/index?id=' + that.data.id
            if (is_draft == 1) {
              wx.navigateBack({
                delta: 0,
              })
            } else {
              wx.redirectTo({
                url: url,
              })
            }
          }, 1000)
        }
      }
    })
  },

  switchTab: function (e) {
    this.setData({
      tabIndex: e.currentTarget.dataset.index
    })
  },

  deleteDevice: function () {
    var devices = this.data.devices
    var index = this.data.selectIndex
    devices.splice(index, 1)
    this.setData({
      devices,
      selectIndex: -1
    })
    this.updateDeviceStat()
  },

  editDevice: function () {
    var devices = this.data.devices
    var index = this.data.selectIndex
    if (index < 0) return false
    var device = devices[index]
    var typeIndex = -1
    var device_types = this.data.device_types
    var default_dates = [device.start_date, device.end_date]
    var names = null
    var nameIndex = -1
    for (var i = 0; i < device_types.length; ++i) {
      if (device_types[i].id == device.type_id) {
        typeIndex = i;
        names = device_types[i].names
        break;
      }
    }

    var specs = null
    var specIndex = -1
    if (names) {
      for (var i = 0; i < names.length; ++i) {
        if (names[i].name == device.name) {
          specs = names[i].specs
          nameIndex = i;
          break;
        }
      }
    }
    if (specs) {
      for (var i = 0; i < specs.length; ++i) {
        if (specs[i].name == device.spec) {
          specIndex = i;
          break;
        }
      }
    }
    var rent_types = this.data.rent_types
    var rentIndex = -1;
    for (var i = 0; i < rent_types.length; ++i) {
      if (rent_types[i].name == device.rent) {
        rentIndex = i;
        break;
      }
    }
    this.setData({
      device_name: device.name,
      selectName: device.name,
      selectSpec: device.spec,
      selectRent: device.rent,
      typeIndex,
      nameIndex,
      specIndex,
      rentIndex,
      start_date: device.start_date,
      end_date: device.end_date,
      device_quantity: device.quantity,
      device_price: device.price,
      showAdd: true,
      dialog_type: 'edit',
      default_dates: default_dates
    })
  },

  getCustom: function (name) {
    var index = name + 'Index'
    var caseName = util.firstCase(name)
    var custom = 'custom' + caseName
    var customVal = custom + 'Val'
    var select = 'select' + caseName
    var data = this.data
    return data[custom] ? data[customVal] : (data[index] >= 0 ? data[select] : '')
  },

  stopClose() {
    this.setData({
      showAdd: true
    })
  },

  addDevice: function () {
    if (this.data.typeIndex < 0) {
      util.error('设备类型必填');
      this.stopClose()
      return false;
    }
    if (!this.getCustom('name')) {
      util.error('设备名称必填')
      this.stopClose()
      return false
    }
    if (!this.getCustom('spec')) {
      util.error('规格型号必填')
      this.stopClose()
      return false
    }
    if (!this.getCustom('rent')) {
      util.error('租赁方式必填')
      this.stopClose()
      return false
    }
    if (!this.data.device_quantity) {
      util.error('设备数量必填')
      this.stopClose()
      return false
    }
    if (!this.data.device_price) {
      util.error('设备单价必填')
      this.stopClose()
      return false
    }
    if (!this.data.start_date) {
      util.error('租赁时间必填')
      this.stopClose()
      return false
    }
    var devices = this.data.devices
    var type = this.data.device_types[this.data.typeIndex]
    var name = this.getCustom('name')
    var spec = this.getCustom('spec')
    var rent = this.getCustom('rent')
    var price = Math.round(this.data.device_price * 100) / 100
    var device = {
      type_name: type.name,
      type_id: type.id,
      name: name,
      spec: spec,
      rent: rent,
      quantity: this.data.device_quantity,
      price: price,
      start_date: this.data.start_date,
      end_date: this.data.end_date
    }
    var dialog_type = this.data.dialog_type
    if (dialog_type == 'create') {
      devices.push(device)
    } else {
      devices[this.data.selectIndex] = device
    }
    this.setData({
      devices,
      typeIndex: -1,
      nameIndex: -1,
      specIndex: -1,
      rentIndex: -1
    })
    this.setData({
      showAdd: false
    })
    this.updateDeviceStat()
  },
  onClose: function (e) {
    if (e.detail == 'confirm') return false;
    return true
  },
  updateDeviceStat() {
    var devices = this.data.devices
    var device_total = devices.length
    var device_money = 0
    for (var i = 0; i < devices.length; ++i) {
      device_money = device_money + Math.round(parseFloat(devices[i].price) * parseInt(devices[i].quantity) * 100)
    }
    device_money = device_money / 100;
    this.setData({
      device_total,
      device_money
    })
  },

  onChange: function (e) {
    var name = e.currentTarget.dataset.name
    var val = e.detail.value
    if (['customSpec', 'customName', 'customRent'].indexOf(name) != -1) {
      val = e.detail;
    }
    this.setData({
      [name]: val
    })
    if (name == 'device_price') {
      let price
      if (/^(\d?)+(\.\d{0,2})?$/.test(val)) { //正则验证，提现金额小数点后不能大于两位数字
        price = val;
      } else {
        price = val.substring(0, val.length - 1);
      }
      this.setData({
        device_price: price
      })
    }
    if (name == 'customName' && val) {
      this.setData({
        customSpec: true,
      })
    }
    if (name == 'typeIndex') {
      this.setData({
        nameIndex: -1,
        specIndex: -1
      })
    }
    if (name == 'nameIndex') {
      var device_types = this.data.device_types
      var typeIndex = this.data.typeIndex
      var nameIndex = this.data.nameIndex
      var selectName = device_types[typeIndex].names[nameIndex].name
      this.setData({
        selectName: selectName,
        specIndex: -1
      })
    }
    if (name == 'specIndex') {
      var device_types = this.data.device_types
      var typeIndex = this.data.typeIndex
      var nameIndex = this.data.nameIndex
      var specIndex = this.data.specIndex
      var selectSpec = device_types[typeIndex].names[nameIndex].specs[specIndex].name
      this.setData({
        selectSpec: selectSpec
      })
    }
    if (name == 'rentIndex') {
      var rent_types = this.data.rent_types
      var rentIndex = this.data.rentIndex
      var selectRent = rent_types[rentIndex].name
      this.setData({
        selectRent: selectRent
      })
    }
  },

  switchShowAdd: function (e) {
    var show = e.currentTarget.dataset.show
    if (show) {
      this.setData({
        device_name: '',
        typeIndex: -1,
        start_date: '',
        end_date: '',
        device_quantity: '',
        device_price: '',
        default_dates: []
      })
    }
    this.setData({
      showAdd: show,
      dialog_type: 'create'
    })
  },

  switchShowDate: function (e) {
    this.setData({
      showDate: e.currentTarget.dataset.show
    })
  },

  confirmDate: function (e) {
    this.switchShowDate(e)
    var [start_date, end_date] = e.detail;
    start_date = util.formatDate(start_date)
    end_date = util.formatDate(end_date)
    this.setData({
      start_date,
      end_date
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})