package com.cyksj.web.controller.manage.account;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.*;
import com.cyksj.model.entity.*;
import com.cyksj.model.excel.ExcelPrepareAccountData;
import com.cyksj.model.manage.views.AccountView;
import com.cyksj.model.request.OrderRefundReq;
import com.cyksj.redis.RedisService;
import com.cyksj.service.mange.AccountCommonService;
import com.cyksj.service.order.OrderCommonService;
import com.cyksj.service.order.OrderRefundService;
import com.cyksj.service.user.UserBenefitsService;
import com.cyksj.web.util.EasyExcelUtils;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 项目名: yhlxj
 * 文件名: AccountTempController
 * 创建者: JavaZou
 * 创建时间:2024/10/28 17:17
 */
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/manage/account/temp")
@RestController
public class AccountTempController {
	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final AccountMapper accountMapper;

	private final AccountCommonService accountCommonService;

	private final NetflixTempAccountUserMapper netflixTempAccountUserMapper;

	private final GroupsMapper groupsMapper;

	private final GroupsRelationMapper relationMapper;

	private final OrderDonMapper orderDonMapper;

	private final GoodsDonSkuMapper skuMapper;

	private final OrderRefundService orderRefundService;

	private final RedisService redisService;

	private final OrderCommonService orderCommonService;

	private final GoodsDonMapper goodsDonMapper;

	private final UserBenefitsService userBenefitsService;

	/**
	 * 新增临时账号
	 */
	@PostMapping("/post")
	public Result<String> post(@RequestBody Account account) {
		account.setType(3);
		accountMapper.insert(account);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 编辑临时账号
	 */
	@PutMapping("/update")
	public Result<String> update(@RequestBody Account account) {
		accountMapper.updateById(account);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除
	 */
	@DeleteMapping("/delete/{id}")
	public Result<String> deletedById(@PathVariable Long id) {
		Account account = accountMapper.selectById(id);
		if (account != null && account.getType() == 3) {
			accountMapper.deleteById(id);
			netflixTempAccountUserMapper.delete(Wrappers.lambdaQuery(NetflixTempAccountUser.class)
					.eq(NetflixTempAccountUser::getAccountId, account.getId()));
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 临时账号模板
	 */
	@GetMapping("/export/temp/template")
	public void getTempTemplate(HttpServletResponse response) {
		EasyExcelUtils.createTemplateExcel(response, ExcelPrepareAccountData.class, "临时账号导入模板", "临时账号导入模板", ExcelTypeEnum.XLSX, null);
	}

	/**
	 * 批量导入临时账号
	 */
	@PostMapping("/import")
	public Result<String> batchImport(@RequestParam(defaultValue = "1") Long goodsId, MultipartFile file) throws IOException {
		if (goodsId == null) {
			throw BusinessRuntimeException.getInstance("请选择对应平台");
		}
		EasyExcel.read(file.getInputStream(), ExcelPrepareAccountData.class, new AnalysisEventListener<ExcelPrepareAccountData>() {
			@Override
			public void invoke(ExcelPrepareAccountData data, AnalysisContext analysisContext) {
				String account = data.getAccount();
				String password = data.getPassword();
				if (StrUtil.isEmpty(account) || StrUtil.isEmpty(password)) {
					return;
				}
				Account insert = new Account();
				insert.setAccount(account.trim());
				insert.setPassword(password.trim());
				insert.setGoodsId(goodsId);
				//临时账号
				insert.setType(3);
				insert.setStartTime(DateTime.now());
				if (data.getExpiryTime() != null) {
					insert.setExpiryTime(DateUtil.parse(data.getExpiryTime()));
				} else {
					insert.setExpiryTime(DateUtil.offsetMonth(DateTime.now(), 1));
				}
				insert.setBankCard(data.getBankCard());
				//辅助邮箱
				insert.setEmail(data.getSecondEmail());
				//关联邮箱
				insert.setRelateEmail(data.getRelateEmail());
				//账号是否已经添加过
				if (!insert.getAccount().contains("客服")) {
					if (accountCommonService.checkIsDupAccount(insert.getGoodsId(), insert.getAccount())) {
						return;
					}
				}
				accountMapper.insert(insert);
			}

			@Override
			public void doAfterAllAnalysed(AnalysisContext analysisContext) {

			}
		}).sheet().doRead();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 临时账号列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<AccountView>> get() {
		SearchResult<AccountView> search = beanSearcher.search(AccountView.class, MapUtils.flatBuilder(request.getParameterMap()).field(AccountView::getType, 3).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * excel奈飞退款
	 */
	@PutMapping("/refund")
	public void excelRefund(MultipartFile file) throws IOException {
		if (!file.getOriginalFilename().contains(".xls")) {
			throw BusinessRuntimeException.getInstance("请导入excel文件");
		}
		List<Object> accountList = EasyExcel.read(file.getInputStream()).sheet().headRowNumber(0).doReadSync();
		accountList.forEach(account->{
			Account dbAccount = accountMapper.selectOne(Wrappers.lambdaQuery(Account.class)
					.eq(Account::getGoodsId, 1)
					.eq(Account::getAccount, account)
					.last("limit 1"));
			if (dbAccount != null) {
				GroupsTrips groupsTrips = groupsMapper.selectById(dbAccount.getId());
				if (groupsTrips.getSkuId() != 4) {
					return;
				}
				if (groupsTrips != null) {
					//15天以内的自动退款
					List<GroupsRelation> groupsRelations = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
							.eq(GroupsRelation::getGroupsId, groupsTrips.getId())
							.gt(GroupsRelation::getExpiryTime, DateTime.now())
							.le(GroupsRelation::getExpiryTime, DateUtil.offsetDay(DateTime.now(), 15)));
					GoodsDon goodsDon = goodsDonMapper.selectById(1);
					groupsRelations.forEach(relation->{
						OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
								.eq(OrderDon::getRelationId, relation.getId())
								.eq(OrderDon::getUserId, relation.getUserId())
								.notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
								.orderByDesc(OrderDon::getId)
								.last("limit 1"));
						BigDecimal money = orderDon.getMoney();
						GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
						Integer months = sku.getMonths();
						BigDecimal single = sku.getPrice().divide(BigDecimal.valueOf(months * 30), 2, RoundingMode.DOWN);
						long betDay = DateUtil.between(DateTime.now(), relation.getExpiryTime(), DateUnit.DAY);
						BigDecimal refundMoney = single.multiply(BigDecimal.valueOf(betDay));
						//退款
						OrderRefundReq orderRefundReq = new OrderRefundReq();
						orderRefundReq.setOrderId(orderDon.getId());
						orderRefundReq.setRefundMoney(refundMoney);
						orderDon.setRefundDesc("奈飞15天内过期自动退款");
						String outNo = null;
						try {
							orderRefundReq.setRefundType("ALI_PAY");
							outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
							orderDon.setStatus(OrderDon.Status.refund);
							orderDon.setRefundMoney(orderRefundReq.getRefundMoney());
							orderDonMapper.updateById(orderDon);
							clearUserLockingRelation(relationMapper.selectById(orderDon.getRelationId()), orderDon);
							//记录退款
							orderRefundService.refundRecord(orderDon, orderRefundReq.getRefundMoney(), null, null, goodsDon, sku, outNo, orderDon.getType().getType(), null);
						} catch (Exception e) {
							orderRefundReq.setRefundType("balance");
							userBenefitsService.addUserBalance(relation.getUserId(), refundMoney, UserBalanceSourceRecord.Source.clear_valid, relation.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.clear_valid.getDesc(), true);
							//修改订单状态 为退款
							orderDon.setStatus(OrderDon.Status.refund);
							orderDon.setRefundBalance(refundMoney);
							orderDon.setRefundMoney(BigDecimal.ZERO);
							orderDonMapper.updateById(orderDon);
							orderRefundService.refundRecord(orderDon, orderRefundReq.getRefundMoney(), null, null, goodsDon, sku, outNo, "balance", null);
						}
					});

				}
			}
		});

	}

	private void clearUserLockingRelation(GroupsRelation groupsRelation, OrderDon orderDon) {
		if (groupsRelation == null) {
			return;
		}
		if (GroupsRelation.Status.locking == groupsRelation.getStatus()) {
			log.info("清理用户userId:{}未支付订单", orderDon.getUserId());
			groupsRelation.setUserId(0L);
			Long groupsId = groupsRelation.getGroupsId();
			GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
			if (groupsRelation.getNum() > groupsTrips.getNum()) {
				groupsRelation.setStatus(GroupsRelation.Status.outside);

				redisService.del(RedisService.key.GROUPS_TRIPS_OUTSIDE_RELATION.getNameFormat(groupsId, groupsRelation.getNum()));
			} else {
				groupsRelation.setStatus(GroupsRelation.Status.none);
			}
			groupsRelation.setYhsId(0l);
			relationMapper.updateById(groupsRelation);
			orderCommonService.delRelation(groupsRelation);
		}
	}
}
