package org.springblade.modules.ldt.shop.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import oracle.jdbc.proxy.annotation.Post;
import org.springblade.common.constant.SystemConstant;
import org.springblade.common.enums.OrderType;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.modules.ldt.activity.dto.ActivityDTO;
import org.springblade.modules.ldt.activity.entity.Activity;
import org.springblade.modules.ldt.activity.service.IActivityService;
import org.springblade.modules.ldt.billrecord.entity.BillRecord;
import org.springblade.modules.ldt.billrecord.service.IBillRecordService;

import org.springblade.modules.ldt.billrecord.vo.BillRecordVO;
import org.springblade.modules.ldt.billrecord.wrapper.BillRecordWrapper;
import org.springblade.modules.ldt.loginuser.service.ILoginUserService;
import org.springblade.modules.ldt.member.entity.Member;
import org.springblade.modules.ldt.member.service.IMemberService;
import org.springblade.modules.ldt.member.vo.MemberVO;
import org.springblade.modules.ldt.pointdetail.entity.PointDetail;
import org.springblade.modules.ldt.pointdetail.service.IPointDetailService;
import org.springblade.modules.ldt.pointdetail.vo.PointDetailVO;
import org.springblade.modules.ldt.shop.entity.Shop;
import org.springblade.modules.ldt.shop.service.IShopService;
import org.springblade.modules.ldt.shop.vo.AppShopStaticVO;
import org.springblade.modules.ldt.shopyingshou.entity.ShopYingshou;
import org.springblade.modules.ldt.shopyingshou.service.IShopYingshouService;
import org.springblade.modules.ldt.shopyingshou.vo.ShopYingshouVO;
import org.springblade.modules.system.service.IParamService;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created By lidexi in 2021/7/30
 **/
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-ldt/app/shop")
@Api(value = "商店app接口", tags = "商店app接口")
public class AppShopController {

	private final IShopService shopService;
	private final IActivityService activityService;
	private final IMemberService memberService;
	private final IBillRecordService billRecordService;
	private final IPointDetailService pointDetailService;
	private final IShopYingshouService shopYingshouService;
	private final ILoginUserService loginUserService;




	/**
	 * 商店创建会员中心
	 *
	 * @param shop
	 * @return
	 */
	@PostMapping("/createMemberCenter")
	@ApiOperation(value = "商店创建会员中心", notes = "传入商店")
	public R createMemberCenter(@RequestBody Shop shop) {
		Shop oldEntity = shopService.getById(shop.getId());
		Assert.isFalse(oldEntity.getIsOpenMember() == 1,"该商家已经创建过会员中心，不可重复创建");
		Assert.notNull(oldEntity, "商店不存在");
		Assert.isTrue( SystemConstant.AuditStatus.PASS.getValue() == oldEntity.getAuditStatus(),
			"商店还没通过审核，不能创建会员中心，请先联系商场审核");
		Assert.notNull(shop.getPoint(),"积分数不能为空");
		Assert.notNull(shop.getPointValue(),"积分对应的积分价值不能为空");
		Assert.notNull(shop.getConsumeOnePoint(),"每消费一元赠送的积分数不能为空");
		oldEntity.setPoint(shop.getPoint());
		oldEntity.setPointValue(shop.getPointValue());
		oldEntity.setConsumeOnePoint(shop.getConsumeOnePoint());
		oldEntity.setIsOpenMember(SystemConstant.WHETHER.YES.getValue());
		return R.status(shopService.updateById(oldEntity));
	}

	/**
	 * 通过商店id获取活动信息
	 */
	@GetMapping("/getActivity")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "通过商店id获取活动信息", notes = "传入activityDTO")
	public R<IPage<Activity>> getMembersByMallId(ActivityDTO activityDTO, Query query) {
		Assert.notNull(activityDTO.getSelectType() == null,"查询类型字段不能为空");
		Assert.notNull(activityDTO.getSponsorId(),"商店id不能为空");
		IPage<Activity> pages = null;
		if(activityDTO.getSelectType() == 1){//查询该商店发起的活动
			pages = activityService.page(Condition.getPage(query), new QueryWrapper<>(new Activity()).lambda()
				.eq(Activity::getSponsorType,SystemConstant.MALLORSHOP.SHOP.getValue()).eq(Activity::getSponsorId,activityDTO.getSponsorId())
				.orderByDesc(Activity::getCreateTime));
		}else if(activityDTO.getSelectType() == 2){//可以参加的活动
			//获取该商店所属商场发布的活动
			pages = this.activityService.getCanJoinActicityByShopId(Condition.getPage(query),activityDTO.getSponsorId());

		}else if(activityDTO.getSelectType() == 3){//已参加的活动
			//从活动参加记录表中获取
			pages = this.activityService.getHadJoinActivityByShopId(Condition.getPage(query),activityDTO.getSponsorId());
		}

		return R.data(pages);
	}



	/**
	 * 通过商店id获取会员列表
	 */
	@GetMapping("/getMembersByShopId")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "通过商店id获取会员列表", notes = "传入member")
	public R<IPage<MemberVO>> getMembersByShopId(MemberVO member, Query query) {
		Assert.notNull(member.getShopId(),"商店id不能为空");
		member.setType(SystemConstant.MALLORSHOP.SHOP.getValue());
		query.setDescs("point_value");
		IPage<MemberVO> pages = memberService.selectMemberPage(Condition.getPage(query),member);

		return R.data(pages);
	}

	/**
	 * 获取某个会员在某个商户中的历史消费记录
	 */
	@GetMapping("/getMemberBillRecord")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "获取某个会员在某个商户中的历史消费记录", notes = "传入member")
	public R<IPage<BillRecordVO>> getMemberBillRecord(MemberVO member, Query query) {
		Assert.notNull(member.getShopId(),"商店id不能为空");
		Assert.notNull(member.getId(),"会员id不能为空");

		IPage<BillRecord> pages = billRecordService.page(Condition.getPage(query),new QueryWrapper<>(new BillRecord())
			.lambda().eq(BillRecord::getPayStatus,SystemConstant.BillRecordPayStatus.PAYED.getValue())
			.eq(BillRecord::getShopId,member.getShopId())
			.eq(BillRecord::getType, OrderType.USER_PAY)
			.eq(BillRecord::getMemberId,member.getId())
			.orderByDesc(BillRecord::getUpdateTime));

		return R.data(BillRecordWrapper.build(loginUserService,pointDetailService).pageVO(pages));
	}

	/**
	 * 应收明细
	 */
	@GetMapping("/getYingShouPage")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "应收明细", notes = "传入pointDetail")
	public R<IPage<ShopYingshou>> getYingShouPage(ShopYingshouVO shopYingshou, Query query) {
		Assert.notNull(shopYingshou.getShopId(),"商店id不能为空");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
		String selectMonth = null;
		try {
			selectMonth = simpleDateFormat.format(simpleDateFormat.parse(shopYingshou.getMonthTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		IPage<ShopYingshou> pages = shopYingshouService.page(Condition.getPage(query),new QueryWrapper<>(new ShopYingshou()).lambda()
			.eq(ShopYingshou::getShopId,shopYingshou.getShopId())
			.eq(ShopYingshou::getBillRecordStatus,SystemConstant.BillRecordPayStatus.PAYED.getValue())
			.eq(ShopYingshou::getJsStatus,SystemConstant.JieSuanStatus.jsing.getValue())
			.like(ShopYingshou::getUpdateTime,selectMonth)
			.orderByDesc(ShopYingshou::getUpdateTime));
		return R.data(pages);
	}

	/**
	 * 余额明细
	 */
	@GetMapping("/getRemainDetailPage")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "通过商店id获取会员列表", notes = "传入billRecord")
	public R<IPage<BillRecordVO>> getRemainDetailPage(BillRecordVO billRecord, Query query) {
		Assert.notNull(billRecord.getShopId(),"商店id不能为空");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");

		String selectMonth = null;
		try {
			selectMonth = simpleDateFormat.format(simpleDateFormat.parse(billRecord.getMonthTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		IPage<BillRecord> pages = billRecordService.page(Condition.getPage(query),new QueryWrapper<>(new BillRecord()).lambda()
				.eq(BillRecord::getShopId,billRecord.getShopId()).eq(BillRecord::getPayStatus,1)
				.like(BillRecord::getUpdateTime,selectMonth).orderByDesc(BillRecord::getUpdateTime));

		return R.data(BillRecordWrapper.build(loginUserService,pointDetailService).pageVO(pages));



	}

	/**
	 * 商户修改会员中心
	 */
	@PostMapping("/updateMemberCenter")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "通过商店id获取会员列表", notes = "传入billRecord")
	public R updateMemberCenter(@RequestBody Shop shop) {
		Assert.notNull(shop.getId(),"商店id不能为空");
		Assert.notNull(shop.getConsumeOnePoint(),"每消费一元赠送多少积分不能为空");

		Shop oldEntity = shopService.getById(shop.getId());
		Assert.notNull(oldEntity,"商户不存在");
		oldEntity.setConsumeOnePoint(shop.getConsumeOnePoint());

		return R.data(shopService.updateById(oldEntity));

	}

	/**
	 * 商店首页获取统计数据
	 *
	 * @param shopId
	 * @return
	 */
	@GetMapping("/statistic")
	@ApiOperation(value = "商店首页获取统计数据", notes = "传入商店id")
	public R<AppShopStaticVO> statistic(@RequestParam Long shopId) {
		Shop shop = shopService.getById(shopId);
		Assert.notNull(shop,"商店不存在");

		AppShopStaticVO appShopStaticVO = new AppShopStaticVO();
		//统计会员总数
		List<Member> members = memberService.getBaseMapper().selectList(new QueryWrapper<>(new Member()).lambda()
			.eq(Member::getShopId, shopId).eq(Member::getType,SystemConstant.MALLORSHOP.SHOP.getValue()));
		//商场会员总数
		Integer memberCount = members.size();
		//今日会员新增
		Integer todayMemberIn = 0;

		//今日营收
		BigDecimal todayIncome = BigDecimal.ZERO;
		//今日交易笔数
		Integer todayOrderCount = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date today = new Date();
		//今日新增会员数
		try {
			Date todayDate = sdf.parse(sdf.format(today));
			todayMemberIn = members.stream().filter(member -> member.getCreateTime().after(todayDate)).collect(Collectors.toList()).size();


			//今日营收
			List<BillRecord> billRecords = billRecordService.getBaseMapper().selectList(new QueryWrapper<>(new BillRecord()).lambda()
				.eq(BillRecord::getShopId, shopId).eq(BillRecord::getPayStatus, SystemConstant.BillRecordPayStatus.PAYED.getValue())
				.gt(BillRecord::getCreateTime, todayDate));

			todayIncome = billRecords.stream().map(BillRecord::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

			todayOrderCount = billRecords.size();

		} catch (Exception e) {
			e.printStackTrace();
		}



		return R.data(appShopStaticVO.setMemberCount(memberCount)
			.setTodayMemberIn(todayMemberIn)
			.setTodayIncome(todayIncome)
			.setTodayOrderCount(todayOrderCount)
			.setTotalAccount(shop.getWithdrawTotalPrice()));
	}

}
