package com.hzs.activity.tree.controller.api;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.activity.base.service.IAcGoalMemberConfigService;
import com.hzs.activity.tree.service.ISaTreeOrderService;
import com.hzs.activity.tree.vo.SaTreeOrderVO;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.constant.msg.FinanceMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EAccount;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.activity.base.AcGoalMemberConfig;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.system.config.BdAccount;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.member.account.IMemberAccountServiceApi;
import com.hzs.member.account.IMemberTradeServiceApi;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.dto.MemberBalanceDTO;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.system.config.IAccountServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 * 沙棘树活动购买订单表 前端控制器
 * </p>
 *
 * @author zhangjing
 * @since 2023-06-16
 */
@RestController
@RequestMapping("/api/sa-tree-order")
public class SaTreeOrderController extends BaseController {

    @Autowired
    private ISaTreeOrderService iSaTreeOrderService;
    @DubboReference
    private IMemberServiceApi iMemberServiceApi;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @DubboReference
    private IAccountServiceApi iAccountServiceApi;
    @DubboReference
    private IMemberTradeServiceApi iMemberTradeServiceApi;
    @DubboReference
    private IMemberAccountServiceApi iMemberAccountServiceApi;
    @Autowired
    private IAcGoalMemberConfigService iAcGoalMemberConfigService;


    /**
     * @description: 查询沙棘生效活动
     * @author: zhang jing
     * @date: 2023/6/17 11:00
     * @param: []
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @GetMapping("/queryTreeActivity")
    public AjaxResult queryTreeActivity() {
        return AjaxResult.success(queryTree());
    }

    private SaTreeOrderVO queryTree() {
        Long userId = SecurityUtils.getUserId();
        R<CuMember> cuMember = iMemberServiceApi.getMember(userId);
        SaTreeOrderVO saTreeOrderVO = new SaTreeOrderVO();
        saTreeOrderVO.setPkAwards(cuMember.getData().getPkAwards());
        saTreeOrderVO.setPkCountry(SecurityUtils.getPkCountry());
        saTreeOrderVO = iSaTreeOrderService.queryTreeActivity(saTreeOrderVO);
        if (null != saTreeOrderVO) {
            QueryWrapper<AcGoalMemberConfig> queryWrapper = new QueryWrapper();
            queryWrapper.eq("PK_BASE_ID", saTreeOrderVO.getPkBaseId());
            List<AcGoalMemberConfig> list = iAcGoalMemberConfigService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                for (AcGoalMemberConfig ag : list) {
                    if (ag.getMemberType() == 1 && ag.getPkLevel().equals(cuMember.getData().getPkSettleGrade())) {
                        return saTreeOrderVO;
                    }
                    if (ag.getMemberType() == 2 && ag.getPkLevel().equals(cuMember.getData().getPkAwards())) {
                        return saTreeOrderVO;
                    }
                    if (ag.getMemberType() == 3 && ag.getPkLevel().equals(cuMember.getData().getRegisterAuthority())) {
                        return saTreeOrderVO;
                    }
                }
            }
        }
        return null;
    }

    /**
     * @description: 查询沙棘树扣款账户信息
     * @author: zhang jing
     * @date: 2023/7/15 11:31
     * @param: [saTreeOrderVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @PostMapping("/deductionAccount")
    public AjaxResult deductionAccount(@RequestBody SaTreeOrderVO saTreeOrderVO) {
        SaTreeOrderVO treeAct = queryTree();
        Long userId = SecurityUtils.getUserId();
        saTreeOrderVO.setPkMember(userId);
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<CuMember> cuMember = iMemberServiceApi.getMember(userId);
        List<Long> pkMemberList = new ArrayList<>();
        pkMemberList.add(cuMember.getData().getPkId());
        R<List<CuMemberAccount>> account = iMemberAccountServiceApi.queryCuMemberAccountByPkMembers(pkMemberList);
        if (CollectionUtil.isNotEmpty(account.getData())) {
            saTreeOrderVO.setConsumeBalance(account.getData().get(0).getAccount1());
        }
        //订单金额
        BigDecimal orderAmount = treeAct.getPrice().multiply(BigDecimal.valueOf(saTreeOrderVO.getShopQuantity()));
        saTreeOrderVO.setOrderAmount(orderAmount);
        //接口查询金额是否足够
        R<List<BdAccount>> acccountList = iAccountServiceApi.queryAccountByType(null, pkCountry);
        BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
        memberAmountDTO.setPkMember(userId);
        memberAmountDTO.setTradeAmount(orderAmount);
        memberAmountDTOList.add(memberAmountDTO);
        businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
        businessCommissionDTO.setPkCountry(pkCountry);
        Integer consume = 0; //消费
        Integer bonus = 0; //奖金
        Integer cash = 0; // 现金
        Integer consumeKey = 0; //消费
        Integer bonusKey = 0; //奖金
        Integer cashKey = 0; // 现金
        BigDecimal consumeBalance = BigDecimal.ZERO; //扣除消费
        BigDecimal bonusBalance = BigDecimal.ZERO; //扣除奖金

        if (CollectionUtil.isNotEmpty(acccountList.getData())) {
            for (BdAccount acc : acccountList.getData()) {
                if (acc.getFieldValue() == EAccount.CONSUME.getValue()) {
                    consume = acc.getPkId();
                    consumeKey = acc.getPkTransactionKey();
                }
                if (acc.getFieldValue() == EAccount.BONUS.getValue()) {
                    bonus = acc.getPkId();
                    bonusKey = acc.getPkTransactionKey();
                }
            }
            saTreeOrderVO.setConsume(consumeKey);

            //接口查询金额是否足够
            businessCommissionDTO.setPkAccount(consume);
            List<MemberBalanceDTO> memberBalanceList = iMemberTradeServiceApi.selectBalanceNotEnoughMember(businessCommissionDTO);
            if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                consumeBalance = memberBalanceList.get(0).getBanlance();
                orderAmount = orderAmount.subtract(consumeBalance);
                saTreeOrderVO.setConsumeDeduct(consumeBalance);
                saTreeOrderVO.setBonusDeduct(orderAmount);
                saTreeOrderVO.setBonusBalance(account.getData().get(0).getConsumeAccount4());

                businessCommissionDTO.setPkAccount(bonus);
                memberAmountDTO.setTradeAmount(orderAmount);
                memberAmountDTOList.clear();
                memberAmountDTOList.add(memberAmountDTO);
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                saTreeOrderVO.setBonus(bonusKey);
                memberBalanceList = iMemberTradeServiceApi.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    saTreeOrderVO.setCash(cashKey);
                    bonusBalance = memberBalanceList.get(0).getBanlance();
                    saTreeOrderVO.setBonusDeduct(bonusBalance);
                    orderAmount = orderAmount.subtract(bonusBalance);
                    saTreeOrderVO.setCashDeduct(orderAmount);
                    saTreeOrderVO.setCashBalance(account.getData().get(0).getAccount2());
                    businessCommissionDTO.setPkAccount(cash);
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                }
            } else {
                saTreeOrderVO.setConsumeDeduct(orderAmount);
            }
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT));
        }

        // 查询翻译数据
        Map<Integer, String> map = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_AWARD);

        String pkAwardVal = map.get(iMemberServiceApi.getAwardsTranslateValue(SecurityUtils.getPkCountry(), cuMember.getData().getPkAwards()));
        if (saTreeOrderVO.getShopQuantity() < saTreeOrderVO.getQuantity()) {
            AjaxResult.error(pkAwardVal + ConfigMsgConstants.TREE_COUNT_NOT_NULL + saTreeOrderVO.getQuantity());
        }
        saTreeOrderVO.setPkCreator(userId);
        saTreeOrderVO.setPkMember(userId);
        saTreeOrderVO.setPkCountry(pkCountry);
        return AjaxResult.success(saTreeOrderVO);
    }

    /**
     * @description: 购买沙棘树
     * @author: zhang jing
     * @date: 2023/6/17 11:16
     * @param: [saTreeOrderVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @PostMapping("/shoppingTree")
    public AjaxResult shoppingTree(@RequestBody SaTreeOrderVO saTreeOrderVO) {

        SaTreeOrderVO treeAct = queryTree();
        Long userId = SecurityUtils.getUserId();
        saTreeOrderVO.setPkMember(userId);
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<CuMember> cuMember = iMemberServiceApi.getMember(userId);
        //校验支付密码
        String payPwd = cuMember.getData().getPayPwd();
        if (StringUtils.isEmpty(payPwd) || !SecurityUtils.matchesPassword(saTreeOrderVO.getPayPwd(), payPwd)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.PAYMENT_PASSWORD_ERROR));
        }
        //订单金额
        BigDecimal orderAmount = treeAct.getPrice().multiply(BigDecimal.valueOf(saTreeOrderVO.getShopQuantity()));
        saTreeOrderVO.setOrderAmount(orderAmount);
        //接口查询金额是否足够
        R<List<BdAccount>> acccountList = iAccountServiceApi.queryAccountByType(null, pkCountry);
        BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
        memberAmountDTO.setPkMember(userId);
        memberAmountDTO.setTradeAmount(orderAmount);
        memberAmountDTOList.add(memberAmountDTO);
        businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
        businessCommissionDTO.setPkCountry(pkCountry);
        Integer consume = 0; //消费
        Integer bonus = 0; //奖金
        Integer cash = 0; // 现金
        BigDecimal consumeBalance = BigDecimal.ZERO; //扣除消费
        BigDecimal bonusBalance = BigDecimal.ZERO; //扣除奖金
        BigDecimal cashBalance = BigDecimal.ZERO;//扣除现金

        if (CollectionUtil.isNotEmpty(acccountList.getData())) {
            for (BdAccount acc : acccountList.getData()) {
                if (acc.getFieldValue() == EAccount.CONSUME.getValue()) {
                    consume = acc.getPkId();
                }
                if (acc.getFieldValue() == EAccount.BONUS.getValue()) {
                    bonus = acc.getPkId();
                }
            }
            saTreeOrderVO.setConsume(consume);
            saTreeOrderVO.setBonus(bonus);
            saTreeOrderVO.setCash(cash);
            //接口查询金额是否足够
            businessCommissionDTO.setPkAccount(consume);
            consumeBalance = orderAmount;
            List<MemberBalanceDTO> memberBalanceList = iMemberTradeServiceApi.selectBalanceNotEnoughMember(businessCommissionDTO);
            if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                consumeBalance = memberBalanceList.get(0).getBanlance();
                orderAmount = orderAmount.subtract(consumeBalance);
                bonusBalance = orderAmount;
                businessCommissionDTO.setPkAccount(bonus);
                memberAmountDTO.setTradeAmount(orderAmount);
                memberAmountDTOList.clear();
                memberAmountDTOList.add(memberAmountDTO);
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                memberBalanceList = iMemberTradeServiceApi.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    bonusBalance = memberBalanceList.get(0).getBanlance();
                    orderAmount = orderAmount.subtract(bonusBalance);
                    cashBalance = orderAmount;
                    businessCommissionDTO.setPkAccount(cash);
                    memberAmountDTO.setTradeAmount(orderAmount);
                    memberAmountDTOList.clear();
                    memberAmountDTOList.add(memberAmountDTO);
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                    memberBalanceList = iMemberTradeServiceApi.selectBalanceNotEnoughMember(businessCommissionDTO);
                    if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList);
                    }
                }
            }
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT));
        }

        // 查询翻译数据
        Map<Integer, String> map = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_AWARD);

        String pkAwardVal = map.get(iMemberServiceApi.getAwardsTranslateValue(SecurityUtils.getPkCountry(), cuMember.getData().getPkAwards()));
        if (saTreeOrderVO.getShopQuantity() < saTreeOrderVO.getQuantity()) {
            AjaxResult.error(pkAwardVal + ConfigMsgConstants.TREE_COUNT_NOT_NULL + saTreeOrderVO.getQuantity());
        }
        saTreeOrderVO.setPkCreator(userId);
        saTreeOrderVO.setPkMember(userId);
        saTreeOrderVO.setPkCountry(pkCountry);
        return AjaxResult.success(iSaTreeOrderService.shoppingTree(saTreeOrderVO, consumeBalance, bonusBalance, cashBalance));
    }

//    /**
//     * @description: 生成购买记录
//     * @author: zhang jing
//     * @date: 2023/6/21 10:08
//     * @param: [saTreeOrderVO]
//     * @return: com.hzs.common.core.web.domain.AjaxResult
//     **/
//    @PostMapping("/orderTree")
//    public AjaxResult orderTree(SaTreeOrderVO saTreeOrderVO){
//        // 查询翻译数据
//        Map<Integer, String> map = iTransactionCommonService.exportEnumTransaction( EnumsPrefixConstants.KEY_AWARD);
//        Long userId = SecurityUtils.getUserId();
//        R<CuMember> cuMember = iMemberServiceApi.getMember(userId);
//        String pkAwardVal=map.get(iMemberServiceApi.getAwardsTranslateValue(SecurityUtils.getPkCountry(),cuMember.getData().getPkAwards())) ;
//        if(null==saTreeOrderVO.getShopQuantity()
//                ||saTreeOrderVO.getShopQuantity()<saTreeOrderVO.getQuantity()
//                ||null==saTreeOrderVO.getQuantity()){
//            AjaxResult.error(pkAwardVal+ConfigMsgConstants.TREE_COUNT_NOT_NULL+saTreeOrderVO.getQuantity());
//        }
//        saTreeOrderVO.setPkCreator(userId);
//        saTreeOrderVO.setPkMember(userId);
//        saTreeOrderVO.setPkCountry(SecurityUtils.getPkCountry());
//        return AjaxResult.success(iSaTreeOrderService.shoppingTree(saTreeOrderVO));
//    }

}
