// pages/ticketQuery/ticketQuery.js
const utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: '',
    finish: false,
    customerName: '', //客户名称
    invoiceDateBegin: '', //开票日期范围查询-开始时间yyyy-MM-dd HH:mm:ss
    invoiceDateEnd: '', //开票日期范围查询-结束时间yyyy-MM-dd HH:mm:ss
    hongchongFlag: '', //红冲状态
    status: '', //开票状态
    statusList: ['开票中', '正数开具成功', '负数开具成功', '正数已作废', '负数已作废', '空白作废'],
    statusIndex: '',
    tabIndex: 0,
    monthDate: '',
    userInfo: '',
    company: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUser()
    this.getMonthDate()
    this.getList()
  },
  //获取企业信息(当前登录用户的默认企业信息)
  getUser() {
    this.setData({
      userInfo: utils.getInfo(),
      company: utils.getCurrEntInfo()
    })
  },
  //列表
  getList(type) {
    let params = {
      mobile: utils.getInfo().mobile,
      belongEntTaxId: this.data.company.entTaxId,
      reqChannel: 5,
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize
    }
    let customerName = utils.trimAll(this.data.customerName)
    if (customerName !== '') {
      params.customerName = customerName
    }
    if (this.data.invoiceDateBegin !== '') {
      params.invoiceDateBegin = this.data.invoiceDateBegin + ' 00:00:00'
    }
    if (this.data.invoiceDateEnd !== '') {
      params.invoiceDateEnd = this.data.invoiceDateEnd + ' 23:59:59'
    }
    if (this.data.status !== '') {
      params.status = this.data.status
    }
    if (this.data.hongchongFlag !== '') {
      params.hongchongFlag = this.data.hongchongFlag
    }
    utils.axios({
      method: 'get',
      url: '/sys/invoice/findPage',
      data: params,
      sendBefore() {
        wx.showLoading({
          title: '加载中...'
        })
      },
      complete() {
        wx.hideLoading()
        wx.stopPullDownRefresh()
      },
      success: res => {
        let result = res.data
        if (type === 'toFresh') {
          result.records.forEach((item) => {
            let beginDate = this.data.monthDate.start_day + ' 00:00:00'
            let endDate = this.data.monthDate.end_day + ' 23:59:59'
            if (item.createTime >= beginDate && item.createTime <= endDate) {
              item.isInvalid = true
            } else {
              item.isInvalid = false
            }
          });
          this.setData({
            list: result.records,
            pages: result.pages
          })
        } else {
          let list = this.data.list
          result.records.forEach((item) => {
            let beginDate = this.data.monthDate.start_day + ' 00:00:00'
            let endDate = this.data.monthDate.end_day + ' 23:59:59'
            if (item.createTime >= beginDate && item.createTime <= endDate) {
              item.isInvalid = true
            } else {
              item.isInvalid = false
            }
          });
          list = list.concat(result.records)
          console.log(list);
          this.setData({
            list,
            pages: result.pages
          })
        }
        if (result.total <= this.data.pageSize) {
          this.setData({
            finish: true
          })
        }
      }
    })
  },
  toFresh() {
    this.setData({
      pageNum: 1,
      pages: '',
      finish: false
    })
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    this.getList('toFresh')
  },

  //刷新
  refresh(e) {
    let index = e.currentTarget.dataset.index
    let invoiceReqFlowNo = e.currentTarget.dataset.invoiceno
    let params = {
      invoiceReqFlowNo,
      mobile: utils.getInfo().mobile,
      reqChannel: 5
    }
    utils.axios({
      method: 'post',
      url: '/sys/invoiceInfo/refreshResult',
      data: params,
      sendBefore() {
        wx.showLoading({
          title: '刷新中...',
          mask: true
        })
      },
      complete() {
        wx.hideLoading()
      },
      success: res => {
        utils.toast('已刷新')
        let result = res.data
        let str = `list[${index}].status`
        this.setData({
          [str]: result.status
        })
      }
    })
  },

  // 获取本月开始结束日期
  getMonthDate() {
    var monthDate = {};
    var now = new Date(); //当前日期
    var nowMonth = now.getMonth(); //当前月
    var nowYear = now.getFullYear(); //当前年
    //本月的开始时间
    var monthStartDate = new Date(nowYear, nowMonth, 1);
    var yy = monthStartDate.getFullYear() + "-";
    var mm =
      (monthStartDate.getMonth() + 1 < 10
        ? "0" + (monthStartDate.getMonth() + 1)
        : monthStartDate.getMonth() + 1) + "-";
    var dd =
      monthStartDate.getDate() < 10
        ? "0" + monthStartDate.getDate()
        : monthStartDate.getDate();
    //本月的结束时间
    var monthEndDate = new Date(nowYear, nowMonth + 1, 0);
    var YY = monthEndDate.getFullYear() + "-";
    var MM =
      (monthEndDate.getMonth() + 1 < 10
        ? "0" + (monthEndDate.getMonth() + 1)
        : monthEndDate.getMonth() + 1) + "-";
    var DD =
      monthEndDate.getDate() < 10
        ? "0" + monthEndDate.getDate()
        : monthEndDate.getDate();
    monthDate.start_day = yy + mm + dd;
    monthDate.end_day = YY + MM + DD;
    this.setData({
      monthDate: monthDate
    })
  },
  // 发票作废
  invoiceInvalid(e) {
    let invoiceInfo = e.currentTarget.dataset.invoiceno
    let params = {
      entTaxId: this.data.company.entTaxId,
      deviceType: this.data.company.defaultDeviceInfo.deviceType,
      taxDiscId: this.data.company.defaultDeviceInfo.taxDiscId,
      invoiceInvalidType: invoiceInfo.invoiceType,
      invoiceCategory: invoiceInfo.invoiceCategory,
      invoiceCode: invoiceInfo.invoiceCode,
      invoiceNumber: invoiceInfo.invoiceNumber,
      invalidOper: this.data.userInfo.userName,
      mobile: this.data.userInfo.mobile,
      reqChannel: 5
    }
    utils.axios({
      method: 'post',
      url: '/sys/invoiceExt/invalid',
      data: params,
      sendBefore() {
        wx.showLoading({
          title: '加载中...'
        })
      },
      complete() {
        wx.hideLoading()
        wx.stopPullDownRefresh()
      },
      success: res => {
        if (res.code === 0) {
          utils.toast(res.msg)
          this.toFresh()
        }
      }
    })
  },
  // 发票红冲
  invoiceHongChong(e) {
    let invoiceInfo = e.currentTarget.dataset.invoiceno
    let params = {
      oriInvoiceReqFlowNo: invoiceInfo.invoiceReqFlowNo,
      mobile: this.data.userInfo.mobile,
      reqChannel: 5
    }
    utils.axios({
      method: 'post',
      url: '/sys/invoice/quickyHongchong',
      data: params,
      sendBefore() {
        wx.showLoading({
          title: '加载中...'
        })
      },
      complete() {
        wx.hideLoading()
        wx.stopPullDownRefresh()
      },
      success: res => {
        if (res.code === 0) {
          utils.toast(res.msg)
          this.toFresh()
        }
      }
    })
  },
  //点击重开
  showRetry(e) {
    wx.showModal({
      content: '确定重开该发票吗？',
      confirmColor: '#007dff',
      success: res => {
        if (res.confirm) {
          this.retry(e)
        }
      }
    })
  },
  retry(e) {
    let index = e.currentTarget.dataset.index
    let invoiceReqFlowNo = e.currentTarget.dataset.invoiceno
    let params = {
      invoiceReqFlowNo,
      mobile: utils.getInfo().mobile,
      reqChannel: 5
    }
    utils.axios({
      method: 'post',
      url: '/sys/invoiceInfo/retry',
      data: params,
      sendBefore() {
        wx.showLoading({
          title: '推送中...',
          mask: true
        })
      },
      complete() {
        wx.hideLoading()
      },
      success: res => {
        utils.toast('已推送')
        let result = res.data
        let str = `list[${index}].status`
        this.setData({
          [str]: result.status
        })
      }
    })
  },

  //开票详情
  toDetail(e) {
    let index = e.currentTarget.dataset.index
    let list = this.data.list
    let item = list[index]
    wx.setStorageSync('ticketDetail', item)
    wx.navigateTo({
      url: '/pages/ticketDetail/ticketDetail'
    })
  },

  //搜素
  search(e) {
    let customerName = e.detail.value
    this.setData({
      customerName
    })
    this.toFresh()
  },

  //全部状态
  setStatus(e) {
    let statusIndex = Number(e.detail.value)
    let status = ''
    if (statusIndex === 0) {
      status = 1
    }
    if (statusIndex === 1) {
      status = 3
    }
    if (statusIndex === 2) {
      status = 4
    }
    if (statusIndex === 3) {
      status = 5
    }
    if (statusIndex === 4) {
      status = 6
    }
    if (statusIndex === 5) {
      status = 7
    }
    this.setData({
      statusIndex,
      status
    })
    this.toFresh()
  },
  clearStatus() {
    this.setData({
      statusIndex: '',
      status: ''
    })
    this.toFresh()
  },

  //设置开始结束时间
  setStart(e) {
    let invoiceDateBegin = e.detail.value
    this.setData({
      invoiceDateBegin
    })
    this.toFresh()
  },
  setEnd(e) {
    let invoiceDateEnd = e.detail.value
    this.setData({
      invoiceDateEnd
    })
    this.toFresh()
  },
  clearStart() {
    this.setData({
      invoiceDateBegin: ''
    })
    this.toFresh()
  },
  clearEnd() {
    this.setData({
      invoiceDateEnd: ''
    })
    this.toFresh()
  },

  //切换
  switchTab(e) {
    let index = e.currentTarget.dataset.index
    let status = ''
    let hongchongFlag = ''
    if (index === 1) {
      status = 2
    }
    if (index === 2) {
      status = 3
    }
    if (index === 3) {
      status = ''
      hongchongFlag = 5
    }
    this.setData({
      status,
      hongchongFlag,
      tabIndex: index
    })
    this.toFresh()
  },

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

  },

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

  },

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

  },

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

  },

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let pageNum = this.data.pageNum
    let pages = this.data.pages
    pageNum++
    if (pageNum <= pages) {
      this.setData({
        pageNum
      })
      this.getList()
    } else {
      this.setData({
        finish: true
      })
      return
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '诺信云',
      path: '/pages/index/index'
    }
  }
})