package org.springblade.modules.ldt.mall.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.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.SystemConstant;
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.activityjoinrecord.entity.ActivityJoinRecord;
import org.springblade.modules.ldt.activityjoinrecord.service.IActivityJoinRecordService;
import org.springblade.modules.ldt.billrecord.entity.BillRecord;
import org.springblade.modules.ldt.billrecord.service.IBillRecordService;
import org.springblade.modules.ldt.mall.entity.Mall;
import org.springblade.modules.ldt.mall.service.IMallService;
import org.springblade.modules.ldt.mall.vo.AppMallStaticVO;
import org.springblade.modules.ldt.mallarea.entity.MallArea;
import org.springblade.modules.ldt.mallarea.service.IMallAreaService;
import org.springblade.modules.ldt.mallshoplabel.entity.MallShopLabel;
import org.springblade.modules.ldt.mallshoplabel.service.IMallShopLabelService;
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.shop.dto.ShopDTO;
import org.springblade.modules.ldt.shop.entity.Shop;
import org.springblade.modules.ldt.shop.service.IShopService;
import org.springblade.modules.ldt.shop.vo.ShopVO;
import org.springblade.modules.ldt.shop.wrapper.ShopWrapper;
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/27
 **/
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-ldt/app/mall")
@Api(value = "商场app接口", tags = "商场app接口")
public class AppMallController {

	private final IMallService mallService;
	private final IMallAreaService mallAreaService;
	private final IMallShopLabelService mallShopLabelService;
	private final IShopService shopService;
	private final IMemberService memberService;
	private final IBillRecordService billRecordService;
	private final IActivityService activityService;

	/**
	 * 通过手机获取商场信息
	 *
	 * @param phone
	 * @return
	 */
	@GetMapping("/getMyMallList")
	@ApiOperation(value = "通过手机获取商场信息", notes = "传入phone")
	public R<List<Mall>> getMyMallList(@RequestParam String phone) {
		List<Mall> malls = this.mallService.getBaseMapper().selectList(new QueryWrapper<>(new Mall()).lambda()
			.eq(Mall::getPersonTel, phone));
		return R.data(malls);
	}

	/**
	 * 通过商场id获取商场区域列表
	 *
	 * @param mallId
	 * @return
	 */
	@GetMapping("/getMallAreaByMallId")
	@ApiOperation(value = "通过商场id获取商场区域列表", notes = "传入商场id")
	public R<List<MallArea>> getMallAreaByMallId(@RequestParam String mallId) {
		List<MallArea> mallAreas = this.mallAreaService.getBaseMapper().selectList(new QueryWrapper<>(new MallArea()).lambda()
			.eq(MallArea::getMallId, mallId));
		return R.data(mallAreas);
	}

	/**
	 * 通过商场id获取商场商店标签列表
	 *
	 * @param mallId
	 * @return
	 */
	@GetMapping("/getShopLabelByMallId")
	@ApiOperation(value = "通过商场id获取商场商店标签列表", notes = "传入商场id")
	public R<List<MallShopLabel>> getShopLabelByMallId(@RequestParam Long mallId) {
		List<MallShopLabel> mallShopLabels = this.mallShopLabelService.getBaseMapper().selectList(new QueryWrapper<>(new MallShopLabel()).lambda()
			.eq(mallId != null,MallShopLabel::getMallId, mallId)
			.isNull(mallId == null,MallShopLabel::getMallId));
		return R.data(mallShopLabels);
	}

	/**
	 * 商场审核商户
	 *
	 * @param shop
	 * @return
	 */
	@PostMapping("/auditShop")
	@ApiOperation(value = "商场审核商户", notes = "传入商场")
	public R auditShop(@RequestBody Shop shop) {
		Shop oldEntity = shopService.getById(shop.getId());
		Assert.notNull(oldEntity, "商户不存在");
		oldEntity.setAuditStatus(shop.getAuditStatus());
		oldEntity.setAuditAdvice(shop.getAuditAdvice());

		return R.status(shopService.updateById(oldEntity));
	}

	/**
	 * 商场获取已经审核通过的商店列表
	 *
	 * @param shopDTO
	 * @return
	 */
	@GetMapping("/getShopList")
	@ApiOperation(value = "商场获取商店列表", notes = "传入商场")
	public R<IPage<ShopVO>> getShopList(ShopDTO shopDTO, Query query) {
		Assert.notNull(shopDTO.getMallId(), "商场id不能为空");
		IPage<Shop> shops = shopService.getBaseMapper().selectPage(Condition.getPage(query), new QueryWrapper<>(new Shop()).lambda().eq(shopDTO.getAuditStatus() != null, Shop::getAuditStatus, shopDTO.getAuditStatus())
			.eq(shopDTO.getMallId() != null, Shop::getMallId, shopDTO.getMallId()).like(shopDTO.getLabelId() != null, Shop::getLabelIds, shopDTO.getLabelId())
			.eq(shopDTO.getMallAreaId() != null, Shop::getMallAreaId, shopDTO.getMallAreaId())
			.like(shopDTO.getFullName() != null, Shop::getFullName, shopDTO.getFullName()));
		return R.data(ShopWrapper.build(mallAreaService,mallService).pageVO(shops));
	}

	/**
	 * 商场首页获取统计数据
	 *
	 * @param mallId
	 * @return
	 */
	@GetMapping("/statistic")
	@ApiOperation(value = "商场首页获取统计数据", notes = "传入商场id")
	public R<AppMallStaticVO> statistic(@RequestParam Long mallId) {
		Assert.notNull(mallId,"商场id不能为空");
		AppMallStaticVO appMallStaticVO = new AppMallStaticVO();
		//统计会员总数
		List<Member> members = memberService.getBaseMapper().selectList(new QueryWrapper<>(new Member()).lambda()
			.eq(Member::getMallId, mallId).isNull(Member::getShopId));
		//商场会员总数
		Integer memberCount = members.size();
		//今日会员新增
		Integer todayMemberIn = 0;
		//商店总数
		Integer shopCount = 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<Shop> shops = shopService.getBaseMapper().selectList(new QueryWrapper<>(new Shop()).lambda().eq(Shop::getMallId, mallId)
				.eq(Shop::getAuditStatus,SystemConstant.AuditStatus.PASS.getValue()));
			shopCount = shops.size();

			//今日营收
			List<BillRecord> billRecords = billRecordService.getBaseMapper().selectList(new QueryWrapper<>(new BillRecord()).lambda()
				.eq(BillRecord::getMallId, mallId).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(appMallStaticVO.setMemberCount(memberCount)
			.setShopCount(shopCount)
			.setTodayMemberIn(todayMemberIn)
			.setTodayIncome(todayIncome)
			.setTodayOrderCount(todayOrderCount));
	}

	/**
	 * 商场创建会员中心
	 *
	 * @param mall
	 * @return
	 */
	@PostMapping("/createMemberCenter")
	@ApiOperation(value = "商场创建会员中心", notes = "传入商场")
	public R createMemberCenter(@RequestBody Mall mall) {
		Mall oldEntity = mallService.getById(mall.getId());
		Assert.isFalse(oldEntity.getIsOpenMember() == 1,"该商场已经创建过会员中心，不可重复创建");
		Assert.notNull(oldEntity, "商场不存在");
		Assert.notNull(mall.getPoint(), "积分数不能为空");
		Assert.notNull(mall.getPointValue(), "积分对应的积分价值不能为空");
		Assert.notNull(mall.getConsumeOnePoint(), "每消费一元赠送的积分数不能为空");
		oldEntity.setPoint(mall.getPoint());
		oldEntity.setPointValue(mall.getPointValue());
		oldEntity.setConsumeOnePoint(mall.getConsumeOnePoint());
		oldEntity.setIsOpenMember(SystemConstant.WHETHER.YES.getValue());
		return R.status(mallService.updateById(oldEntity));
	}


	/**
	 * 通过商场id获取商场详情
	 *
	 * @param mallId
	 * @return
	 */
	@GetMapping("/getById")
	@ApiOperation(value = "通过商场id获取商场详情", notes = "传入商场id")
	public R<Mall> getById(@RequestParam Long mallId) {
		return R.data(this.mallService.getById(mallId));
	}

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

	/**
	 * 通过商场id获取活动信息
	 */
	@GetMapping("/getActivity")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "通过商场id获取活动信息", notes = "传入member")
	public R<IPage<Activity>> getMembersByMallId(ActivityDTO activityDTO, Query query) {
		Assert.notNull(activityDTO.getSelectType() == null, "查询类型字段不能为空");
		Assert.notNull(activityDTO.getMallId(), "商场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.MALL.getValue()).eq(Activity::getSponsorId, activityDTO.getMallId())
				.ne(Activity::getAuditStatus,SystemConstant.AuditStatus.STOP.getValue())
				.orderByDesc(Activity::getCreateTime));
		} else if (activityDTO.getSelectType() == 2) {//可以参加的活动
			//获取该商场下所有商户发布的活动
			pages = this.activityService.getCanJoinActicityByMallId(Condition.getPage(query), activityDTO.getMallId());

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

		return R.data(pages);
	}

	/**
	 * 活动审核
	 */
	@PostMapping("/auditActivity")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "活动审核", notes = "传入activity")
	public R getMembersByMallId(@RequestBody Activity activity) {
		Activity oldEntity = activityService.getById(activity.getId());
		Assert.notNull(oldEntity, "活动不存在");
		oldEntity.setAuditAdvice(activity.getAuditAdvice());
		oldEntity.setAuditStatus(activity.getAuditStatus());
		return R.data(activityService.updateById(oldEntity));
	}

}
