// pages/regular/index.js
import * as UTIL from '../../utils/util.js';
import * as API from '../../utils/API.js';
let EVN_CONFIG = require('../../env/env');

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    option1: [
      { text: '收支类型', value: '' },
      { text: '待支付', value: '1' },
      { text: '银行受理', value: '3' },
      { text: '支付失败', value: '4' },
      { text: '部分失败', value: '5' },
    ],
    option2: [
      { text: '结算方式', value: '' },
      { text: '结算类', value: '1' },
      { text: '工程项目类', value: '2' },
      { text: '合同类', value: '4' },
      { text: '其他', value: '5' },
    ],
    option3: [
      { text: '票据状态', value: '' },
      { text: '银行卡转账', value: '1' },
      { text: '信用卡还款', value: '2' },
    ],
    value1: '',
    value2: '',
    value3: '',
    showPopup:false,
    result1:'',
    result2:'',
    result3:'',
    uploadOptions:[],
    showReceiptDialog:false,
    beforeClose(action) {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (action === 'confirm') {
            // 拦截确认操作
             resolve(false);
          } else {
            resolve(true);
          }
        }, 0);
      });
    },
    billList:[],
    billDate:'',
    showPopup2:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },
  getDict(){
    var that = this;
    //获取附件字典
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'common_attach', {method:'GET'}, {
      success: (res) => {
        if(res.data.length>0){
          this.setData({
            uploadOptions:res.data,
          })
        }
      }
    })
    // 收支类型字典查询
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'income_expenses_type', {method:'GET'}, {
      success: (res) => {
        let option1 = [{
          text: '收支类型', value: ''
        }];
        res.data.map(rr=>{
          option1.push({
            text: rr.dictLabel, value: rr.dictValue
          })
        })
        that.setData({
          option1:option1,
          expensesTypeOptions:res.data,
        })
      }
    })
    // 结算方式字典查询
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'settle_style', {method:'GET'}, {
      success: (res) => {
        let option2 = [{
          text: '结算方式', value: ''
        }];
        res.data.map(rr=>{
          option2.push({
            text: rr.dictLabel, value: rr.dictValue
          })
        })
        that.setData({
          option2:option2,
          settleTypeOptions:res.data,
        })
      }
    })
    // 票据状态字典查询
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'bill_type', {method:'GET'}, {
      success: (res) => {
        let option3 = [{
          text: '票据状态', value: ''
        }];
        res.data.map(rr=>{
          if (rr.dictValue == 4 ||rr.dictValue == 5 ||rr.dictValue == 6 ||rr.dictValue == 7) {
            option3.push({
              text: rr.dictLabel, value: rr.dictValue
            })
          }
        })
        that.setData({
          option3:option3,
          billTypeOptions:res.data,
        })
      }
    })
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  showPopup(){
    var that = this;
    that.setData({
      showPopup:true
    })
  },
  onClose() {
    this.setData({ showPopup: false });
  },
  onChange(event) {
    console.log(event.detail);
    this.setData({
      result: event.detail,
    });
  },
  showReceiptDialog(){
    var that = this;
    that.setData({
      showReceiptDialog:true
    })
  },
  onChangeSZ(event) {
    console.log(event.detail);
    this.setData({
      result1: event.detail,
    });
  },
  onChangeJS(event) {
    console.log(event.detail);
    this.setData({
      result2: event.detail,
    });
  },
  onChangePJ(event) {
    console.log(event.detail);
    this.setData({
      result3: event.detail,
    });
  },
  bindDateBeginChange: function(e) {
    this.setData({
      billDate: e.detail.value
    })
  },
  goSubmit(){
    var that = this ;
    let form = {
      pageNum:'1',
      pageSize:'999',
      billNum:'',//票据编号
      billType:that.data.result3,//票据状态
      billDate:that.data.billDate,//开盘日期
      accountSummary:that.data.result2,//结算事项
      incomeExpensesType:that.data.result1,//收支类型
      orderByColumn:'billDate',
      isAsc:'desc',
      settleStyle:'1',
      method:'GET',
    }
    console.log(form);
    UTIL.httpRequest(API.URL_GET_GETBILLLISTDETAIL , form, {
      success: (res) => {
        res.rows.map(rrr=>{
          rrr.billTypeText = UTIL.getTransform(rrr.billType,that.data.billTypeOptions);
          rrr.incomeExpensesTypeText = UTIL.getTransform(rrr.incomeExpensesType,that.data.expensesTypeOptions);
          rrr.daiAmount = rrr.daiAmount == null ? '0.00':parseFloat(rrr.daiAmount).toFixed(2)
          rrr.jieAmount = rrr.jieAmount == null ? '0.00':parseFloat(rrr.jieAmount).toFixed(2)
        })
        that.setData({
          value1:that.data.result1,
          value2:that.data.result2,
          value3:that.data.result3,
          billList:res.rows,
          showPopup:false
        })
      }
    })
  },
  reset(){
    this.setData({
      value1:'',
      value2:'',
      value3:'',
      result1:'',
      result2:'',
      result3:'',
    })
    this.onShow();
  },

  changeTab1(event){
    this.setData({
      result1: event.detail,
      value1: event.detail
    });
    var that = this ;
    let form = {
      pageNum:'1',
      pageSize:'999',
      billNum:'',//票据编号
      billType:that.data.result3,//票据状态
      billDate:that.data.billDate,//开盘日期
      accountSummary:that.data.result2,//结算事项
      incomeExpensesType:that.data.result1,//收支类型
      orderByColumn:'billDate',
      isAsc:'desc',
      settleStyle:'1',
      method:'GET',
    }
    console.log(form);
    UTIL.httpRequest(API.URL_GET_GETBILLLISTDETAIL , form, {
      success: (res) => {
        res.rows.map(rrr=>{
          rrr.billTypeText = UTIL.getTransform(rrr.billType,that.data.billTypeOptions);
          rrr.incomeExpensesTypeText = UTIL.getTransform(rrr.incomeExpensesType,that.data.expensesTypeOptions);
          rrr.daiAmount = rrr.daiAmount == null ? '0.00':parseFloat(rrr.daiAmount).toFixed(2)
          rrr.jieAmount = rrr.jieAmount == null ? '0.00':parseFloat(rrr.jieAmount).toFixed(2)
        })
        that.setData({
          billList:res.rows,
          showPopup:false
        })
      }
    })
  },
  changeTab2(event){
    this.setData({
      result2: event.detail,
      value2: event.detail
    });
    var that = this ;
    let form = {
      pageNum:'1',
      pageSize:'999',
      billNum:'',//票据编号
      billType:that.data.result3,//票据状态
      billDate:that.data.billDate,//开盘日期
      accountSummary:that.data.result2,//结算事项
      incomeExpensesType:that.data.result1,//收支类型
      orderByColumn:'billDate',
      isAsc:'desc',
      settleStyle:'1',
      method:'GET',
    }
    console.log(form);
    UTIL.httpRequest(API.URL_GET_GETBILLLISTDETAIL , form, {
      success: (res) => {
        res.rows.map(rrr=>{
          rrr.billTypeText = UTIL.getTransform(rrr.billType,that.data.billTypeOptions);
          rrr.incomeExpensesTypeText = UTIL.getTransform(rrr.incomeExpensesType,that.data.expensesTypeOptions);
          rrr.daiAmount = rrr.daiAmount == null ? '0.00':parseFloat(rrr.daiAmount).toFixed(2)
          rrr.jieAmount = rrr.jieAmount == null ? '0.00':parseFloat(rrr.jieAmount).toFixed(2)
        })
        that.setData({
          billList:res.rows,
          showPopup:false
        })
      }
    })
  },
  changeTab3(event){
    this.setData({
      result3: event.detail,
      value3: event.detail
    });
    var that = this ;
    let form = {
      pageNum:'1',
      pageSize:'999',
      billNum:'',//票据编号
      billType:that.data.result3,//票据状态
      billDate:that.data.billDate,//开盘日期
      accountSummary:that.data.result2,//结算事项
      incomeExpensesType:that.data.result1,//收支类型
      orderByColumn:'billDate',
      isAsc:'desc',
      settleStyle:'1',
      method:'GET',
    }
    console.log(form);
    UTIL.httpRequest(API.URL_GET_GETBILLLISTDETAIL , form, {
      success: (res) => {
        res.rows.map(rrr=>{
          rrr.billTypeText = UTIL.getTransform(rrr.billType,that.data.billTypeOptions);
          rrr.incomeExpensesTypeText = UTIL.getTransform(rrr.incomeExpensesType,that.data.expensesTypeOptions);
          rrr.daiAmount = rrr.daiAmount == null ? '0.00':parseFloat(rrr.daiAmount).toFixed(2)
          rrr.jieAmount = rrr.jieAmount == null ? '0.00':parseFloat(rrr.jieAmount).toFixed(2)
        })
        that.setData({
          billList:res.rows,
          showPopup:false
        })
      }
    })
  },
  goHX(e){
    var that = this ;
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定核销？',
      success (res) {
        if (res.confirm) {
          UTIL.httpRequest(API.URL_GET_GETDETAILOFF+id , {method:'GET'}, {
            success: (res) => {
              if (res.code == API.SUCCESS_CODE) {
                wx.showToast({
                  title: '核销成功',
                  icon: 'success',
                  duration: 2000,
                })
                that.onShow();
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },
  goZF(e){
    var that = this ;
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定作废？',
      success (res) {
        if (res.confirm) {
          UTIL.httpRequest(API.URL_GET_GETDETAILCANCEL+id , {method:'GET'}, {
            success: (res) => {
              if (res.code == API.SUCCESS_CODE) {
                wx.showToast({
                  title: '作废成功',
                  icon: 'success',
                  duration: 2000,
                })
                that.onShow();
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },
  goYS(e){
    var that = this ;
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定遗失？',
      success (res) {
        if (res.confirm) {
          UTIL.httpRequest(API.URL_GET_GETDETAILLOSE+id , {method:'GET'}, {
            success: (res) => {
              if (res.code == API.SUCCESS_CODE) {
                wx.showToast({
                  title: '操作成功',
                  icon: 'success',
                  duration: 2000,
                })
                that.onShow();
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },
  goSC(e){
    var that = this ;
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定删除？',
      success (res) {
        if (res.confirm) {
          UTIL.httpRequest(API.URL_GET_GETDETAILREMOVE+id , {method:'GET'}, {
            success: (res) => {
              if (res.code == API.SUCCESS_CODE) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                })
                that.onShow();
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  goSCLS(e){
    var that = this ;
    var id = e.currentTarget.dataset.id;
    var options = JSON.stringify(e.currentTarget.dataset.options);
    wx.navigateTo({
      url: 'flowAdd/flowAdd?options='+options,
    })
    return;
    var form = {
      accountDate:'',//日期
      accountId:'',//账户id
      accountName:'',//账户名称
      accountSummary:'',//摘要
      accountType:'',//账户类型101=现金,102=银行存款
      billNum:'',//单据编号
      checkedStatus:'',//审核状态：1未提交、2待审核、3已审核、4已挂起
      contractionId:'',//关联合同选择发包收入的时候必填
      incomeType:'',//收入类型 1经营收入、2发包收入（这个关联合同）、3补助收入、4其他收入、5投资收益 
      incomeDate:'',//收入时间
      incomeExpensesType:'',//收支类别1收入2支出
      isBill:'',//是否来源票据0：否  1：是
      jieAmount:'',//收入金额
      subjectId:'',//对方科目编码
      subjectNameAll:'',//对方科目名称
    }

    UTIL.httpRequest(API.URL_GET_GETFLOWADD, {method:'GET'}, {
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          wx.showToast({
            title: '核销成功',
            icon: 'success',
            duration: 2000,
          })
          that.onLoad();
        }
      }
    })
  },
  goAdd(){
    wx.navigateTo({
      url: 'add/add',
    })
  },
  goEdit(e){
    var options = JSON.stringify(e.currentTarget.dataset.options);
    wx.navigateTo({
      url: 'edit/edit?detail='+options,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;

    that.getDict();

    var form = {
      pageNum:'1',
      pageSize:'999',
      billNum:'',//票据编号
      billType:'',//票据状态
      billDate:'',//开盘日期
      accountSummary:'',//结算事项
      incomeExpensesType:'',//收支类型
      orderByColumn:'billDate',
      isAsc:'desc',
      settleStyle:'1'
    }
    console.log(form);
    UTIL.httpRequest(API.URL_GET_GETBILLLISTDETAIL , form, {
      success: (res) => {
        res.rows.map(rrr=>{
          rrr.billTypeText = UTIL.getTransform(rrr.billType,that.data.billTypeOptions);
          rrr.incomeExpensesTypeText = UTIL.getTransform(rrr.incomeExpensesType,that.data.expensesTypeOptions);
          rrr.daiAmount = rrr.daiAmount == null ? '0.00':parseFloat(rrr.daiAmount).toFixed(2)
          rrr.jieAmount = rrr.jieAmount == null ? '0.00':parseFloat(rrr.jieAmount).toFixed(2)
        })
        that.setData({
          billList:res.rows
        })
      }
    })

    // let query = wx.createSelectorQuery().in(this);
    // query.selectAll('.cell_right').boundingClientRect(function(rect){

    //   console.log(rect)
      
    // }).exec();

    

    // console.log(query.selectAll('.cell_right'));
    
  },

  goSearch(e){
    console.log(e);
    var that = this;
    let form = {
      pageNum:'1',
      pageSize:'999',
      billNum:e.detail,//票据编号
      billType:that.data.result3,//票据状态
      billDate:that.data.billDate,//开盘日期
      accountSummary:that.data.result2,//结算事项
      incomeExpensesType:that.data.result1,//收支类型
      orderByColumn:'billDate',
      isAsc:'desc',
      settleStyle:'1',
      method:'GET',
    }
    UTIL.httpRequest(API.URL_GET_GETBILLLISTDETAIL , form, {
      success: (res) => {
        res.rows.map(rrr=>{
          rrr.billTypeText = UTIL.getTransform(rrr.billType,that.data.billTypeOptions);
          rrr.incomeExpensesTypeText = UTIL.getTransform(rrr.incomeExpensesType,that.data.expensesTypeOptions);
          rrr.daiAmount = rrr.daiAmount == null ? '0.00':parseFloat(rrr.daiAmount).toFixed(2)
          rrr.jieAmount = rrr.jieAmount == null ? '0.00':parseFloat(rrr.jieAmount).toFixed(2)
        })
        that.setData({
          billList:res.rows
        })
      }
    })
  },
  upload(e){
    this.setData({itemId:e.currentTarget.dataset.id});
    this.asyncFun(e.currentTarget.dataset.id)
    this.setData({"fileList":[]})
  },
  asyncFun(id){
    let uploadList = this.data.uploadOptions
    let newList = []
    let _this = this
    uploadList.map( res => {
      let oData = {
        tableId: id,
        tableName: "t_contraction_info", //上传表
        bizPath: "contraction",
        fileType: res.dictValue, //附件类型  1原始发票 2会议纪要 3会议照片 4 参会人员签字
        method:'GET'
      }
      UTIL.httpRequest(API.URL_GET_ATTACHMENTLIST, oData, {
        success: (rr) => {
          if(rr.code==200&&rr.rows.length>0){
            rr.rows.map((rrr,index) => {
              rrr.url = wx.getStorageSync('dressCode') + rrr.fileUrl
              if(index==rr.rows.length-1){
                newList.push(Object.assign({},res,{"list":rr.rows}))
                _this.setData({"fileList":_this.data.fileList.concat(newList)});
                _this.setData({"showUpload":true})
              }
            })
          }else{
            let newuploadList = uploadList
            newuploadList.map(rd => {
              rd.list = newList
            })
            _this.setData({"fileList":newuploadList});
            _this.setData({"showUpload":true})
          }
        }
      })
    })

  },
  afterRead(event) {
    let _this = this
    wx.showLoading({
      title: '上传中...'
    })
    let fileForm={
      file: event.detail,
      fileType:event.currentTarget.dataset.idx,
      tableName: "t_contraction_info", //上传表
      bizPath: "contraction", //上传目录
      tableId:_this.data.itemId
    }
    this.uploadFile(fileForm,event)
  },
  uploadFile(uploadFile,event) {
    let _this = this
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: wx.getStorageSync('dressCode')+API.URL_GET_UPLOAD,
        filePath: uploadFile.file.file.url,
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data",//记得设置
          "chartset":"utf-8",
          'Authorization':'Bearer '+getApp().globalData.userInfo.token
        },
        formData:uploadFile,
        success: (res) => {
          res.data = JSON.parse(res.data);
          if(res.statusCode == 200){
            let files = _this.data.fileList
            let fName = res.data.fileUrl.split('/')
            let fLength = fName.length
            files[event.currentTarget.dataset.idx].list.push({
              "fileName": fName[fLength-1],
              "fileType": "0",
              "fileUrl":res.data.fileUrl ,
              "id": res.data.id,
              "tableId": 6,
              "url":wx.getStorageSync('dressCode')+res.data.fileUrl
            })
            _this.setData({"fileList":files})
            wx.hideLoading()
          }
        },
        fail: (err) => {
          //上传失败：修改pedding为reject
          reject(err)
        }
      });
    })
  },
  deleteImg(event){
    this.setData({"fileEvent":event})
    this.setData({"showPopup2":true});
  },
  closeBox(){
    this.setData({"showUpload":false})
    this.setData({"showRelevance":false})
  },
  cancelTem:function(e){
    this.setData({"fileEvent":"{}"});
    this.setData({"showPopup":false});
  },
  confirmTem:function(e){
    let event = this.data.fileEvent
    UTIL.httpRequest(API.URL_GET_GETFILEREMOVE+event.detail.file.id , {method:'GET'}, {
      success: (res) => {
        if(res.code==200){
          let ll = this.data.fileList
          var jsonlist = ll[event.target.dataset.idx].list;
          jsonlist.splice(event.detail.index, 1)
          ll[event.target.dataset.idx].list = jsonlist
          this.setData({"fileList":ll})
          this.setData({showPopup2:false});
          wx.showToast({
            title: '删除成功！',
            icon: 'success',
            duration: 2000,
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

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

  },

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

  },

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

  },

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

  }
})