// pages/car/add.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModal: false,
    defaultText: '请选择',
    isSubmitting: false,

    shipTypeArray: [], //船型
    shipType: '',

    shipArray:[], //船主
    shipIndex:null,

    certificatePathList:[], //船舶证书
    contractPathList:[],  //安全环保合同
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //船型
    let treeData = app.globalData.treeArr
    for (const element of treeData) {
      let arrStr;
      switch (element.dictValue) {
        case 'ship_type':
          arrStr = "shipTypeArray";
          break;
      }
      this.setData({
        [arrStr]: element.children
      })
    }
    // 默认填充船主信息
    this.setData({
      shipId     : wx.getStorageSync('id'),
      shipMobile : wx.getStorageSync('phone')
    })
    //获取船主下拉列表
    this.loadUserData()
  },

  //船主
  loadUserData:function(){
    app.request.GET({
      url: app.API.roleUser,
      params: {
        roleName : '船主',
      },
      page: this,
      successFun: true
    }).then(res => {
      this.setData({
        shipArray : res.data.data,
        shipIndex : app.util.getDicIndex(res.data.data, this.data.shipId, 'id')
      })
      if(this.data.shipId){
        this.setData({
          shipMobile : this.data.shipArray[this.data.shipIndex].phone,
        })
      }
    })
  },

  //下拉选择
  bindPickerChange: function (e) { 
    let { pickername } = e.target.dataset
    let getIndex = pickername + 'Index'
    app.util.getPickerIndex(this, getIndex, e);
    switch (pickername) {
      case 'ship': //选择船主
        this.setData({
          shipMobile : this.data.shipArray[this.data.shipIndex].phone,
        })
        break;
    }
  },

  // 单选
  dangerStatusChange: function (e) {
    this.setData({
      [e.currentTarget.dataset.radiotype]: e.detail.value
    })
  },
  //多选
  checkboxChange: function (e) {
    this.setData({
      [e.currentTarget.dataset.checkboxtype]: e.detail
    })
  },

  //图片上传
  afterRead:function(event){
    const { file } = event.detail;
    const { type } = event.currentTarget.dataset
    app.request.uploadDIY({
      url: app.API.uploadImgMap,
      page: this,
      filePaths:file.url,
      setfiled:'file',
      params: {},
      //isToken: false,
      isLoading: false,
      successFun: true
    }).then(res => {
        const imgArray = this.data[type];
        imgArray.push({
          ...file,
          url: app.host.BASEIMG_URL + JSON.parse(res.data).data.imageFile,
          imgUrl: JSON.parse(res.data).data.imageFile
        });
        this.setData({
          [type]: imgArray
        });
    })
  },

  // 删除图片
  deleteImg: function (event) {
    const { type } = event.currentTarget.dataset
    let getFileList = this.data[type];
    getFileList.splice(event.detail.index, 1)
    this.setData({
      [type]: getFileList
    })
  },

  //提交事件
  formSubmit: function ({detail:{value}}) {
    var warn = ""; //弹框时提示的内容
    /** 船舶证书 certificatePathList  （必传）  图片处理 START **/
    let getcertificatePathList = this.data.certificatePathList
    if(getcertificatePathList.length < 1){
      warn = "请上传船舶证书图片！";
    }
    let certificateNameList = []
    let certificatePathList = []
    getcertificatePathList.forEach((element,index) => {
      certificateNameList.push('图片'+(index+1)+'.'+element.imgUrl.split('.')[1])
      certificatePathList.push(element.imgUrl)
    });
    value.certificateNameList = certificateNameList
    value.certificatePathList = certificatePathList
    /** 图片处理 END **/

    /** 安全环保合同 contractPathList  （非必传）  图片处理 START **/
    let getcontractPathList = this.data.contractPathList
    if(getcontractPathList.length < 1){
      // warn = "请上传安全环保合同！";
    }else{
      // 上传了安保合同才处理
      let contractNameList = []
      let contractPathList = []
      getcontractPathList.forEach((element,index) => {
        contractNameList.push('图片'+(index+1)+'.'+element.imgUrl.split('.')[1])
        contractPathList.push(element.imgUrl)
      });
      value.contractNameList = contractNameList
      value.contractPathList = contractPathList
    }
    /** 图片处理 END **/

    if (value.shipNumber == '') {
      warn = "请输入船舶号";
    } else if (value.shipType == '') {
      warn = "请输入船型";
    } else if (value.shipId == '') {
      warn = "请选择船主";
    }
    if (warn != '') {
      app.util.checkForm(warn);
    } else {
      app.request.POST({
        url: app.API.shipAdd,
        params: value,
        page: this,
        isLoadingTxt: '提交中...',
        isSubmitting: true,
        successFun: true
      }).then(res => {
        wx.showToast({
          title: '新增成功',
          icon: 'success',
          duration: 2000,
          mask:true,
          complete: function () {
            setTimeout(() => {
              wx.navigateBack()
            }, 1500) //延迟时间  
          }
        })
      })
    }
  }

})