let Parse = getApp().Parse;
const company = getApp().globalData.company
const util = require('../../../../../utils/util.js')
const dateF = require('../../../../../utils/date')
const req = require('../../../../../utils/request')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: null,
    store: null,
    merchant: null,
    totalCount: 0,
    todayCount: 0,
    totalPrice: 0,
    todayPrice: 0,
    uid: null,
    profit: 0, //分润
    isShowPayouts: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      uid: wx.getStorageSync('merchant')?.objectId
    })
    console.log(options)
    var TIME = util.formatTime(new Date()); //当前时间
    console.log(TIME);
    let time = dateF.formatTime("YYYY-mm-dd", TIME)
    this.setData({
      time: time
    });

    let merchant = wx.getStorageSync('merchant'); //用户
    this.setData({
      merchant: merchant
    })
    if (!merchant) {
      wx.redirectTo({
        url: '/nova-tourism/pages/my/merchant/login/index'
      });
    }
    this.refersh()
  },
  async refersh() {
    await this.getShopStore()
    if (!this.data.store?.objectId) return
    await this.getShopOrder(this.data.store?.objectId)
    await this.getTodayOrder(this.data.store?.objectId)
    this.getProfit()

  },
  /**获取店铺 */
  async getShopStore() {
    let ShopStore = new Parse.Query('ShopStore')
    ShopStore.equalTo('company', company)
    ShopStore.equalTo('user', this.data.merchant.objectId)
    let shopStore = await ShopStore.first()
    if (shopStore && shopStore.id) {
      let id = shopStore.toJSON().objectId
      await this.setData({
        store: shopStore.toJSON()
      })

    } else {
      wx.setStorageSync('store', undefined)
      wx.setStorageSync('merchant', undefined)
    }
  },
  /**提现弹框-开 */
  async openPayouts() {
    await this.refersh()
    this.setData({
      isShowPayouts: true
    })
  },
  /**提现弹框-关 */
  closePayouts() {
    this.setData({
      isShowPayouts: false
    })
  },
  /**获取当前商户分润金额 */
  async getProfit() {
    let store_uid = wx.getStorageSync('merchant')?.objectId
    if (!store_uid) return
    let sql = `WITH t1 AS(--当前商户所绑定的用户
      SELECT u."objectId" FROM "_User" u 
      LEFT JOIN "ShopStore" s ON s."objectId" = u."store" 
      WHERE s."user" = '${store_uid}'--当前店长uid
    ),
  room_o AS (
    SELECT SUM((spec.value::json->>'invite-1')::FLOAT)
    FROM "RoomOrder" o,
    jsonb_each(o."incomeMap") AS spec (key, value)
    WHERE o."company"='${company}'
    AND o."isDeleted" IS NOT TRUE
    AND o."isPay" IS TRUE
    AND o."user" IN (SELECT "objectId" FROM t1)
  ),
  order_o AS (
    SELECT SUM((spec.value::json->>'invite-1')::FLOAT)
    FROM "Order" o,
    jsonb_each(o."incomeMap") AS spec (key, value)
    WHERE o."company"='${company}'
    AND o."isDeleted" IS NOT TRUE
    AND o."isPay" IS TRUE
    AND o."user" IN (SELECT "objectId" FROM t1)
  ),
  sum_t2 AS (SELECT * FROM room_o UNION ALL SELECT * FROM order_o)
  SELECT SUM(sum_t2."sum") FROM sum_t2`
    let data = await req.customSQL(sql)
    // console.log(sql)
    // console.log(data)
    let profit = data[0]?.sum || 0
    await this.setData({
      profit
    })
    this.getWithdraw()
  },
  /**
   * 分润可提现金额 = 获取当前商户分润金额-申请提现金额
   * 营业额可提现金额 = 总营业额*0.7-申请提现金额
   */
  async getWithdraw() {
    let sql = `select sum("count") as "withdraw" from "UserAgentWithdraw"
        where "company" = '${company}' and "user" = '${this.data.merchant.objectId}' 
        and "isDeleted" is not true
        and "channel" = 'sharing'
        group by "user"`
    let sql02 = `select sum("count") as "withdraw" from "UserAgentWithdraw"
        where "company" = '${company}' and "user" = '${this.data.merchant.objectId}' 
        and "isDeleted" is not true
        and "channel" = 'turnover'
        group by "user"`
    let data = await req.customSQL(sql)
    let data02 = await req.customSQL(sql02)

    console.log(data, data02)
    console.log(this.data.profit)
    let overSharing= data[0]?.withdraw || 0
    let overTurnover = data02[0]?.withdraw||0
    this.setData({
      sharing: (Math.floor(this.data.profit - overSharing * 100) / 100)?.toFixed(2),
      overSharing,
      turnover: (Math.floor((this.data.payoutPrice - overTurnover ) * 100) / 100)?.toFixed(2),
      overTurnover,
      // earnings: (Math.floor((this.data.profit - data[0].withdraw + payoutPrice) * 100) / 100)?.toFixed(2)
    })
 
    // console.log(this.data.earnings)
  },

  /**获取累计订单数据 */
  async getShopOrder(id) {
    /**民宿订单sql */
    let sql = ''
    if (this.data.store.type == 'stay') {
      sql = `select count("objectId") as "count", sum("price") as "totalPrice"  from "RoomOrder"
           where "company" = '${company}' and "shopStore" = '${id}' and "isPay" = true and "isDeleted" is not true
           group by "shopStore"`
    } else {
      sql = `select count("objectId") as "count", sum("totalPrice") as "totalPrice"  from "ShopOrder"
            where "company" = '${company}' and "shopStore" = '${id}' and "status" <> 100
            group by "shopStore"`
    }
    let data = await req.customSQL(sql)
    let gift_sql = `select count("objectId") as "count", sum("totalPrice") as "totalPrice"  from "Order"
    where "company" = '${company}' and "store" = '${id}' and "isPay" = true and "isDeleted" is not true
    group by "store"`
    let gift_data = await req.customSQL(gift_sql)
    let totalCount = parseFloat(data[0]?.count || 0) + parseFloat(gift_data[0]?.count || 0)
    let totalPrice = ((parseFloat(data[0]?.totalPrice || 0) * 1000) + (parseFloat(gift_data[0]?.totalPrice || 0) * 1000)) / 1000
    this.setData({
      totalCount: totalCount || 0,
      totalPrice: totalPrice || 0,
      payoutPrice: Math.floor(totalPrice * 0.7 * 100) / 100,
      room_count: parseFloat(data[0]?.count || 0),
      room_totalPrice: parseFloat(data[0]?.totalPrice || 0),
      gift_count: parseFloat(gift_data[0]?.count || 0),
      gift_totalPrice: parseFloat(gift_data[0]?.totalPrice || 0),
    })
  },


  /** 获取今日订单数据*/
  async getTodayOrder(id) {
    var TIME = util.formatTime(new Date()); //当前时间
    console.log(TIME);
    let time = dateF.formatTime("YYYY-mm-dd 00:00:10", TIME)
    console.log(time);
    let sql = ''
    if (this.data.store.type == 'stay') {
      sql = `select count("objectId") as "count", sum("price") as "totalPrice"  from "RoomOrder"
           where "company" = '${company}' and "shopStore" = '${id}' and "isPay" = true and "createdAt" > '${time}'
           group by "shopStore"`
    } else {
      sql = `select count("objectId") as "count", sum("price") as "totalPrice"  from "ShopOrder"
            where "company" = '${company}' and "shopStore" = '${id}' and "status" <> 100 and "createdAt" > '${time}'
            group by "shopStore"`
    }
    let data = await req.customSQL(sql)

    let gift_sql = `select count("objectId") as "count", sum("totalPrice") as "totalPrice"  from "Order"
    where "company" = '${company}' and "store" = '${id}' and "isPay" = true and "createdAt" > '${time}' and "isDeleted" is not true
    group by "store"`
    // console.log(gift_sql)
    let gift_data = await req.customSQL(gift_sql)
    let todayCount = parseFloat(data[0]?.count || 0) + parseFloat(gift_data[0]?.count || 0)
    let todayPrice = ((parseFloat(data[0]?.totalPrice || 0) * 1000) + (parseFloat(gift_data[0]?.totalPrice || 0) * 1000)) / 1000
    this.setData({
      todayCount: todayCount || 0,
      todayPrice: todayPrice || 0,
      room_todayCount: parseFloat(data[0]?.count || 0),
      room_todayPrice: parseFloat(data[0]?.totalPrice || 0),
      gift_todayCount: parseFloat(gift_data[0]?.count || 0),
      gift_todayPrice: parseFloat(gift_data[0]?.totalPrice || 0),
    })

  },

  // orderlist() {
  //     let storeId = this.data.store.objectId
  //     wx.navigateTo({
  //         url: '../merchant-home/order-list/index?storeId=' + storeId
  //     });
  // },
  //民宿
  order2list() {
    let storeId = this.data.store.objectId
    wx.navigateTo({
      url: '../merchant-home/order2-list/index?storeId=' + storeId
    });
  },
  giftOrder2list() {
    let storeId = this.data.store.objectId
    wx.navigateTo({
      url: '../merchant-home/gift-order/index?storeId=' + storeId
    });
  },
  // order3list() {
  //     let storeId = this.data.store.objectId
  //     wx.navigateTo({
  //         url: '../merchant-home/order3-list/index?storeId=' + storeId
  //     });
  // },

  // goods() {
  //     let id = this.data.store.objectId
  //     wx.navigateTo({
  //         url: '/nova-tourism/pages/my/merchant/merchant-home/goods/index?id=' + id
  //     });

  // },

  logout() {
    wx.showModal({
      title: '确认要退出吗？',
      showCancel: true,
      success(res) {
        if (res.confirm) {
          wx.removeStorageSync('merchant')
          wx.removeStorageSync('store')
          wx.navigateTo({
            url: '../../../../pages/index/index'
          })
        } else {

        }
      }
    })
  },
  package() {

    wx.navigateTo({
      url: '/nova-tourism/pages/my/merchant/merchant-home/package/index'
    });

  },
  dishes() {
    let id = this.data.store.objectId
    wx.navigateTo({
      url: '/nova-tourism/pages/my/merchant/merchant-home/dishes/index?id=' + id
    });

  },
  tables() {
    let id = this.data.store.objectId
    wx.navigateTo({
      url: '/nova-tourism/pages/my/merchant/merchant-home/tables/index?id=' + id
    });

  },
  // category() {
  //     let id = this.data.store.objectId
  //     let type = this.data.store.type
  //     wx.navigateTo({
  //         url: `/nova-tourism/pages/my/merchant/merchant-home/category/index?id=${id}&&type=${type}`
  //     });

  // },
  goodmanage() {
    wx.navigateTo({
      url: '../good/good-list/index'
    });

  },
  roommanage() {
    wx.navigateTo({
      url: '../room-manage/index'
    });

  },
  account() {
    wx.navigateTo({
      url: '../merchant-home/account/index'
    });

  },

  comments() {
    switch (this.data.store.type) {
      case 'stay':
        wx.navigateTo({
          url: '../../merchant/comments/hotel/index'
        });
        break;
      case 'catering':
        wx.navigateTo({
          url: '/nova-tourism/pages/my/merchant/comments/setmeal/index'
        });
        break;
      case 'shop':
        wx.navigateTo({
          url: '/nova-tourism/pages/my/merchant/comments/setmeal/index'
        });
        break;
      default:
        break;
    }

  },


  async codeVerify() {
    console.log(this.data.store.type);
    let that = this
    wx.scanCode({
      success(res) {
        let content = res.result
        console.log(content)
        let code1 = content || content.match(/\id=(.*)/)[1]
        console.log(code1);
        switch (that.data.store.type) {
          case 'stay':
            wx.navigateTo({
              url: `../code-verify/index?id=${code1}`
            });
            break;
          case 'catering':
            wx.navigateTo({
              url: `/nova-tourism/pages/shop-admin/index?id=${code1}`
            });
            break;
          case 'shop':
            wx.navigateTo({
              url: `/nova-tourism/pages/shop-admin/index?id=${code1}`
            });
            break;
          default:
            break;
        }
        // wx.navigateTo({
        //     url: `/nova-tourism/pages/my/merchant/code-verify/index?id=${res.id}`
        // });
      },
      fail(err) {
        console.log(err)
        wx.showToast({
          title: '扫码失败，请确认二维码信息正确',
          icon: 'none'
        })
      }
    })
  },
  toWithdraw(e) {
    let {price,channel} = e.currentTarget.dataset
    let id = this.data.store.storeName
    wx.navigateTo({
      url: `../../merchant/merchant-home/store-withdraw/index?earnings=${price||0}&&channel=${channel}&&id=${id}`,
    })
  },

  gourl(e) {
    const url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: `${url}`,
    });
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})