package com.hzs.sale.ticket.controller.api;

import cn.hutool.core.bean.BeanUtil;
import com.hzs.activity.ticket.service.IAcTicketService;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.HttpStatus;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.reflect.ReflectUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.activity.ticket.AcTicket;
import com.hzs.common.domain.member.ext.CuMemberAccountExt;
import com.hzs.common.domain.sale.ticket.ext.SaTicketExt;
import com.hzs.common.domain.sale.ticket.SaBuyTicket;
import com.hzs.common.domain.sale.ticket.SaTicket;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.sale.order.controller.ParentOrderController;
import com.hzs.sale.order.param.OrderParam;
import com.hzs.sale.ticket.param.BuyTicketParam;
import com.hzs.sale.ticket.param.SaTicketParam;
import com.hzs.sale.ticket.service.ISaBuyTicketService;
import com.hzs.sale.ticket.service.ISaTicketService;
import com.hzs.sale.ticket.vo.AcTicketVO;
import com.hzs.sale.ticket.vo.SaTicketVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 门票主表 前端控制器
 */
@RestController
@RequestMapping("/api/ticket")
public class ApiSaTicketController extends ParentOrderController {

    @Autowired
    private ISaTicketService saTicketService;
    @Autowired
    private ISaBuyTicketService saBuyTicketService;
    @Autowired
    private IAcTicketService acTicketService;

    /**
     * 支付购买订单
     *
     * @param orderParam 订单参数
     */
    @RepeatSubmitSimple
    @PostMapping("/pay-ticket")
    public AjaxResult paySaTicket(@RequestBody OrderParam orderParam) {
        if (orderParam.getPayPwd() == null || orderParam.getPkTicket() == null ||
                orderParam.getTicketParamList() == null || orderParam.getTicketParamList().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        for (BuyTicketParam buyTicketParam : orderParam.getTicketParamList()) {
            if (validateFieldNotNull(buyTicketParam, buyTicketParam.getValidConfirmField())) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
            }
        }
        initSecurityOrderParam(orderParam);
        // 查询报单会员账户信息
        AjaxResult result = validateMemberAccount(orderParam);
        if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return result;
        }
        // 查询 门票活动价格
        AcTicket acTicket = acTicketService.queryAcTicketByPkId(orderParam.getPkTicket());
        if (acTicket == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.AC_TICKET_NOT_EXISTS));
        }
        // 验证已经销售 门票数量
        Integer number = saTicketService.queryBuySaTicketNum(orderParam.getPkTicket());
        if (number != null && acTicket.getQuantity() < number + orderParam.getTicketParamList().size()) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.NOT_CHECK_AC_ACTIVITY));
        }
        // 校验是否超过限购数量
        if (orderParam.getTicketParamList().size() > acTicket.getLimitQuantity()) {
            return AjaxResult.error("当前活动门票每人限购【" + acTicket.getLimitQuantity() + "】张");
        } else {
            int buyCount = saTicketService.sumQuantity(acTicket.getPkId(), SecurityUtils.getUserId());
            if (buyCount + orderParam.getTicketParamList().size() > acTicket.getLimitQuantity()) {
                return AjaxResult.error("当前活动门票每人限购【" + acTicket.getLimitQuantity() + "】张");
            }
        }

        // 计算价格
        BigDecimal payMoney = ComputeUtil.computeMultiply(acTicket.getPayMoney(), BigDecimal.valueOf(orderParam.getTicketParamList().size()));
        CuMemberAccountExt cuMemberAccountExt = (CuMemberAccountExt) result.get(AjaxResult.DATA_TAG);
        saTicketService.queryOrderSpendDetails(cuMemberAccountExt, payMoney, orderParam.getCenterCodeId());
        if (cuMemberAccountExt.getIsPayment()) {
            // 开始支付 扣款
            return AjaxResult.success(saTicketService.paySaTicket(orderParam, acTicket.getPayMoney(), cuMemberAccountExt, null));
        } else {
            if (StringUtils.isEmpty(cuMemberAccountExt.getErrorMsg())) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_BALANCE_NOT_PAY));
            } else {
                return AjaxResult.error(cuMemberAccountExt.getErrorMsg());
            }
        }
    }

    /**
     * 支付购买订单
     *
     * @param orderParam 订单参数
     */
    @PostMapping("/cancel-pay-ticket")
    public AjaxResult cancelPaySaTicket(@RequestBody OrderParam orderParam) {
        if (orderParam.getOrderCode() == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        // 查询门票
        SaTicket saTicket = saTicketService.querySaTicketByParam(orderParam, SecurityUtils.getUserId());
        if (saTicket == null || DateUtils.compareDateBefore(saTicket.getCreationTime(), DateUtils.currentDate())) {
            return AjaxResult.error("只能撤销个人当天购买的门票！");
        }
        saTicketService.cancelSaTicket(saTicket, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    /**
     * 支付购买订单
     *
     * @param orderParam 订单参数
     */
    @PostMapping("/pay-online")
    public AjaxResult paySaTicketOnline(@RequestBody OrderParam orderParam) {
        if (orderParam.getPkTicket() == null || orderParam.getTicketParamList() == null || orderParam.getTicketParamList().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        for (BuyTicketParam buyTicketParam : orderParam.getTicketParamList()) {
            if (validateFieldNotNull(buyTicketParam, buyTicketParam.getValidConfirmField())) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
            }
        }
        initSecurityOrderParam(orderParam);
        // 查询 门票活动价格
        AcTicket acTicket = acTicketService.queryAcTicketByPkId(orderParam.getPkTicket());
        if (acTicket == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        // 验证已经销售 门票数量
        Integer number = saTicketService.queryBuySaTicketNum(orderParam.getPkTicket());
        if (number != null && acTicket.getQuantity() < number + orderParam.getTicketParamList().size()) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.NOT_CHECK_AC_ACTIVITY));
        }
        // 校验是否超过限购数量
        if (orderParam.getTicketParamList().size() > acTicket.getLimitQuantity()) {
            return AjaxResult.error("当前活动门票每人限购【" + acTicket.getLimitQuantity() + "】张");
        } else {
            int buyCount = saTicketService.sumQuantity(acTicket.getPkId(), SecurityUtils.getUserId());
            if (buyCount + orderParam.getTicketParamList().size() > acTicket.getLimitQuantity()) {
                return AjaxResult.error("当前活动门票每人限购【" + acTicket.getLimitQuantity() + "】张");
            }
        }
        return AjaxResult.success(saTicketService.querySaTicketOnlineOrderCode(orderParam, acTicket.getPayMoney()));
    }

    /**
     * 支付购买订单
     *
     * @param orderParam 订单参数
     */
    @PostMapping("/pay-back")
    public AjaxResult payBackSaTicketOnline(@RequestBody OrderParam orderParam) {
        saTicketService.paySaTicketOnlineOrderCode(SecurityUtils.getUserId(), orderParam.getOrderCode());
        return AjaxResult.success();
    }

    /**
     * 会员前台查询门票活动列表
     */
    @GetMapping("/query")
    public TableDataInfo querySaTick() {
        SaTicketParam saTicketParam = SaTicketParam.builder()
                .pkMember(SecurityUtils.getUserId())
                .build();
        List<SaTicketExt> ticketExtList = saTicketService.querySaTicketByParam(saTicketParam);
        List<SaTicketVO> ticketVOList = new ArrayList<>();
        for (SaTicketExt saTicketExt : ticketExtList) {
            for (SaBuyTicket saBuyTicket : saTicketExt.getSaBuyTicketList()) {
                SaTicketVO saTicketVO = SaTicketVO.builder()
                        .pkId(saBuyTicket.getPkId())
                        .creationTime(saTicketExt.getCreationTime())
                        .memberCode(saTicketExt.getMemberCode())
                        .memberName(saTicketExt.getMemberName())
                        .actName(saTicketExt.getActName())
                        .orderCode(saTicketExt.getOrderCode())
                        .orderAmount(saTicketExt.getOrderAmount())
                        .price(saTicketExt.getPrice())
                        .quantity(saTicketExt.getQuantity())
                        .buyName(saBuyTicket.getBuyName())
                        .phone(saBuyTicket.getPhone())
                        .idCard(saBuyTicket.getIdCard())
                        .sex(saBuyTicket.getSex())
                        .clothSize(saBuyTicket.getClothSize())
                        .cohabitant(saBuyTicket.getCohabitant())
                        .emergencyPhone(saBuyTicket.getEmergencyPhone())
                        .build();
                ticketVOList.add(saTicketVO);
            }
        }
        return getDataTable(ticketVOList);
    }

    /**
     * 支付购买订单
     *
     * @param ticketParam 订单参数
     */
    @PostMapping("/update-ticket")
    public AjaxResult update(@RequestBody BuyTicketParam ticketParam) {
        List<BuyTicketParam> ticketParamList = new ArrayList<>();
        ticketParamList.add(ticketParam);
        for (BuyTicketParam buyTicketParam : ticketParamList) {
            if (buyTicketParam.getPkId() == null) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
            }
            SaBuyTicket saBuyTicket = saBuyTicketService.querySaBuyTicket(SecurityUtils.getUserId(), buyTicketParam.getPkId());
            if (saBuyTicket == null || DateUtils.compareDateBefore(saBuyTicket.getCreationTime(), DateUtils.currentDate())) {
                return AjaxResult.error("只能修改个人当天购买的门票！");
            }
        }
        if (!saTicketService.updateSaTicketByParam(SecurityUtils.getUserId(), ticketParamList)) {
            return AjaxResult.error("改手机号已经购买过门票，请重新输入手机号！");
        }
        return AjaxResult.success();
    }

    /**
     * 会员前台查询门票活动列表
     **/
    @GetMapping("/query-ac")
    public TableDataInfo queryAcTick() {
        List<AcTicket> acTicketList = acTicketService.queryAcTicketByDate(new Date(), SecurityUtils.getPkCountry(), SecurityUtils.getSystemType());
        List<AcTicketVO> acTicketVOList = new ArrayList<>();
        for (AcTicket acTicket : acTicketList) {
            AcTicketVO acTicketVO = BeanUtil.copyProperties(acTicket, AcTicketVO.class);
            acTicketVOList.add(acTicketVO);
        }
        return getDataTable(acTicketVOList);
    }

    /**
     * 验证字段是否必输
     */
    private boolean validateFieldNotNull(BuyTicketParam buyTicketParam, List<String> fieldList) {
        return fieldList.stream().anyMatch(field -> {
            Object obj = ReflectUtils.invokeGetter(buyTicketParam, field);
            return obj == null || "".equals(obj);
        });
    }
}
