package com.jeequan.jeepay.mch.ctrl.product;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.PackageOrder;
import com.jeequan.jeepay.db.entity.ProductInfo;
import com.jeequan.jeepay.db.entity.ProductType;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.ProductAppService;
import com.jeequan.jeepay.service.impl.ProductInfoService;
import com.jeequan.jeepay.service.impl.ProductTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品中心
 *
 * @author huay
 * @date 2023-11-08 14:50
 */
@RestController
@RequestMapping("/api/product")
public class ProductController extends CommonCtrl {

	@Autowired private ProductInfoService productInfoService;
	@Autowired private ProductTypeService productTypeService;
	@Autowired private ProductAppService productAppService;

	/**
	 * 产品中心列表
	 * **/
	@RequestMapping(value = "/getProductList", method = RequestMethod.GET)
	@MethodLog(remark = "产品中心列表")
	public ApiRes getProductList() throws BizException {
		ProductInfo productInfo = getObject(ProductInfo.class);
		/*LambdaQueryWrapper<ProductInfo> wrapper = ProductInfo.gw();
		selectParams(productInfo, wrapper);
		wrapper.orderByDesc(ProductInfo::getCreatedAt);*/
		Page<ProductInfo> page = new Page<>();
		List<ProductInfo> productInfoList = productInfoService.getProductList(productInfo.getProductName(),productInfo.getState(),productInfo.getProductType());
		page.setRecords(productInfoList);
		page.setTotal(productInfoList.size());
		page.setCurrent(1);
		return ApiRes.ok(page);
	}

	@RequestMapping(value = "/getProductById", method = RequestMethod.GET)
	@MethodLog(remark = "产品详情")
	public ApiRes getProductById() throws BizException {
		//获取查询条件
		ProductInfo productInfo = getObject(ProductInfo.class);

		ProductInfo info  = productInfoService.getProductById(productInfo.getProductId());
		//查询已关联已开通的应用数量，
		List<PackageOrder> packageOrderList = productAppService.getList(productInfo.getProductId(),getCurrentMchNo());
		List<String> bindingApp = packageOrderList.stream().map(PackageOrder::getAppId).filter(str-> !str.isEmpty()).distinct().collect(Collectors.toList());
		info.setApplyCount(packageOrderList.size());
		info.setBindingAppList(bindingApp);
		//返回收费信息和剩余天数以及总剩余天数
		List<PackageOrder> packageOrderListSave =new ArrayList<>();
		long allRemainingDays = 0L;
		for (PackageOrder packageOrder : packageOrderList) {
			if (packageOrder.getCostRule() != null){
				JSONArray costRule = packageOrder.getCostRule();
				//目前规则只能选取一条
				int validTime = costRule.getJSONObject(0).getIntValue("validTime");
				if (costRule.getJSONObject(0).getDate("autoTime") != null){
					LocalDate currentDate = costRule.getJSONObject(0).getDate("autoTime").toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
					// 计算到期后的日期
					LocalDate futureDate = currentDate.plusDays(validTime);
					// 计算剩余天数
					LocalDate today = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
					long remainingDays = ChronoUnit.DAYS.between(today, futureDate);
					packageOrder.setRemainingDays(remainingDays);
					//暂时不需要
					//productAppListSave.add(productApp);
					allRemainingDays += remainingDays;
				}
			}
		}
		//暂时不需要
		//info.setProductAppList(productAppListSave);
		info.setAllRemainingDays(allRemainingDays);
		return ApiRes.ok(info);
	}

	@RequestMapping(value = "/startProduct", method = RequestMethod.POST)
	@MethodLog(remark = "产品开通")
	public ApiRes startProduct() throws BizException {
		//获取查询条件
		PackageOrder app = getObject(PackageOrder.class);
		app.setMchNo(getCurrentMchNo());
		app.setCreatedAt(new Date());
		app.setUpdatedAt(new Date());
		app.setPracPrice(BigDecimal.valueOf(0));
		productInfoService.startProduct(app);
		return ApiRes.ok("已提交！");
	}

	@RequestMapping(value = "/getProductTypeList", method = RequestMethod.GET)
	@MethodLog(remark = "获取所有分类列表")
	public ApiRes getProductTypeList() throws BizException {
		return ApiRes.ok(productTypeService.list(ProductType.gw()));
	}

	/**
	 * @author: huay
	 * @describe: 查询公共条件
	 */
	public void selectParams(ProductInfo productInfo, LambdaQueryWrapper<ProductInfo> wrapper) {
		wrapper.like(StringUtils.isNotEmpty(productInfo.getProductName()), ProductInfo::getProductName, productInfo.getProductName());
		wrapper.eq(ProductInfo::getState, productInfo.getState());
	}

}
