// pages/create-order/index.js
import http from '../../utils/http'
import util from '../../utils/util'
import api from '../../utils/api'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['内部设备调用', '调用设备添加'],
    tabIndex: 0,
    work_points: [],
    pointIndex: -1,
    id: -1,
    project: null,
    remark: '',
    devices: [],
    // create/edit
    type: 'create',
    order_id: '',
    loadedOrder: false,
    role: null,
    // 审核(check)|确认(pass)|重新提交(re-submit)|退回(back)
    actionType: null,
    order: null,
    canEdit: true,
    showBack: false,
    showRent: false,
    showDate: false,
    deviceIndex: -1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // options = {
    //   id: 1,
    //   type: 'edit',
    //   order_id: 194
    // }
    var id = options.id ? options.id : 1
    var type = options.type ? options.type : 'create'
    var order_id = options.order_id ? options.order_id : ''
    this.setData({
      id,
      type,
      order_id
    })
    this.init()
  },

  init() {
    var order_id = this.data.order_id
    api.getProject(this)
    api.getByName(this, 'work-points/get', 'work_points');
    if (order_id) {
      var that = this

      api.getByName(this, 'orders/detail', 'order', {
        id: order_id
      }, function (res) {
        api.getByName(that, 'orders/getRole', 'role', {
          id: that.data.order ? that.data.order.project_id : ''
        }, function (res) {
          that.updateActionType()
          that.initData()
        });
      });
      wx.setNavigationBarTitle({
        title: '订单详情',
      })
    }
  },

  updateActionType: function () {
    var actionType = ''
    var role = this.data.role
    var order = this.data.order
    if (order.level == role.level) {
      if (['checking', 'checked'].indexOf(order.status_key) != -1 && role && role.rights && role.rights.applyCheck) actionType = 'check';
      else if (order.status_key == 'reject' && role.key == 'machine') actionType = 're-submit'
      else if (order.status_key == 'checked' && role.key == 'machine') actionType = 'back'
    }
    var canEdit = (actionType == 're-submit');
    if (order.is_draft == 1) {
      canEdit = true
      actionType = 'edit'
    }
    this.setData({
      actionType,
      canEdit
    })
  },

  navigate: function (e) {
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },

  switchChecked: function (e) {
    var index = e.detail.index
    var devices = this.data.devices
    devices[index].checked = !devices[index].checked
    this.setData({
      devices
    })
  },

  switchShow: function (e) {
    var name = e.currentTarget.dataset.name
    var val = this.data[name]
    this.setData({
      [name]: !val
    })
  },

  check: function (e) {
    var type = e.currentTarget.dataset.type
    var that = this
    var msg = '确认通过审核吗？'
    if (type == 'reject') msg = '确认驳回申请吗？'
    else if (type == 'pass' || type == 're-submit') msg = '确认提交吗？'
    else if (type == 'back') {
      this.switchShow(e)
      return false
    } else if (type == 're-rent') {
      this.switchShow(e)
      return false
    }
    Dialog.confirm({
        title: '提示',
        message: msg,
      })
      .then(() => {
        that.submitCheck(e)
      })
  },
  editDate: function (e) {
    var deviceIndex = e.detail.index
    var device = this.data.devices[deviceIndex]
    var default_dates = [device.start_date, device.end_date]

    this.setData({
      showDate: true,
      default_dates,
      deviceIndex
    })
  },
  confirmDate: function (e) {
    var [start_date, end_date] = e.detail;
    start_date = util.formatDate(start_date)
    end_date = util.formatDate(end_date)
    var devices = this.data.devices
    var deviceIndex = this.data.deviceIndex
    if (this.data.actionType == 'back') {
      var init_end_date = this.data.devices[deviceIndex].init_end_date
      if (init_end_date >= start_date) {
        util.error('该设备还在使用中，请重新选择续租时间')
        return false;
      }
    }
    devices[deviceIndex].start_date = start_date
    devices[deviceIndex].end_date = end_date
    devices[deviceIndex].is_change = true
    this.setData({
      devices,
      showDate: false
    })

  },
  submitCheck: function (e) {
    var type = e.currentTarget.dataset.type
    var is_change = e.currentTarget.dataset.change
    var that = this
    if (this.data.devices.length <= 0) {
      util.error('请选择调用设备');
      return false;
    }
    if (type == 'back') {
      var devices = this.data.devices
      var find = false;
      for (var i = 0; i < devices.length; ++i) {
        if (devices[i].checked) {
          find = true;
          break;
        }
      }
      if (!find) {
        util.error('归还设备不能为空');
        return false;
      }
      this.switchShow(e)
    }
    http({
      url: 'orders/check',
      data: {
        id: this.data.order_id,
        type: type,
        remark: this.data.remark,
        devices: this.data.devices,
        is_change: is_change
      },
      success: function (res) {
        if (res.code == 0) {
          util.success('操作成功')
          setTimeout(function () {
            that.init()
          }, 1000)
        }
      }
    })
  },

  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;
      }
    }
    this.setData({
      pointIndex,
      remark: order.remark,
      devices: order.inner_devices,
      loadedOrder: true
    })
  },

  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;
    }
    if (type == 're-rent') {
      var devices = this.data.devices
      for (var i = 0; i < devices.length; ++i) {
        if (devices[i].start_date <= devices[i].init_end_date) {
          util.error('有设备还在使用中，请重新选择续租时间')
          return false;
        }
      }
      this.setData({
        showRent: false
      })
    }
    var work_point = this.data.work_points[this.data.pointIndex]
    var url = (submit_type == 'create' || type == 're-rent') ? 'orders/createInner' : 'orders/updateInner'
    wx.setStorageSync('sg-added-devices', [])
    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,
        type: type
      },
      success: function (res) {
        if (res.code == 0) {
          util.success('操作成功')
          setTimeout(function () {
            var url = '/pages/order-inner/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
    })
  },

  onChange: function (e) {
    var name = e.currentTarget.dataset.name
    this.setData({
      [name]: e.detail.value
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.type == 'create' || this.data.loadedOrder) {
      var devices = wx.getStorageSync('sg-added-devices')
      devices = devices ? devices : []
      this.setData({
        devices
      })
    }
  },

  goAdd: function (e) {
    var devices = this.data.devices
    wx.setStorageSync('sg-added-devices', devices)
    this.navigate(e)
  },

  deleteDevice: function (e) {
    wx.showModal({
      title: "提示",
      content: "是否确定删除",
      success: (res) => {
        if (res.confirm) {
          var index = e.detail.index
          var devices = this.data.devices
          devices.splice(index, 1)
          this.setData({
            devices
          })
        }
      }
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})