import { doGet, doPost, doPut, poller } from 'wechat_common/utils/request'
import { bindSiteId, bindCode } from 'wechat_common/utils/context'
import UrlConstants from 'root/constants/ecommerce/urlConstants'
import compose from 'ramda/src/compose'

import { bindRefresh, bindRetry, bindShowToast } from 'wechat_common/networkErrorManager'

export function getCategories(options) {
  return doGet(bindRetry(options))
}

export function getProducts(url) {
  return doGet(bindRefresh({ url }))
}

export const getFlashSaleProducts = bindSiteId((siteId, status, pageNum) => {
  const url = UrlConstants.ECOMMERCE.GET_FLASH_SALE_PRODUCTS(
    siteId,
    status,
    pageNum,
  )

  return doGet(bindRetry({ url }))
})

export const getGroupBuyProducts = bindSiteId(
  (siteId, status, pageNum, code) => {
    const url = UrlConstants.ECOMMERCE.GET_GROUP_BUY_PRODUCTS(
      siteId,
      status,
      pageNum,
      code,
    )

    return doGet(bindRetry({ url }))
  },
)

export function getGroupBuyDetail(options) {
  return doGet(bindRetry(options))
}

export function getProduct(options) {
  return doGet(bindRetry(options))
}
export function getShare(options) {
  return doPost(bindShowToast(options))
}

export function getSettings(options) {
  return doGet(bindRetry(options))
}

export function convertCoupon(options) {
  return doPost(bindShowToast(options))
}

export function getOptimal(options) {
  return doPost(bindShowToast(options))
}

export const getCoupons = compose(bindCode, bindSiteId)((siteId, code) =>
  doGet(bindRetry({ url: UrlConstants.ECOMMERCE.GET_COUPON_LIST_BY_SITE(siteId, code) })),
)

export const getUserCoupons = compose(bindCode, bindSiteId)(
  (siteId, code, status, page, size) =>
    doGet(bindRetry({
      url: UrlConstants.ECOMMERCE.GET_COUPON_LIST_BY_USER(
        siteId,
        code,
        status,
        page,
        size,
      ),
    })),
)

export function search(options) {
  return doPost(bindRetry(options))
}

export const getMembershipCard = compose(bindCode, bindSiteId)((siteId, code) =>
  doGet(bindRetry({ url: UrlConstants.ECOMMERCE.GET_MEMBERSHIP_CARD(siteId, code) })),
)

export function getSignature(url) {
  return doGet(bindRetry({ url }))
}
export function getAffiliateSettings(url) {
  return doGet(bindRetry({ url }))
}
export function getAffiliateMpCode(url) {
  return doGet(bindRetry({ url }))
}
export function fetchCommissionDetail(url) {
  return doGet(bindRetry({ url }))
}
export function fetchCommissionHistory(url) {
  return doGet(bindRetry({ url }))
}
export function fetchCommissionOrder(url) {
  return doGet(bindRetry({ url }))
}
export function applyAffiliate(options) {
  return doPost(bindShowToast(options))
}
export function updateAffiliate(options) {
  return doPut(bindShowToast(options))
}
export function createWithdrawal(options) {
  return doPost(bindShowToast(options))
}

export function createOrder(options) {
  doPost(bindShowToast({
    url: options.url,
    data: options.data,
    success(res) {
      if (res.status === 200) {
        const pollUrl = `/r/v1/tasks/${res.data.type}/${res.data.id}.jsm?v=2`

        poller(pollUrl, options.success, options.fail)
      } else if (options.success) {
        options.success(res)
      }
    },
    fail() {
      if (options.fail) {
        options.fail()
      }
    },
  }))
}

export function createGroupBuyOrder(options) {
  doPost(bindShowToast({
    url: options.url,
    data: options.data,
    success(res) {
      if (res.status === 200) {
        const pollUrl = `/r/v1/tasks/${res.data.type}/${res.data.id}.jsm?v=2`

        poller(pollUrl, options.success, options.fail)
      } else if (options.success) {
        options.success(res)
      }
    },
    fail(err) {
      if (options.fail) {
        options.fail(err)
      }
    },
  }))
}

export function getOrders(options) {
  doGet(bindRetry(options))
}

export function updateOrder(options) {
  doPut(bindShowToast(options))
}

export function getSliders(options) {
  doGet(bindRetry(options))
}

export function receviceCoupons(options) {
  doPost(bindShowToast(options))
}

const getOrderById = compose(bindCode, bindSiteId)(
  (siteId, code, { params: { orderId }, ...options }) => {
    doGet(bindRetry({
      url: UrlConstants.ECOMMERCE.GET_ORDERS_BY_ID({ siteId, code, orderId }),
      ...options,
    }))
  },
)

export function upload(options) {
  wx.uploadFile({
    url: options.url,
    filePath: options.filePath,
    name: 'file',
    formData: {
      token: options.token,
    },
    success: res => {
      if (options.success) {
        options.success(res)
      }
    },
  })
}

export function middleWareFunction(options) {
  return doPost(bindShowToast(options))
}

export function fetchComments(options) {
  return doGet(bindRetry(options))
}
export function fetchPointsRule(url) {
  return doGet(bindRetry({ url }))
}

export const fetchPointRecords = compose(bindCode, bindSiteId)(
  (siteId, code, page) =>
    doGet(bindRetry({
      url: UrlConstants.ECOMMERCE.FETCH_POINT_RECORDS(siteId, code, page),
    })),
)

export const fetchNewCouponList = compose(bindCode, bindSiteId)(
  (siteId, code) =>
    new Promise((resolve, reject) => {
      poller(
        UrlConstants.ECOMMERCE.FETCH_NEW_COUPON_LIST(siteId, code),
        resolve,
        reject,
      )
    }),
)

const cancelOrder = compose(bindCode, bindSiteId)(
  (siteId, code, { params: { orderId }, ...options }) =>
    doPut(bindShowToast({
      url: UrlConstants.ECOMMERCE.CANCEL_ORDER(siteId, orderId, code),
      ...options,
    })),
)

const getUserInfo = compose(bindCode, bindSiteId)((siteId, code, options) =>
  doGet(bindRetry({
    url: UrlConstants.ECOMMERCE.GET_USER_INFO(siteId, code),
    ...options,
  })),
)

export const fetchRechargeSetting = bindSiteId(siteId =>
  doGet(bindRetry({
    url: UrlConstants.ECOMMERCE.FETCH_RECHARGE_SETTING(siteId),
  })),
)

export const getStoreValueCardInfo = compose(bindCode, bindSiteId)(
  (siteId, code) =>
    doGet(bindRetry({
      url: UrlConstants.ECOMMERCE.GET_STORE_VALUE_CARD_INFO(siteId, code),
    })),
)

export const recharge = compose(bindCode, bindSiteId)(
  (siteId, code, rechargeRuleId) =>
    doPost(bindShowToast({
      url: UrlConstants.ECOMMERCE.RECHARGE(siteId),
      data: {
        code,
        rechargeRuleId,
      },
    })).then(res => {
      if (res.status === 200) {
        const pollUrl = `/r/v1/tasks/${res.data.type}/${res.data.id}.jsm?v=2`
        return new Promise(resolve => {
          poller(pollUrl, response => {
            resolve(response)
          })
        })
      } else {
        return Promise.reject(res)
      }
    }),
)

export const fetchRechargeRecords = compose(bindCode, bindSiteId)(
  (siteId, code, page) =>
    doGet(bindRetry({
      url: UrlConstants.ECOMMERCE.FETCH_RECHARGE_RECORDS(siteId, code, page),
    })),
)

export default {
  getCategories,
  getProducts,
  getProduct,
  getShare,
  getSettings,
  convertCoupon,
  search,
  getMembershipCard,
  getSignature,
  createOrder,
  createGroupBuyOrder,
  getOrders,
  updateOrder,
  getSliders,
  getFlashSaleProducts,
  getGroupBuyProducts,
  getGroupBuyDetail,
  getCoupons,
  getOptimal,
  receviceCoupons,
  getOrderById,
  upload,
  middleWareFunction,
  fetchComments,
  fetchPointsRule,
  fetchPointRecords,
  fetchNewCouponList,
  cancelOrder,
  getUserInfo,
  getStoreValueCardInfo,
  fetchRechargeSetting,
  recharge,
  fetchRechargeRecords,
}
