package com.jeequan.jeepay.agent.ctrl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.utils.DateKit;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 统计相关接口
 *
 * @author terrfly
 * @date 2022-03-16 15:50
 */
@RestController
@RequestMapping("/api/stat")
public class StatController extends CommonCtrl{

	@Autowired private InfoAccountService infoAccountService;
	@Autowired private MchInfoService mchInfoService;
	@Autowired private AgentInfoService agentInfoService;
	@Autowired private PayOrderService payOrderService;
	@Autowired private MchStoreDeviceService mchStoreDeviceService;
	@Autowired private SysUserService sysUserService;
	@Autowired private MchQrcodeCardService mchQrcodeCardService;

	/** 统计数据 **/
	@PreAuthorize("hasAnyAuthority('ENT_C_MAIN_AGENT_COUNT', 'ENT_AGENT_STATISTIC_COUNT')")
	@RequestMapping(value="/index", method = RequestMethod.GET)
	public ApiRes currentUserInfo() {

		JSONObject paramJSON = getReqParamJSON();
		String agentNo = null;
		List<String> agentSubList = null;

		// 统计数据类型countType： 1-服务商本身数据  2-我与全部下级服务商数据  3-服务商号搜索
		Byte countType = paramJSON.getByte("countType");
		if (countType != null && countType == 2) {
			agentSubList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
		} else if (countType != null && countType == 3) {
			agentNo = getValStringRequired("agentNo");
		}else {
			agentNo = getCurrentAgentNo();
		}

		// 拓展员参数
		if (getCurrentUser().isEpUser()) {
			paramJSON.put("epUserId", getCurrentUser().getSysUser().getSysUserId());
		}

		// 1. 钱包余额
		InfoAccount infoAccount = infoAccountService.queryById(agentNo, CS.SYS_ROLE_TYPE.AGENT);

		JSONObject result = new JSONObject();
		result.put("realBalanceAmount", infoAccount == null ? 0L : infoAccount.getBalanceAmount());
		result.put("unAmount", infoAccount == null ? 0L : infoAccount.getUnAmount());
		result.put("auditProfitAmount", infoAccount == null ? 0L : infoAccount.getAuditProfitAmount());
		// 页面上的钱包余额
		Long availableBalanceAmount = infoAccount == null ? 0L : infoAccount.getBalanceAmount() - infoAccount.getUnAmount();
		result.put("availableBalanceAmount", availableBalanceAmount);

		AgentInfo agentInfo = agentInfoService.getById(getCurrentAgentNo());
		// 冻结金额 及 冻结原因
		Long freezeAmount = agentInfo == null ? 0L : agentInfo.getFreezeAmount();
		result.put("freezeAmount", freezeAmount);
		result.put("freezeDesc", agentInfo == null ? "" : agentInfo.getFreezeDesc());
		// 可提现金额（页面上的钱包余额-冻结金额）
		result.put("allowTakeAmount", Math.max(availableBalanceAmount - freezeAmount, 0L));

		JSONObject mchJson = mchInfoService.mchCount(agentNo, agentSubList, paramJSON);
		result.put("mchCount", mchJson);

		JSONObject agentJson = agentInfoService.agentCount(agentNo, agentSubList, paramJSON);
		result.put("agentCount", agentJson);

		// 日交易统计
		String mchNo = paramJSON.getString("mchNo");
		Map<String, Object> countMap = payOrderService.tradeCount(mchNo, agentNo, agentSubList, paramJSON);

		// 订单统计
		result.put("orderCount", countMap);

		// 今日交易笔数
		result.put("orderTodayCount", countMap.get("payCount"));

		// 今日交易金额
		result.put("orderTodaySum", countMap.get("payAmount"));
		// 码牌总数
		long qrCodeCardAllCount = mchQrcodeCardService.count(
				MchQrcodeCard.gw()
						.eq(MchQrcodeCard::getAgentNo, getCurrentAgentNo())
						.eq(MchQrcodeCard::getQrcState, CS.YES));
		result.put("qrCodeCardAllCount", qrCodeCardAllCount);
		// 已绑定的码牌
		long qrCodeCardBindCount = mchQrcodeCardService.count(
				MchQrcodeCard.gw()
						.eq(MchQrcodeCard::getAgentNo, getCurrentAgentNo())
						.eq(MchQrcodeCard::getQrcState, CS.YES)
						.eq(MchQrcodeCard::getBindState, CS.YES));
		result.put("qrCodeCardBindCount", qrCodeCardBindCount);
		// 剩余空码
		result.put("qrCodeCardUnBindCount", qrCodeCardAllCount - qrCodeCardBindCount);

		// 云喇叭总数
		long speakerAllCount = mchStoreDeviceService.count(MchStoreDevice.gw()
				.eq(MchStoreDevice::getAgentNo, getCurrentAgentNo())
				.eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_SPEAKER)
		);
		result.put("speakerAllCount", speakerAllCount);
		// 未绑定喇叭数
		long speakerUnCount = mchStoreDeviceService.count(MchStoreDevice.gw()
				.eq(MchStoreDevice::getAgentNo, getCurrentAgentNo())
				.eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_SPEAKER)
				.eq(MchStoreDevice::getBindState, CS.NO)
		);
		result.put("speakerUnCount", speakerUnCount);
		// 云打印总数
		long printerAllCount = mchStoreDeviceService.count(MchStoreDevice.gw()
				.eq(MchStoreDevice::getAgentNo, getCurrentAgentNo())
				.eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_PRINTER)
		);
		result.put("printerAllCount", printerAllCount);
		// 未绑定打印数
		long printerUnCount = mchStoreDeviceService.count(MchStoreDevice.gw()
				.eq(MchStoreDevice::getAgentNo, getCurrentAgentNo())
				.eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_PRINTER)
				.eq(MchStoreDevice::getBindState, CS.NO)
		);
		result.put("printerUnCount", printerUnCount);
		// 扫码pos机总数
		result.put("posAllCount", mchStoreDeviceService.count(MchStoreDevice.gw()
				.eq(MchStoreDevice::getAgentNo, getCurrentAgentNo())
				.eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_POS)
		));
		// 未绑定扫码pos数
		result.put("posUnCount", mchStoreDeviceService.count(MchStoreDevice.gw()
				.eq(MchStoreDevice::getAgentNo, getCurrentAgentNo())
				.eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_POS)
				.eq(MchStoreDevice::getBindState, CS.NO)
		));
		// 智能pos机总数
		result.put("posAllCount", mchStoreDeviceService.count(MchStoreDevice.gw()
				.eq(MchStoreDevice::getAgentNo, getCurrentAgentNo())
				.eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_AUTO_POS)
		));
		// 未绑定智能pos数
		result.put("posUnCount", mchStoreDeviceService.count(MchStoreDevice.gw()
				.eq(MchStoreDevice::getAgentNo, getCurrentAgentNo())
				.eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_AUTO_POS)
				.eq(MchStoreDevice::getBindState, CS.NO)
		));

		return ApiRes.ok(result);
	}

	/**
	 * @author: xiaoyu
	 * @date: 2022/3/23 16:39
	 * @describe: 拓展员商户统计数据
	 */
	@RequestMapping(value="/userChart", method = RequestMethod.GET)
	public ApiRes userChart() {

		Long sysUserId = getValLongRequired("sysUserId");
		String dateRange = getValString("queryDateRange");

		SysUserEntity sysUserEntity = sysUserService.getById(sysUserId);
		if (sysUserEntity == null || !sysUserEntity.getBelongInfoId().equals(getCurrentAgentNo())) {
			return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
		}

		// 返回数据
		JSONObject result = new JSONObject();
		result.put("mchAllCount", 0);
		result.put("mchTodayAddCount", 0);
		result.put("mchOnNetCount", 0);
		result.put("mchOnNetNewCount", 0);
		result.put("payAllAmount", 0);
		result.put("payAmount", 0);

		// 拓展员邀请的商户
		List<MchInfo> list = mchInfoService.list(MchInfo.gw().eq(MchInfo::getCreatedUid, sysUserId));
		if (CollUtil.isEmpty(list)) {
			return ApiRes.ok(result);
		}

		String createdStart = null;
		String createdEnd = null;
		if (StringUtils.isNotEmpty(dateRange)) {
			// 获取查询时间请求参数  [开始时间,  结束时间]
			Date[] queryDateRangeArray = DateKit.getQueryDateRange(dateRange);

			createdStart = DateUtil.formatDateTime(queryDateRangeArray[0]);
			createdEnd = DateUtil.formatDateTime(queryDateRangeArray[1]);
		}


		// 商户总数
		long mchAllCount = mchInfoService.mchCount(null, sysUserId, createdStart, createdEnd);
		result.put("mchAllCount", mchAllCount);

		// 按时间搜索商户数
		long mchTodayAddCount = mchInfoService.mchCount(null, sysUserId, createdStart, createdEnd);
		result.put("mchTodayAddCount", mchTodayAddCount);

		// 商户入网总数
		long mchOnNetCount = mchInfoService.mchApplyCount(null, sysUserId, createdStart, createdEnd);
		result.put("mchOnNetCount", mchOnNetCount);

		// 按时间搜索商户入网数
		long mchOnNetNewCount = mchInfoService.mchApplyCount(null, sysUserId, createdStart, createdEnd);
		result.put("mchOnNetNewCount", mchOnNetNewCount);

		BigDecimal payAllAmount = payOrderService.totalAmount(null, sysUserId, createdStart, createdEnd);
		result.put("payAllAmount", payAllAmount);

		BigDecimal payAmount = payOrderService.totalAmount(null, sysUserId, createdStart, createdEnd);
		result.put("payAmount", payAmount);

		return ApiRes.ok(result);
	}


}
