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

  /**
   * 页面的初始数据
   */
  data: {
    popupVisible:false,
    subjects:[],
    isIPX: app.globalData.isIPX,
    subjectName:'',
    visible:false,
    subjectId:'',
    radio:'1',
    applicationList:[],
    applicationListSecond:[],
    assetStatusOptions:[],
    auditStatus:[],
    loading: false,
    finished: false,
    show: false,
    showTab: false,
    showPickerTime: false,
    fileList:[],
    listLength:'0',
    searchInput:'',
    queryParams:{
      pageNum:1,
      pageSize:999,
      startDate:'',
      startSubjectId:'',
      endSubjectId:'',
      showSubSubject:false
    },
    uploadFiles1:[],
    projectId:'',
    projectIndex:'',
    showBtn:true,
    yearMonth:[],
    deptName:'',
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    currentDate: new Date(),
    date:''
  },
  
  changeTabItem(e){
    console.log(e.detail.currentTarget.dataset.item);
    console.log(e);
    
    this.setData({
      subjectName:e.detail.currentTarget.dataset.item.subjectId+ " " + e.detail.currentTarget.dataset.item.subjectName,
      ['queryParams.endSubjectId']:e.detail.currentTarget.dataset.item.subjectId,
      popupVisible:false
    })
    this.getList();

  },
  showSub(event){
    this.setData({
      ['queryParams.showSubSubject']:event.detail
    })
    this.getList();
  },
  onClose(e){
    console.log(e);
    this.setData({
      popupVisible:false
    })
  },
  openTabs(e){
    console.log(e);
    this.setData({
      tabsVisible:true
    })
    this.selectComponent('#tabs').resize();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    UTIL.httpRequest(API.getLoginBook,{}, {
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          if (res.data.currentDay != null || res.data.startDay != null){
            let resDate = res.data.currentDay != null ? res.data.currentDay : res.data.startDay != null ? res.data.startDay : UTIL.formatDates(new Date())
            let date = resDate.split('-');
            let mindate = res.data.startDay.split('-')
            this.setData({
              date:date[0] + '年' + date[1] + '月',
              currentDate:new Date(date[0], date[1]-1, 1).getTime(),
              ['queryParams.startDate']:resDate,
              minDate: new Date(mindate[0],mindate[1]-1).getTime(),
            })
            this.getList();
            this.getSubjects();
          }
        }
      }
    })
  },
  getList(){
    var _this = this;
    setTimeout(() => {
      UTIL.httpRequest(API.trailBalanceList,_this.data.queryParams, {
        success: (response) => {
          // _this.data.listLength = response.total;
          response.rows.map(res=>{
            res.bqjffs = Number(res.bqjffs).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
              return $1 + ","; }).replace(/\.$/, "");
            res.bqdffs = Number(res.bqdffs).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
              return $1 + ","; }).replace(/\.$/, "");
            res.qcjfye = Number(res.qcjfye).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
              return $1 + ","; }).replace(/\.$/, "");
            res.qcdfye = Number(res.qcdfye).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
              return $1 + ","; }).replace(/\.$/, "");
            res.qmjffs = Number(res.qmjffs).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
              return $1 + ","; }).replace(/\.$/, "");
            res.qmdffs = Number(res.qmdffs).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
              return $1 + ","; }).replace(/\.$/, "");
          })
          // _this.data.applicationList = response.rows;
          _this.setData({
            listLength:response.total,
            applicationList:response.rows,
          })
        }
      });
    }, 1000);
  },
  openPick(){
    this.setData({
      showPickerTime:true
    })
  },
  closePick(){
    this.setData({
      showPickerTime:false
    })
  },
  onConfirm(time) {
    console.log(time.detail);
    let date = UTIL.formatDates(time.detail).split('-');
    this.setData({
      date:date[0] + '年' + date[1] + '月',
      ['queryParams.startDate']:UTIL.formatDates(time.detail),
      showPickerTime : false
    })
    this.getList();
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  getSubjects() {
    this.data.subjects = [];
    var that  = this;
    let map = {};
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'subject_type', {method:'GET'}, {
      success: (resp) => {
        this.setData({
          subjects:resp.data.map((x) => {
            let item = {
              subjectId: x.dictValue,
              subjectName: x.dictLabel,
              subjectNameAll: x.dictLabel,
              subjectType: x.dictValue,
              subjectLevel: 0,
              children: [],
              visible: true,
            };
            map[x.dictValue] = item;
            return item;
          })
        });
        console.log(this.data.subjects);
        UTIL.httpRequest('/finance/subject/listAll',{year:this.data.queryParams.startDate ? this.data.queryParams.startDate.substr(0, 4) : null}, {
          success: (resp) => {
            let list = this.makeTree(resp.rows || resp.data);
            console.log(list);
            for(let v of list)
            {
              if(v.subjectId.length === 3)
              {
                map[v.subjectType].children.push(v);
              }
            }
            this.setData({
              subjects:this.data.subjects
            })
            
          }
        });
      }
    })
    // this.getDicts('subject_type').then((resp) => {
      
    //   let url = '/finance/subject/listAll?year='+this.yearNews; // '/open/villageAffairs/public/subjects/153'
    //   request(url).then((resp) => {
        
    //   })
    // });
  },
  makeTree(list) {
    function isnull(p) {
      return p === null || p === undefined || p === '';
    }
    function makeTree_r(l, p) {
      const isRoot = isnull(p);
      let res = [];
      for(let v of l)
      {
        if((isRoot && isnull(v.parentId)) || (!isRoot && v.parentId == p))
        {
          let arr = makeTree_r(l, v.subjectId);
          if(arr.length > 0)
            v.children = arr;
          else
            delete v.children;
          res.push(v);
        }
      }
      return res;
    }
    return makeTree_r(list.map((x) => {
      x.visible = true;
      return x;
    }));
  },
  openPup(){
    this.setData({
      popupVisible:true
    })
  },
  onTabChanged(){
    this.setData({searchValue:''})
    this.onSearch();
  },
  onSearch(value) {
    function handleTree_r(l, func) {
      let res = 0;
      for(let v of l)
      {
        let r = func(v) ? 1 : 0;
        if(v.children && Array.isArray(v.children) && v.children.length > 0)
        {
          r += handleTree_r(v.children, func);
        }
        v.visible = r > 0;
        res += r;
      }
      return res;
    }

    for(let v of this.data.subjects)
    {
      if(v.subjectId === this.data.active && value)
      {
        handleTree_r(v.children, (x) => x.subjectId.startsWith(value) || x.subjectName.indexOf(value) !== -1);
      }
      else
      {
        handleTree_r(v.children, (x) => true);
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})