const req = require('../../utils/request')
const company = getApp().globalData.company
const dateF = require("../../utils/date")
const Parse = getApp().Parse;
const uid = Parse.User.current()?.id



async function getStores(params) {
  let {
    val,
    uid,
    skip,
    limit,
    isShow
  } = params
  let wh1 = val ? `AND (store."storeName" LIKE '%` + val + "%'" + 'OR store."storeAddress" LIKE ' + "'%" + val + "%')" : ``
  let sql = `SELECT * ,
  ("perCapita" * 1) price,
  (SELECT room."price" FROM "ShopRoom" room 
   WHERE room."shop" = store."objectId"
   AND room."isDeleted" IS NOT TRUE
   AND room."isEnabled" = TRUE
   ORDER BY room."price" ASC LIMIT 1
  ) "minPrice",
  (SELECT clt."isCollect" FROM "DramaShopCollect" clt 
   WHERE clt."homestayStore" = store."objectId" 
   AND clt."isCollect" = TRUE
   AND clt."isDeleted" IS NOT TRUE
   AND clt."user" = '${uid}'
   LIMIT 1 
  ) "iscollect"
  FROM "ShopStore" store
  WHERE "company" = '${company}'
  AND "type" = 'stay'
  AND "isVerified" IS TRUE
  AND "isDeleted" IS NOT TRUE
  ${wh1}
  ${isShow?`ORDER BY "isShow" DESC,"iscollect","index",store."createdAt" ASC`:`ORDER BY "iscollect","isShow" DESC,"index",store."createdAt" ASC`} 
  OFFSET ${skip || 0} LIMIT ${limit || 10}`
  // console.log(sql)
  let res = await req.customSQL(sql);
  // console.log(res)
  return res
}
/**获取收货地址 */
async function getAddress() {
  let address = null
  let query = new Parse.Query("ShopAddress")
  let addressId = wx.getStorageSync('addressId')
  if (addressId) {
    query.equalTo('objectId', addressId)
  } else {
    let user = Parse.User.current();
    query.equalTo("user", user?.id);
    query.descending("is_default")
  }
  let res = await query.first()
  if (res?.id) {
    address = res?.toJSON() || null
  }
  return address
}

/**
 * 获取当前房间被占用日期
 * @param {*} rid 房间id
 */
async function getRoomOccupiaDate(rid) {
  let query = new Parse.Query('RoomOrder')
  query.equalTo('company', company)
  query.notEqualTo('isDeleted', true)
  query.equalTo('isPay', true)
  query.equalTo('room',rid)
  query.containedIn('status', [100, 200, 300, 500, 602, 102, 104])
  query.greaterThan('endTime', new Date(new Date().setHours(14, 1, 0))) //查询订单结束时间大于今天14点01的订单
  query.limit(180)
  let d = await query.find()
  let dList = []
  for (let i in d) {
    let item = d[i]
    let list = getDateList(item?.get('startTime'), item?.get('endTime'))
    dList = [...dList, ...list]
  }
  return dList
}
/**返回两个时间之中的 年-月-日 */
function getDateList(startTime, endTime) {
  startTime.setHours(0, 0, 0, 0);
  endTime.setHours(0, 0, 0, 0);
  let diff = endTime - startTime;
  let diffDate = Math.ceil(diff / (1000 * 60 * 60 * 24));
  let list = []
  for (let i = 0; i < diffDate; i++) {
    let current = new Date(startTime)
    current.setDate(startTime.getDate() + i)
    list.push({
      year: current.getFullYear(),
      month: current.getMonth(),
      date: current.getDate()
    })
  }
  return list
}
/**
 * 判断当前时间段内该房间是否空闲
 * @param {*} fromto 时间段{from,to}
 * @param {*} rid 房间id
 */
async function isFree(fromto, rid) {
  let {
    from,
    to
  } = fromto
  let endObj = {
    start: new Date(from),
    end: new Date(to),
  }
  let startObj = {
    start: new Date(from),
    end: new Date(to),
  }
  let middleObj = {
    start: new Date(from),
    end: new Date(to),
  }

  endObj.start.setHours(14, 1, 0);
  endObj.end.setHours(14, 1, 0);
  startObj.start.setHours(11, 59, 0);
  startObj.end.setHours(13, 59, 0);
  startObj.end.setDate(endObj.end.getDate()-1)
  middleObj.start.setHours(11, 59, 0)
  middleObj.end.setHours(13, 59, 0)

  let query = new Parse.Query('RoomOrder')
  query.equalTo('company', company)
  query.notEqualTo('isDeleted', true)
  query.equalTo('isPay', true)
  query.containedIn('status', [100, 200, 300, 500, 602, 102, 104])
  query.equalTo('room',rid)
  //订单结束时间在范围内
  let endQuery = new Parse.Query('RoomOrder')
  endQuery.greaterThan('endTime', endObj.start)
  endQuery.lessThan('endTime', endObj.end)
  //订单开始时间在范围内
  let startQuery = new Parse.Query('RoomOrder')
  startQuery.greaterThanOrEqualTo('startTime', startObj.start)
  startQuery.lessThanOrEqualTo('startTime', startObj.end)
  //所选时间包含在订单时间之内
  let middleQuery = new Parse.Query('RoomOrder')
  middleQuery.lessThanOrEqualTo('startTime', middleObj.start)
  middleQuery.greaterThanOrEqualTo('endTime',middleObj.end)

  //查询fromto之间进行的订单
  let mainQuery = Parse.Query.and(
    query,Parse.Query.or(endQuery, startQuery,middleQuery)
  )
  
  let c = await mainQuery.count()
  if (c && c > 0) {
    return false
  } else {
    return true
  }
}

/**获取两个date的间隔天数 */
function getDays(date1, date2) {
  const d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
  const d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
  const timeDiff = Math.abs(d2.getTime() - d1.getTime()); //绝对值
  const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); //向上取整
  return daysDiff;
}

/**
 * 用户绑定邀请关系和店铺
 * @param {*} uid 用户id
 * @param {*} shop_id 店铺id
 */
async function bindShop(uid, shop_id) {
  console.log(uid, shop_id)
  wx.request({
    url: "https://server.fmode.cn/api/yswx/bindShop",
    data: {
      uid, shop_id
    },
    method: "POST",
    success(success) {
      console.log('成功')
    console.log(success)
    return success
    },
    fail(err) {
      console.log('失败')
      console.log(err)
      return err
    },
  });
}
/**
 * 图片预览
 * @param {*} urls urls
 * @param {*} index 下标默认0
 */
async function previewImgs(urls,index){
  // console.log(urls,index)
  wx.previewImage({
    current: urls[parseInt(index)||0],
    urls: urls
  });
}
module.exports = {
  getStores,
  getAddress,
  isFree,
  getRoomOccupiaDate,
  getDays,bindShop,previewImgs
};