// pages/contract/add/add.js
import * as UTIL from '../../../utils/util.js';
import * as API from '../../../utils/API.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    id:null,
    form:{
        reviewTime:'2022-01-01',
        buildTime:'2022-01-01',
        startTime:'2022-01-01',
        endTime:'2022-01-01',
        biddingDate:'2022-01-01',
        fixedValue:'',
        fixedSubject:'153:固定资产清理',
        depreciationSubject:'152:累计折旧',
        depreciationFeeSubject:'541005:管理费用-折旧及修理费',
        originalValue:0.00,
        quantity:0.00,
        netValue:0.00,
        residualsRate:1,
        netSalvage:0.00,
        expectedYears:1,
        depreciationYears:0,
        depreciationValue:0,
        perYearDepreciationValue:0,
    },
    assetTypeindex:'0',
    operationTypendex:'0',
    addTypeindex:'0',
    useTypeindex:'0',
    depreciationTypeindex:'0',
    assetStatusindex:'0',
    isFormAssetindex:'0',
    isMinindex:'0',
    unitindex:'0',
    showBiddingDate:false,
    minDate: new Date(2008, 5, 1).getTime(),
    maxDate: new Date(2040, 0, 31).getTime(),
   // 资产类别字典
   assetTypeOptions: [],
   // 经营属性字典
   operationTypeOptions: [],
   // 增加方式字典
   addTypeOptions: [],
   // 使用情况字典
   useTypeOptions: [],
   // 折旧方式字典
   depreciationTypeOptions: [],
   // 资产状态字典
   assetStatusOptions: [],
   // 系统是否字典
   sysYesNoOptions: [],
   //单位字段
   unitOptions:[],

   status:0,
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  openBox(even){
    this.setData({
      [even.currentTarget.dataset.name]:true
    })
  },
  onChange(event){
    this.setData({
      [event.currentTarget.dataset.formname]: event.detail,
    })
  },
  closeBox(even){
    this.setData({
      [even.currentTarget.dataset.name]:false
    })
  },
  
  onConfirmBuildTime(e){
    let data = this.getNewDate(new Date(e.detail.value));
    this.setData({'form.buildTime':data});
  },

  onConfirmOperationType (e) {
    let obj =  e.detail.value;
    this.setData({
      'form.operationType':this.data.operationTypeOptions[obj].dictValue,
      'operationTypeindex':obj
    })
  },
  onConfirmAddType (e) {
    let obj =  e.detail.value;
    this.setData({
      'form.addType':this.data.addTypeOptions[obj].dictValue,
      'addTypeindex':obj
    })
  },
  onConfirmUseType (e) {
    let obj =  e.detail.value;
    this.setData({
      'form.useType':this.data.useTypeOptions[obj].dictValue,
      'useTypeindex':obj
    })
  },
  onConfirmAssetStatus (e) {
    let obj =  e.detail.value;
    this.setData({
      'form.assetStatus':this.data.assetStatusOptions[obj].dictValue,
      'assetStatusindex':obj
    })
  },
  onConfirmIsMin (e) {
    console.log(e);
    let obj =  e.detail.value;
    this.setData({
      'form.isMin':this.data.sysYesNoOptions[obj].dictValue,
      'isMinindex':obj
    })
  },
  onConfirmAssetType (e) {
    let obj =  e.detail.value;
    this.setData({
      'form.assetType':this.data.assetTypeOptions[obj].dictValue,
      'assetTypeindex':obj
    })
  },
  onConfirmIsFormAsset (e) {
    let obj =  e.detail.value;
    this.setData({
      'form.isFormAsset':this.data.sysYesNoOptions[obj].dictValue,
      'isFormAssetindex':obj
    })
  },
  onConfirmUnit (e) {
    let obj =  e.detail.value;
    this.setData({
      'form.unit':this.data.unitOptions[obj].dictValue,
      'unitindex':obj
    })
  },
  onConfirmDepreciationType (e) {
    let obj =  e.detail.value;
    this.setData({
      'form.depreciationType':this.data.depreciationTypeOptions[obj].dictValue,
      'depreciationTypeindex':obj
    })
  },
  getNewDate(date){
    //date是传过来的时间戳，注意需为13位，10位需*1000
    //也可以不传,获取的就是当前时间
    var time
    if(date){
       time = new Date(date);
    }else{
       time = new Date();
    }
    var year= time.getFullYear()  //年
    var month = ("0" + (time.getMonth() + 1)).slice(-2); //月
    var day = ("0" + time.getDate()).slice(-2); //日
    var mydate = year + "-" + month + "-" + day;
    return mydate
  },
  goSubmit:function(){
    if(this.data.form.code===''||this.data.form.code==null){ //合同编码
      UTIL.showToastNoneIcon('请填写资产编码！');
      return false;
    }else if(this.data.form.name===''||this.data.form.name==null){  //合同名称
      UTIL.showToastNoneIcon('请输入资产名称！');
      return false;
    }else if(this.data.form.assetType===''||this.data.form.assetType==null){  //甲方
      UTIL.showToastNoneIcon('资产类别不能为空！');
      return false;
    }else if(this.data.form.operationType===''||this.data.form.operationType==null){  //乙方
      UTIL.showToastNoneIcon('经营属性不能为空！');
      return false;
    }else if(this.data.form.addType === ''||this.data.form.addType==null){//收付款类型
      UTIL.showToastNoneIcon('增加方式能为空！');
      return false;
    }else if(this.data.form.buildTime === ''||this.data.form.buildTime==null){//合同来源
      UTIL.showToastNoneIcon('构建时间不能为空！');
      return false;
    }else if(this.data.form.useType === ''||this.data.form.useType==null){//合同金额
      UTIL.showToastNoneIcon('使用情况不能为空！');
      return false;
    }else if(this.data.form.assetStatus === ''||this.data.form.assetStatus==null){//签订日期
      UTIL.showToastNoneIcon('资产状态不能为空！');
      return false;
    }else if(this.data.form.quantity === ''||this.data.form.quantity==null){//开始日期
      UTIL.showToastNoneIcon('请输入数量、面积！');
      return false;
    }else if(this.data.form.unit === ''||this.data.form.unit==null){//结束日期
      UTIL.showToastNoneIcon('计量单位不能为空！');
      return false;
    }else if(this.data.form.originalValue === ''||this.data.form.originalValue==null){//单价
      UTIL.showToastNoneIcon('原值不能为空！');
      return false;
    }else if(this.data.form.depreciationType === ''||this.data.form.depreciationType==null){//已结款
      UTIL.showToastNoneIcon('折旧方式不能为空！');
      return false;
    }else if(this.data.status == '0'){
      let that = this
      this.setData({'status':'1'})
      if(this.data.form.id!=null&&this.data.form.id!=""){
        let data = this.data.form;
        data.method = "POST";
        UTIL.httpRequest(API.URL_POST_PERMANENTUPDATE,data,{
          success: (res) => {
                this.setData({'status':'0'})
                if(res.code == 200){
                  UTIL.showToastNoneIcon('修改成功');
                  setTimeout(function(){
                    wx.navigateBack({
                      delta:1
                    })
                  },2000)
                }else{
                  UTIL.showToastNoneIcon('修改失败：'+res.msg);
                }
          },
          fail: function (response) {
            if (typeof fail === FUNCTION_TEXT) {
              fail(handleFail(response));
            } else {
              showToastNoneIcon(API.MSG_FAIL_HTTP);
            }
            that.setData({'status':0})
          },
          complete: function (response) {
            wx.hideNavigationBarLoading();
          }
        })
      }else{
        let data = this.data.form;
        data.method = "POST";
        UTIL.httpRequest(API.URL_POST_PERMANENTADD,data,{
          success: (res) => {
            that.setData({'status':'0'})
           if(res.code == 200){
            UTIL.showToastNoneIcon("新增成功");
            setTimeout(function(){
              wx.navigateBack({
                delta:1
              })
            },2000)
          }else{
            UTIL.showToastNoneIcon("新增失败："+res.msg);
          }
          },
          fail: function (response) {
            if (typeof fail === FUNCTION_TEXT) {
              fail(handleFail(response));
            } else {
              showToastNoneIcon(API.MSG_FAIL_HTTP);
            }
            that.setData({'status':0})
          },
          complete: function (response) {
            wx.hideNavigationBarLoading();
          }
        })
      }
    }
  },
  bindNewInput: function (e) {
    this.setData({
      [e.currentTarget.dataset.name]: e.detail.value
    })
    if(e.currentTarget.dataset.name == 'form.originalValue' ){
      this.setData({
        'form.netSalvage' : (this.data.form.residualsRate*e.detail.value/100).toFixed(2),
        'form.perYearDepreciationValue' : ((e.detail.value-(this.data.form.residualsRate*e.detail.value/100))/this.data.form.expectedYears).toFixed(2),
        'form.netValue':this.data.form.originalValue-this.data.form.depreciationValue
      })
    }
      if(e.currentTarget.dataset.name == 'form.residualsRate' &&e.detail.value<=100){
        this.setData({
          'form.netSalvage' : (this.data.form.originalValue*e.detail.value/100)<this.data.form.originalValue?(this.data.form.originalValue*e.detail.value/100).toFixed(2):this.data.form.originalValue,
        })
        this.setData({
          'form.perYearDepreciationValue' : ((this.data.form.originalValue-this.data.form.netSalvage)/this.data.form.expectedYears).toFixed(2),
        })
      }
      if(e.currentTarget.dataset.name == 'form.residualsRate' &&e.detail.value>100){
        this.setData({
          'form.residualsRate' : 5,
        })
      }
      if(e.currentTarget.dataset.name == 'form.netSalvage' ){
        this.setData({
          'form.perYearDepreciationValue' : ((this.data.form.originalValue-e.detail.value)/this.data.form.expectedYears).toFixed(2)
        })
      }
      if(e.currentTarget.dataset.name == 'form.expectedYears' ){
        this.setData({
          'form.perYearDepreciationValue' : ((this.data.form.originalValue-this.data.form.netSalvage)/e.detail.value).toFixed(2)
        })
      }
      if(e.currentTarget.dataset.name == 'form.depreciationYears' ){
        this.setData({
          'form.depreciationValue' : (this.data.form.perYearDepreciationValue*e.detail.value)>this.data.form.originalValue?this.data.form.originalValue:(this.data.form.perYearDepreciationValue*e.detail.value).toFixed(2),
          'form.netValue' : (this.data.form.originalValue-(this.data.form.perYearDepreciationValue*e.detail.value))>=0?(this.data.form.originalValue-(this.data.form.perYearDepreciationValue*e.detail.value).toFixed(2)):0
        })
      }
    
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.id!=null&&options.id!=""){
      this.setData({id:options.id})
      //获取收入合同状态
      UTIL.httpRequest(API.URL_GET_PERMANENTDETAIL + this.data.id, {method:'GET'}, {
        success: (res) => {
          this.setData({'form':res.data});
          let that = this;
          //获取资产类别
           UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'asset_type', {method:'GET'}, {
             success: (r) => {
               if(r.data.length>0){
                 that.setData({
                    assetTypeOptions:r.data,
                 })
                 r.data.map((rr,ind) => {
                     if(rr.dictValue == res.data.assetType){
                        that.setData({'assetTypeindex':ind})
                     }
                 })
               }
             }
           })
           //获取经营属性
           UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'operation_type', {method:'GET'}, {
             success: (r) => {
               if(r.data.length>0){
                 that.setData({
                    operationTypeOptions:r.data,
                 })
                 r.data.map((rr,ind) => {
                    if(rr.dictValue == res.data.operationType){
                       that.setData({'operationTypeindex':ind})
                    }
                })
               }
             }
           })
            //获取增加方式
            UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'add_type', {method:'GET'}, {
             success: (r) => {
               if(r.data.length>0){
                 that.setData({
                    addTypeOptions:r.data,
                 })
                 r.data.map((rr,ind) => {
                    if(rr.dictValue == res.data.addType){
                       that.setData({'addTypeindex':ind})
                    }
                })
               }
             }
           })
           //获取使用情况
           UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'use_type', {method:'GET'}, {
             success: (r) => {
               if(r.data.length>0){
                 that.setData({
                    useTypeOptions:r.data,
                 })
                 r.data.map((rr,ind) => {
                    if(rr.dictValue == res.data.useType){
                       that.setData({'useTypeindex':ind})
                    }
                })
               }
             }
           })
             //获取折旧方式
             UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'depreciation_type', {method:'GET'}, {
               success: (r) => {
                 if(r.data.length>0){
                   that.setData({
                    depreciationTypeOptions:r.data,
                   })
                   r.data.map((rr,ind) => {
                    if(rr.dictValue == res.data.depreciationType){
                       that.setData({'depreciationTypeindex':ind})
                    }
                })
                 }
               }
             })
              //获取资产状态
              UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'asset_status', {method:'GET'}, {
               success: (r) => {
                 if(r.data.length>0){
                   that.setData({
                    assetStatusOptions:r.data,
                   })
                   r.data.map((rr,ind) => {
                    if(rr.dictValue == res.data.assetStatus){
                       that.setData({'assetStatusindex':ind})
                    }
                })
                 }
               }
             })
              //获取单位
              UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'fixed_assets_unit', {method:'GET'}, {
               success: (r) => {
                 if(r.data.length>0){
                   that.setData({
                    unitOptions:r.data,
                   })
                   r.data.map((rr,ind) => {
                    if(rr.dictValue == res.data.unit){
                       that.setData({'unitindex':ind})
                    }
                })
                 }
               }
             })
             //获取系统是否
             UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'sys_yes_no', {method:'GET'}, {
                success: (r) => {
                  if(r.data.length>0){
                    that.setData({
                        sysYesNoOptions:r.data,
                    })
                    r.data.map((rr,ind) => {
                     if(rr.dictValue == res.data.isMin){
                        that.setData({'isMinindex':ind})
                     }
                     if(rr.dictValue == res.data.isFormAsset){
                        that.setData({'isFormAssetindex':ind})
                     }
                 })
                  }
                }
              })
        }
      })
    }else{
      let that = this;
        this.setData({
          'form.reviewTime':this.getNewDate(),
          'form.buildTime':this.getNewDate(),
          'form.startTime':this.getNewDate(),
          'form.endTime':this.getNewDate(),
          'form.biddingDate':this.getNewDate(),
        })
      //获取资产类别
       UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'asset_type', {method:'GET'}, {
         success: (res) => {
           if(res.data.length>0){
             that.setData({
               assetTypeOptions:res.data,
               'form.assetType':res.data[0].dictValue
             })
           }
         }
       })
       //获取经营属性
       UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'operation_type', {method:'GET'}, {
         success: (res) => {
           if(res.data.length>0){
             that.setData({
                operationTypeOptions:res.data,
               'form.operationType':res.data[0].dictValue
             })
           }
         }
       })
        //获取增加方式
        UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'add_type', {method:'GET'}, {
         success: (res) => {
           if(res.data.length>0){
             that.setData({
                addTypeOptions:res.data,
               'form.addType':res.data[0].dictValue
             })
           }
         }
       })
       //获取使用情况
       UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'use_type', {method:'GET'}, {
         success: (res) => {
           if(res.data.length>0){
             that.setData({
                useTypeOptions:res.data,
               'form.useType':res.data[0].dictValue
             })
           }
         }
       })
         //获取折旧方式
         UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'depreciation_type', {method:'GET'}, {
           success: (res) => {
             if(res.data.length>0){
               that.setData({
                depreciationTypeOptions:res.data,
                 'form.depreciationType':res.data[1].dictValue
               })
             }
           }
         })
          //获取资产状态
          UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'asset_status', {method:'GET'}, {
           success: (res) => {
             if(res.data.length>0){
               that.setData({
                assetStatusOptions:res.data,
                 'form.assetStatus':res.data[0].dictValue
               })
             }
           }
         })
          //获取单位
          UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'fixed_assets_unit', {method:'GET'}, {
           success: (res) => {
             if(res.data.length>0){
               that.setData({
                unitOptions:res.data,
                 'form.unit':res.data[0].dictValue
               })
             }
           }
         })
          //获取是否
          UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'sys_yes_no', {method:'GET'}, {
            success: (res) => {
              if(res.data.length>0){
                that.setData({
                    sysYesNoOptions:res.data,
                  'form.isMin':res.data[0].dictValue,
                  'form.isFormAsset':res.data[0].dictValue
                })
              }
            }
          })
    }
   
  },

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

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})