const config = require('../../config/config.js')
const Http = require('../../utils/http.js')
const HttpBasics = require('../../utils/HttpBasics.js')
const util = require('../../utils/util')
const changeNum = require('../../utils/changeNum.js')
import * as echarts from '../../ec-canvas/echarts';
var app = getApp()

function setOption(chart, xdata, ydata) {
  const option = {
    title: {
      padding: [10, 0, 0, 20],
      textStyle: {
        fontSize: 14,
        color: '#FF6A6A'
      },
    },
    backgroundColor: "#fff",
    color: ["#006EFF", "#67E0E3", "#9FE6B8"],
    animation: true,
    grid: {
      top: '3%',
      left: "5%",
      right: "7%",
      bottom: "4%",
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xdata,
      splitLine: {
        show: false
      }, //去除网格线
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    yAxis: [{
      splitLine: {
        lineStyle: {
          type: 'none'
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        rotate: 40,
        formatter: function(a, b) {
          return a
        }
      },
      type: 'value',
    }],
    series: [{
      type: 'line',
      data: ydata,
      smooth: true, //这句就是让曲线变平滑的 
      lineStyle: {
        normal: {
          color: '#33cdff',
        }
      },
      areaStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(
            0, 0, 0, 1, [{
              offset: 0,
              color: '#FFF'
            }, {
              offset: 1,
              color: '#52A0FD'
            }]
          )
        }
      },
    }]
  };
  chart.setOption(option)
  console.log(chart)
}
/**
 * 交易记录
 */
function getBarOption(x, y) {
  return {
    color: ['#FF6A6A'],
    fontSize: "14rpx",
    grid: {
      top: '3%',
      left: "5%",
      right: "7%",
      bottom: "4%",
      containLabel: true,
    },
    xAxis: {
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      type: 'category',
      boundaryGap: false,
      data: x
    },
    yAxis: {
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'none'
        }
      },
      axisLabel: {
        rotate: 40,
      }
    },
    series: [{
      data: y,
      type: 'line',
      smooth: true,
      lineStyle: {
        normal: {
          color: '#FF6A6A',
        }
      },
      areaStyle: {}
    }]
  };
};
/**
 * 核销记录
 */
function getScatterOption(x, y) {
  return {
    color: '#FFCE00',
    fontSize: "14rpx",
    grid: {
      top: '3%',
      left: "5%",
      right: "7%",
      bottom: "4%",
      containLabel: true,
    },
    xAxis: {
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      type: 'category',
      boundaryGap: false,
      data: x
    },
    yAxis: {
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'none'
        }
      },
      axisLabel: {
        rotate: 40,
      }
    },
    series: [{
      data: y,
      type: 'line',
      smooth: true,
      areaStyle: {}
    }]
  };
};
/**
 * 获取交易记录
 */
function getTabletListOrder() {
  let newArr = {
    xList: [],
    amountList: []
  }
  return new Promise((resolve, reject) => {
    Http.getRequest(config.api.dateAmountRecordListOrder, app.globalData.token, '', {}, (res) => {
      // 日期
      res.data && res.data.map(file => {
        newArr.xList.push(file.mouthAndDate)
        newArr.amountList.push(file.amountStr)
      })
      resolve(newArr);
    })
  })
};

/**
 * 获取核销记录
 */
function getTabletListVerify() {
  let newArr = {
    xList: [],
    amountList: []
  }
  return new Promise((resolve, reject) => {
    Http.getRequest(config.api.dateAmountRecordListVerified, app.globalData.token, '', {}, (res) => {
      // 日期
      res.data && res.data.map(file => {
        newArr.xList.push(file.mouthAndDate)
        newArr.amountList.push(file.amountStr)
      })
      resolve(newArr)
    })
  })
};
Page({
  data: {
    token:'',
    currentIndex: 0,
    userInfo: {},
    recordMoney: 0,
    recordData: [],
    userInfoLoadIf: false,
    ec: {
      lazyLoad: true
    },
    classIfyList: [
      // {
      //   text: '收银台',
      //   icon: 'iconfont  icon-shouyintai1',
      //   id: 3
      // },
      {
        text: '会员核销',
        icon: 'iconfont icon-hexiao',
        id: 0
      },
      // {
      //   text: '消费卡收款',
      //   icon: 'iconfont icon-shouye1',
      //   id: 1
      // },
      // {
      //   text: '当日解单',
      //   icon: 'iconfont icon-shoufukuan',
      //   id: 2
      // },
      {
        text: '会员积分',
        icon: 'iconfont icon-jifen',
        id: 4
      },
      // {
      //   text: '会员赠券',
      //   icon: 'iconfont icon-quan',
      //   id: 5
      // },
      {
        text: '营销结算',
        icon: 'iconfont icon-jiesuan',
        id: 6
      },
      // {
      //   text: '商户建券',
      //   icon: 'iconfont icon-lingquanzhongxin',
      //   id: 7
      // },
      // {
      //   text: '商品配送',
      //   icon: 'iconfont icon-wuliu',
      //   id: 8
      // }
    
    ],
    amountMoney: '',
    djZmoney:'',
    writeOffMoney: '',
    getFullYear: new Date().getFullYear(),
    getMonth: new Date().getMonth() + 1,
    getDate: new Date().getDate(),
    dateTime: '',
    show: null,
    billList: [],
    ifShowChart: null,
    ifShowChart1: null,
    ifShowChart2: null,
    ecBar: {
      lazyLoad: true
    },
    ecScatter: {
      lazyLoad: true
    },
    djArr:[],
    djMoney:[],
    count:''
  },
  //获取商户信息
  getUserInfo() {
    return new Promise((resolve, reject) => {
      Http.getRequest(config.api.userDetail, app.globalData.token, '', {}, (res) => {
        resolve(res.data);
      })
    })
  },
  //今日交易额
  getUnverifiedAmountOnDate() {
    let {
      getFullYear,
      getMonth,
      getDate,
      amountMoney,
      writeOffMoney
    } = this.data
    let dateTimer = getFullYear + '-' + getMonth + '-' + getDate
    Http.getRequest(config.api.getUnverifiedAmountOnDate, app.globalData.token, '', {
      date: dateTimer
    }, (res) => {
      console.log(res)
      this.setData({
        amountMoney: res.data.amount,
        count: res.data.orderCount,
      })
    })
  },
  //今日核销额
  getVerifiedAmountOnDate() {
    let {
      getFullYear,
      getMonth,
      getDate
    } = this.data
    let dateTimer = getFullYear + '-' + getMonth + '-' + getDate
    Http.getRequest(config.api.getVerifiedAmountOnDate, app.globalData.token, '', {
      date: dateTimer
    }, (res) => {
      this.setData({
        writeOffMoney: res.data.amount
      })
    })
  },
  onPullDownRefresh: function() {
    let that = this;
    // that.getUnverifiedAmountOnDate()
    // that.getVerifiedAmountOnDate();
    that.getpaybill();
    if (that.oneComponent) {
      that.getrecordData();
    }
    if (that.jiaoyiComponent) {
      that.getTabletListOrder();
    }
    if (that.hexiaoComponent) {
      that.getTabletListVerify();
    }
    tt.hideNavigationBarLoading();
    tt.stopPullDownRefresh();
  },
  onLoad: function (options) {
    var that = this;
    this.checkuserstatus()
  },
  onReady() {
    // this.oneComponent = this.selectComponent('#mychart-pament');
    // this.jiaoyiComponent = this.selectComponent('#mychart-jiaoyi');
    // this.hexiaoComponent = this.selectComponent('#mychart-hexiao');
    this.getrecordData();
    this.getTabletListOrder();
    this.getTabletListVerify();
    this.getUserInfo().then(res => {
      this.setData({
        userInfo: res,
        userInfoLoadIf:true
      })
      app.globalData.merchant = res;
      tt.setNavigationBarTitle({
        title: res.mall_name + "(" + res.merchant_name + ")"
      })
    })
    app.globalData.userInfo = this.getUserInfo;
  },
  /**
   * gotolook
   */
  gotobill: function(e) {
    console.log(e)
    let owe = e.currentTarget.dataset.data.owe;
    let status = e.currentTarget.dataset.data.status;
    let receivedate = e.currentTarget.dataset.data.receiveDate;
    let starttime = e.currentTarget.dataset.data.starttime;
    let endtime = e.currentTarget.dataset.data.endtime;
    let id = e.currentTarget.dataset.data.id;
    var transactionId = e.currentTarget.dataset.data.transactionId;
    var priceDetail = e.currentTarget.dataset.data.priceDetail;
    var freeze = e.currentTarget.dataset.data.freeze;

    let pay = e.currentTarget.dataset.data.pay ? e.currentTarget.dataset.data.pay : 0;
    let latePayPrice = e.currentTarget.dataset.data.latePayPrice ? e.currentTarget.dataset.data.latePayPrice : 0;
    let serviceChargePay = e.currentTarget.dataset.data.serviceChargePay ? e.currentTarget.dataset.data.serviceChargePay : 0;
    if (starttime && endtime) {
      var end = starttime + "至" + endtime;
    } else {
      var end = "";
    }
    if (transactionId) {
      var tradeTime = e.currentTarget.dataset.data.tradeTime;
    } else {
      var tradeTime = e.currentTarget.dataset.data.payDate;
    }
    console.log(e.currentTarget.dataset.data, tradeTime, 6666666)
    var billTypeValue = e.currentTarget.dataset.data.billTypeValue;
    let receivePay = e.currentTarget.dataset.data.receivePay;
    tt.navigateTo({
      url: `/pages/bill/billdetail/index?owe=${owe}&receivedate=${receivedate}&status=${status}&end=${end}&id=${id}&tradeTime=${tradeTime}&transactionId=${transactionId}&priceDetail=${priceDetail}&billTypeValue=${billTypeValue}&receivePay=${receivePay}&freeze=${freeze}&pay=${pay}&latePayPrice=${latePayPrice}&serviceChargePay=${serviceChargePay}`,
    })
  },
  /**
   * 核销记录
   */
  // hexiaoInit: function(heXiaox, heXiaoYiy) {
  //   this.hexiaoComponent.init((canvas, width, height) => {
  //     const barChart = echarts.init(canvas, null, {
  //       width: width,
  //       height: height
  //     });
  //     canvas.setChart(barChart);
  //     barChart.setOption(getScatterOption(heXiaox, heXiaoYiy));
  //     return barChart;
  //   });
  // },
  /**
   * 交易记录
   */
  // jiaoyiInit: function(jiaoYix, jiaoYiy) {
  //   this.jiaoyiComponent.init((canvas, width, height) => {
  //     const barChart = echarts.init(canvas, null, {
  //       width: width,
  //       height: height
  //     });
  //     canvas.setChart(barChart);
  //     barChart.setOption(getBarOption(jiaoYix, jiaoYiy));
  //     return barChart;
  //   });
  // },

  // init_one: function(xdata, ydata) { //初始化第一个图表
  //   console.log(this.oneComponent, xdata, ydata)
  //   this.oneComponent.init((canvas, width, height) => {
  //     const chart = echarts.init(canvas, null, {
  //       width: width,
  //       height: height
  //     });
  //     console.log(chart, xdata, ydata)
  //     setOption(chart, xdata, ydata)
  //     this.chart = chart;
  //     return chart;
  //   });
  // },
  toWriteoff(e) {
    console.log(e)
    let id = e.currentTarget.dataset.id
    console.log(id)
    if (id == 0) {
      tt.navigateTo({
        url: '/pages/scan/scan',
      })
    } else if (id == 1) {
      // 优惠卡收款
      tt.navigateTo({
        url: '/pages/cardReceive/cardReceive',
      })
    } else if (id == 2) {
      tt.navigateTo({
        url: '/pages/main/solution/solution',
      })
    } else if (id == 3) {
      tt.navigateTo({
        url: '/pages/payment/index',
      })
    } else if (id == 4) {
      tt.navigateTo({
        url: '/pages/creditSelect/index',
      })
    } else if (id == 5) {
      tt.navigateTo({
        url: '/pages/incouponSelect/index',
      })
    } else if (id == 6) {
      tt.navigateTo({
        url: '/pages/marktingsettlement/marktingsettlement',
      })
    }else if(id==7){//用户发卷
      tt.navigateTo({
        url: '/pages/sendDiscounts/sendDiscounts',
      })
    } else if (id == 8) {//商品配送
      tt.navigateTo({
        url: '/pages/delivery/delivery',
      })
    }
  },
  toTran(e) {
    let type = e.currentTarget.dataset.type
    tt.navigateTo({
      url: `./transaction/transaction?type=${type}`,
    })
  },
  onShow() {
    let that = this;
    /**
     * 交易记录
     */
    if (that.oneComponent) {
      that.getrecordData();
    }
    if (that.jiaoyiComponent) {
      that.getTabletListOrder();
    }
    if (that.hexiaoComponent) {
      that.getTabletListVerify();
    }
    /**
     * 获得交易记录和核销额
     */
    that.getUnverifiedAmountOnDate();
    that.getVerifiedAmountOnDate();
    that.getpaybill();
    that.setData({
      currentIndex: 0
    })
  },
  getpaybill: function() {
    let that = this;
    that.getUserInfo().then(res => {
      Http.postRequest(config.api.listBillOweAndWaitPay, app.globalData.token, '', {
        merchantId: res.merchant_id,
        tenantId: res.tenant_id,
      }, (res) => {
        console.log(res);
        if (res) {
          res.data.map(file => {
            if (file.starttime && file.endtime) {
              file.end = file.starttime.substring(0, 7).replace(/-/g, ".") + "-" + file.endtime.substring(0, 7).replace(/-/g, ".");
            } else {
              file.end = "";
              file.endtime = ""
            }
            file.receiveDate = util.fmtDate(file.receiveDate);
          })
          that.setData({
            billList: res.data,
            djArr : res.data.filter(item => item.status == 2),
          })
          that.data.djMoney = that.data.djArr.map(item => parseInt(item.owe / 100))
          let money = 0
          that.data.djMoney.filter(function (item, index) {
            money += item;
          }) 
          that.setData({
            djZmoney: changeNum.changePeoNumber(money) 
          })
        }
      })
    })
  },
  
  getTabletListVerify: function() {
    let that = this;
    getTabletListVerify()
      .then(res => {
        if (res.xList.length > 0 && res.amountList.length > 0) {
          that.setData({
            ifShowChart1: 'show1'
          })
          // that.hexiaoInit(res.xList, res.amountList)
        } else {
          /**
           * 判断是否显示数据表
           */
          that.setData({
            ifShowChart1: 'show'
          })
        }
      })
  },
  /**
   * 交易
   */
  getTabletListOrder: function() {
    let that = this;
    getTabletListOrder()
      .then(res => {
        console.log(res);
        if (res.xList.length > 0 && res.amountList.length > 0) {
          // that.jiaoyiInit(res.xList, res.amountList)
          that.setData({
            ifShowChart: 'show1'
          })
        } else {
          /**
           * 判断是否显示数据表
           */
          that.setData({
            ifShowChart: 'show'
          })
        }
      })
  },
  /**
   * 收银记录
   */
  getrecordData() {
    let _this = this;
    HttpBasics.get({
        url: config.api.getMicroPayAmountOnDate
      })
      .then(res => {
        _this.setData({
          recordMoney: res.data.amount
        })
      })
      .catch(err => {
        tt.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      });
    HttpBasics.get({
        url: config.api.listMicropay
      })
      .then(res => {
        let dataX = [];
        let dataY = [];
        if (res.data && res.data.length > 0) {
          _this.setData({
            ifShowChart2: "show1"
          })
          res.data.map((item, index) => {
            dataX.push(item.mouthAndDate)
            dataY.push(Number(item.amountStr))
          })
          // _this.init_one(dataX, dataY)
        } else {
          _this.setData({
            ifShowChart2: "show"
          })
        }
      })
      .catch(err => {
        tt.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      });
  },
  toTran(e) {
    let type = e.currentTarget.dataset.type
    tt.navigateTo({
      url: `/pages/transaction/transaction?type=${type}`,
    })
  },
  toRecord() {
    tt.navigateTo({
      url: `/pages/record/list/index`,
    })
  },
  
  checkuserstatus() {
    let _this = this;
    HttpBasics.get({
      url: config.api.checkPhoneStatus
    })
    .then(res => {
    })
    .catch(err => {
      if (err.code == 11005) {
        tt.redirectTo({
          url: `/pages/getuserinfo/index`
        })
      }
    });
  },

})

