package com.zanxiang.game.data.serve.service.impl;

import com.zanxiang.erp.security.util.SecurityUtil;
import com.zanxiang.game.data.serve.component.DataPowerComponent;
import com.zanxiang.game.data.serve.pojo.dto.AdsOrderDetailDTO;
import com.zanxiang.game.data.serve.pojo.dto.AdsOrderDetailListDTO;
import com.zanxiang.game.data.serve.pojo.dto.AdsOrderDetailTotalDTO;
import com.zanxiang.game.data.serve.pojo.entity.AdsOrderDetail;
import com.zanxiang.game.data.serve.pojo.entity.TPayCallCpLog;
import com.zanxiang.game.data.serve.pojo.enums.OrderByEnum;
import com.zanxiang.game.data.serve.pojo.vo.AdsOrderDetailTotalVO;
import com.zanxiang.game.data.serve.pojo.vo.AdsOrderDetailVO;
import com.zanxiang.game.data.serve.pojo.vo.OrderCPDetailVO;
import com.zanxiang.game.data.serve.service.IAdsOrderDetailService;
import com.zanxiang.game.data.serve.utils.Page;
import com.zanxiang.module.util.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdsOrderDetailService implements IAdsOrderDetailService {

    @Autowired
    private Dao dao;
    @Autowired
    private DataPowerComponent dataPowerComponent;

    @Override
    public Page<AdsOrderDetailVO> listOfPage(AdsOrderDetailListDTO dto) {
        List<Long> userIds = dto.getPitcherId() == null ? dataPowerComponent.getSubUserIdList() : Collections.singletonList(Long.parseLong(dto.getPitcherId()));
        List<Long> gameIds = dto.getGameId() == null ? dataPowerComponent.getSubGameIdList() : dto.getGameId();
        if (StringUtils.isBlank(dto.getPitcherId()) && !SecurityUtil.isManager()) {
            // 只有管理员才能查看全部数据
            dto.setPitcherId(SecurityUtil.getUserId().toString());
        }
        Pager pager = dto.toPage();
        Criteria cri = Cnd.cri();
        if (StringUtils.isNotBlank(dto.getSourceSystem())) {
            cri.where().andEquals("source_system", dto.getSourceSystem());
        }
        if (StringUtils.isNotBlank(dto.getOrderId())) {
            cri.where().andEquals("order_id", dto.getOrderId());
        }
        if (StringUtils.isNotBlank(dto.getCpOrderId())) {
            cri.where().andEquals("cp_order_id", dto.getCpOrderId());
        }
        if (StringUtils.isNotBlank(dto.getMerchantOrderNo())) {
            cri.where().andEquals("merchant_order_no", dto.getMerchantOrderNo());
        }
        if (StringUtils.isNotBlank(dto.getUserId())) {
            cri.where().andEquals("game_user_id", dto.getUserId());
        }
        if (StringUtils.isNotBlank(dto.getUsername())) {
            cri.where().andEquals("username", dto.getUsername());
        }
        if (StringUtils.isNotBlank(dto.getServerName())) {
            cri.where().andEquals("server_name", dto.getServerName());
        }
        if (gameIds != null) {
            cri.where().andInList("order_game_id", gameIds);
        }
        if (CollectionUtils.isNotEmpty(dto.getChannelId())) {
            cri.where().andInStrList("agent_id", dto.getChannelId());
        }
        if (StringUtils.isNotBlank(dto.getAccountId())) {
            cri.where().andEquals("account_id", dto.getAccountId());
        }
        if (userIds != null) {
            cri.where().andInList("zx_pitcher_id", userIds);
        }
        if (StringUtils.isNotBlank(dto.getDeviceSystem())) {
            cri.where().andEquals("os", dto.getDeviceSystem());
        }
        if (StringUtils.isNotBlank(dto.getProductName())) {
            cri.where().andEquals("product_name", dto.getProductName());
        }
        if (StringUtils.isNotBlank(dto.getPayWay())) {
            cri.where().andEquals("payway", dto.getPayWay());
        }
        if (StringUtils.isNotBlank(dto.getMerchantNo())) {
            cri.where().andEquals("pay_account_id", dto.getMerchantNo());
        }
        if (StringUtils.isNotBlank(dto.getStatus())) {
            cri.where().andEquals("order_status", dto.getStatus());
        }
        if (StringUtils.isNotBlank(dto.getCpStatus())) {
            cri.where().andEquals("cp_status", dto.getCpStatus());
        }
        if (StringUtils.isNotBlank(dto.getIsFirstRecharge())) {
            cri.where().andEquals("is_first_recharge", dto.getIsFirstRecharge());
        }
        if (dto.getBeginDate() != null && dto.getEndDate() != null) {
            //下单时间，订单创建时间
            cri.where().andBetween("day", dto.getBeginDate(), dto.getEndDate());
        }
        if (dto.getRegTimeStart() != null && dto.getRegTimeEnd() != null) {
            //玩家注册时间
            cri.where().andBetween("DATE(reg_time)", dto.getRegTimeStart(), dto.getRegTimeEnd());
        }
        if (dto.getPayTimeStart() != null && dto.getPayTimeEnd() != null) {
            //支付时间，订单充值时间
            cri.where().andBetween("DATE(pay_time)", dto.getPayTimeStart(), dto.getPayTimeEnd());
        }
        if (dto.getRegPayIntervalTimeMin() != null) {
            cri.where().andGTE("TIMESTAMPDIFF(MINUTE, reg_time, pay_time)", dto.getRegPayIntervalTimeMin());
        }
        if (dto.getRegPayIntervalTimeMax() != null) {
            cri.where().andLTE("TIMESTAMPDIFF(MINUTE, reg_time, pay_time)", dto.getRegPayIntervalTimeMax());
        }
        //默认排序方式
        if (StringUtils.isBlank(dto.getSortType())) {
            dto.setSortType(OrderByEnum.DESC.getOrderType());
        }
        if (StringUtils.isBlank(dto.getSortFiled())) {
            cri.getOrderBy().orderBy("day", dto.getSortType())
                    .orderBy("order_create_time", dto.getSortType());
        } else {
            cri.getOrderBy().orderBy(dto.getSortFiled(), dto.getSortType());
        }
        List<AdsOrderDetailVO> records = dao.query(AdsOrderDetail.class, cri, pager).stream().map(this::toVO).collect(Collectors.toList());
        pager.setRecordCount(dao.count(AdsOrderDetail.class, cri));
        return new Page<>(records, pager);
    }

    @Override
    public AdsOrderDetailTotalVO orderTotal(AdsOrderDetailTotalDTO dto) {
        List<Long> userIds = dto.getPitcherId() == null ? dataPowerComponent.getSubUserIdList() : Collections.singletonList(Long.parseLong(dto.getPitcherId()));
        List<Long> gameIds = dto.getGameId() == null ? dataPowerComponent.getSubGameIdList() : dto.getGameId();
        /*if (StringUtils.isBlank(dto.getPitcherId()) && !SecurityUtil.isManager()) {
            // 只有管理员才能查看全部数据
            dto.setPitcherId(SecurityUtil.getUserId().toString());
        }*/
        Criteria cri = Cnd.cri();
        if (StringUtils.isNotBlank(dto.getSourceSystem())) {
            cri.where().andEquals("source_system", dto.getSourceSystem());
        }
        if (StringUtils.isNotBlank(dto.getOrderId())) {
            cri.where().andEquals("order_id", dto.getOrderId());
        }
        if (StringUtils.isNotBlank(dto.getCpOrderId())) {
            cri.where().andEquals("cp_order_id", dto.getCpOrderId());
        }
        if (StringUtils.isNotBlank(dto.getMerchantOrderNo())) {
            cri.where().andEquals("merchant_order_no", dto.getMerchantOrderNo());
        }
        if (StringUtils.isNotBlank(dto.getUserId())) {
            cri.where().andEquals("game_user_id", dto.getUserId());
        }
        if (StringUtils.isNotBlank(dto.getUsername())) {
            cri.where().andEquals("username", dto.getUsername());
        }
        if (StringUtils.isNotBlank(dto.getServerName())) {
            cri.where().andEquals("server_name", dto.getServerName());
        }
        if (gameIds != null) {
            cri.where().andInList("order_game_id", gameIds);
        }
        if (CollectionUtils.isNotEmpty(dto.getChannelId())) {
            cri.where().andInStrList("agent_id", dto.getChannelId());
        }
        if (StringUtils.isNotBlank(dto.getAccountId())) {
            cri.where().andEquals("account_id", dto.getAccountId());
        }
        if (userIds != null) {
            cri.where().andInList("zx_pitcher_id", userIds);
        }
        if (StringUtils.isNotBlank(dto.getDeviceSystem())) {
            cri.where().andEquals("os", dto.getDeviceSystem());
        }
        if (StringUtils.isNotBlank(dto.getProductName())) {
            cri.where().andEquals("product_name", dto.getProductName());
        }
        if (StringUtils.isNotBlank(dto.getPayWay())) {
            cri.where().andEquals("payway", dto.getPayWay());
        }
        if (StringUtils.isNotBlank(dto.getMerchantNo())) {
            cri.where().andEquals("pay_account_id", dto.getMerchantNo());
        }
        if (StringUtils.isNotBlank(dto.getStatus())) {
            cri.where().andEquals("order_status", dto.getStatus());
        }
        if (StringUtils.isNotBlank(dto.getCpStatus())) {
            cri.where().andEquals("cp_status", dto.getCpStatus());
        }
        if (StringUtils.isNotBlank(dto.getIsFirstRecharge())) {
            cri.where().andEquals("is_first_recharge", dto.getIsFirstRecharge());
        }
        if (dto.getBeginDate() != null && dto.getEndDate() != null) {
            //下单时间，订单创建时间
            cri.where().andBetween("day", dto.getBeginDate(), dto.getEndDate());
        }
        if (dto.getRegTimeStart() != null && dto.getRegTimeEnd() != null) {
            //玩家注册时间
            cri.where().andBetween("reg_time", dto.getRegTimeStart(), dto.getRegTimeEnd());
        }
        if (dto.getPayTimeStart() != null && dto.getPayTimeEnd() != null) {
            //支付时间，订单充值时间
            cri.where().andBetween("pay_time", dto.getPayTimeStart(), dto.getPayTimeEnd());
        }
        if (dto.getRegPayIntervalTimeMin() != null) {
            cri.where().andGTE("TIMESTAMPDIFF(MINUTE, reg_time, pay_time)", dto.getRegPayIntervalTimeMin());
        }
        if (dto.getRegPayIntervalTimeMax() != null) {
            cri.where().andLTE("TIMESTAMPDIFF(MINUTE, reg_time, pay_time)", dto.getRegPayIntervalTimeMax());
        }
        Sql sql = Sqls.create("""
                SELECT
                    IFNULL(SUM(amount), 0) as amount,
                    IFNULL(SUM(real_amount), 0) as real_amount
                FROM
                    game_ads.ads_order_detail
                """ + cri);
        sql.setCallback(Sqls.callback.entity());
        sql.setEntity(dao.getEntity(AdsOrderDetailTotalVO.class));
        dao.execute(sql);

        return sql.getObject(AdsOrderDetailTotalVO.class);
    }

    @Override
    public Page<OrderCPDetailVO> getOrderDetailList(AdsOrderDetailDTO dto) {
        //未传递参数，显示空结果
        if (StringUtils.isBlank(dto.getOrderId())) {
            return null;
        }
        //查询条件
        Criteria cri = Cnd.cri();
        cri.where().andEquals("order_id", dto.getOrderId());
        //拼接默认排序条件
        cri.getOrderBy().desc("create_time");
        //pager对象
        Pager pager = dto.toPage();
        //得到查询的结果
        List<OrderCPDetailVO> records = dao.query(TPayCallCpLog.class, cri, pager).stream().map(this::toVO).collect(Collectors.toList());
        pager.setRecordCount(dao.count(TPayCallCpLog.class, cri));
        return new Page<>(records, pager);
    }

    /**
     * 订单详情列表
     * @param gameOrder 原始表中的数据
     * @return AdsOrderDetailVO
     */
    private AdsOrderDetailVO toVO(AdsOrderDetail gameOrder) {
        if (gameOrder == null) {
            return null;
        }
        //自然量渠道设定名称
        if ("0".equals(gameOrder.getAgentId()) && StringUtils.isBlank(gameOrder.getAgentName())) {
            gameOrder.setAgentName("自然量");
        }
        return BeanUtil.copy(gameOrder, AdsOrderDetailVO.class);
    }

    /**
     * cp回调信息
     * @param tPayCallCpLog 原始表中的数据
     * @return OrderCPDetailVO
     */
    private OrderCPDetailVO toVO(TPayCallCpLog tPayCallCpLog) {
        if (tPayCallCpLog == null) {
            return null;
        }
        return BeanUtil.copy(tPayCallCpLog, OrderCPDetailVO.class);
    }


}
