package com.hzs.sale.deliver.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
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.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.account.CuMemberTrade;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.system.config.BdAccount;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.member.account.IMemberTradeServiceApi;
import com.hzs.sale.deliver.param.*;
import com.hzs.sale.deliver.service.ISaDeliverBusinessService;
import com.hzs.sale.deliver.vo.DeliverSecondDataAccountVO;
import com.hzs.sale.deliver.vo.DeliverSecondDataDetailVO;
import com.hzs.sale.deliver.vo.DeliverSecondDataVO;
import com.hzs.sale.deliver.vo.DeliverSecondVO;
import com.hzs.sale.order.service.ISaOrderService;
import com.hzs.sale.util.OrderUtil;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.config.IAccountServiceApi;
import com.hzs.system.sys.IUserServiceApi;
import com.hzs.system.sys.dto.UserAuthorityDTO;
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.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 发货清单二次发货控制器
 * @Author: jiang chao
 * @Time: 2023/5/5 15:30
 * @Classname: SaDeliverSecondController
 * @PackageName: com.hzs.sale.deliver.controller.manage
 */
@RestController
@RequestMapping("/manage/deliver-second")
public class SaDeliverSecondController extends BaseController {

    @Autowired
    private ISaOrderService iSaOrderService;
    @Autowired
    private ISaDeliverBusinessService iSaDeliverBusinessService;
    @Autowired
    private UserTokenService userTokenService;

    @DubboReference
    private IAreaServiceApi iAreaServiceApi;
    @DubboReference
    private IMemberTradeServiceApi iMemberTradeServiceApi;
    @DubboReference
    private IAccountServiceApi iAccountServiceApi;
    @DubboReference
    private IUserServiceApi iUserServiceApi;

    /**
     * 列表
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.DELIVER_ORDER, business = EOperationBusiness.DELIVER_SECOND, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(DeliverSecondParam param) {
        param.setCreationTime(DateUtils.handTimeStartAndEnd(param.getCreationTime()));
        param.setPayTime(DateUtils.handTimeStartAndEnd(param.getPayTime()));

        Integer pkCountry = SecurityUtils.getPkCountry();

        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        param.setAreaScopeList(userAuthorityDTO.getRoleAreaScopeList());
        param.setVertexIdList(userAuthorityDTO.getVertexIdList());
        param.setTeamList(userAuthorityDTO.getUserTeamList());

        startPage();
        List<DeliverSecondVO> resultList = iSaOrderService.secondList(param, pkCountry);

        // 当查询有数据才进行处理
        if (resultList.size() > 0) {
            // 获取行政区划map
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();

            for (DeliverSecondVO deliverSecond : resultList) {
                // 省市区处理
                OrderUtil.handleOrderAddress(areaMap, deliverSecond);

                if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                    if (null != deliverSecond.getInExchangeRate()) {
                        deliverSecond.setOrderAchieveRmb(deliverSecond.getOrderAchieve().multiply(deliverSecond.getInExchangeRate()));
                    }
                }
            }
        }

        return getDataTable(resultList);
    }

    /**
     * 查看明细
     *
     * @param pkId 订单ID
     * @return
     */
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Long pkId) {
        // 查询订单以及详情
        SaOrderExt saOrderExt = iSaOrderService.queryOrderListByIdList(Collections.singletonList(pkId), SecurityUtils.getPkCountry()).get(0);
        return AjaxResult.success(saOrderExt.getOrderItemsExtList());
    }

    /**
     * 二次发货数据
     *
     * @param pkId 订单ID
     * @return
     */
    @GetMapping("/data")
    public AjaxResult data(@RequestParam Long pkId) {
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 查询订单以及详情
        SaOrderExt saOrderExt = iSaOrderService.queryOrderListByIdList(Collections.singletonList(pkId), pkCountry).get(0);

        // 返回数据
        DeliverSecondDataVO deliverSecondData = BeanUtil.copyProperties(saOrderExt, DeliverSecondDataVO.class);
        deliverSecondData.setDetailList(BeanUtil.copyToList(saOrderExt.getOrderItemsExtList(), DeliverSecondDataDetailVO.class));

        if (EOrderPayType.WALLET.getValue() == saOrderExt.getPayType()) {
            // 钱包支付，查询支付方式
            List<CuMemberTrade> tradeList = iMemberTradeServiceApi.querySourceCodeLastTrade(saOrderExt.getPkCreator(), saOrderExt.getOrderCode(), ETradeClassify.CONSUME.getValue()).getData();
            // 获取对应的币种信息
            Map<Integer, BdAccount> accountMap = iAccountServiceApi.getAccountMap(tradeList.stream().map(CuMemberTrade::getPkAccount).collect(Collectors.toList())).getData();

            // 处理支付明细
            List<DeliverSecondDataAccountVO> accountList = new ArrayList<>(tradeList.size());
            for (CuMemberTrade cuMemberTrade : tradeList) {
                Integer pkTransactionKey = cuMemberTrade.getPkAccount();
                if (null != accountMap.get(cuMemberTrade.getPkAccount())) {
                    pkTransactionKey = accountMap.get(cuMemberTrade.getPkAccount()).getPkTransactionKey();
                }

                accountList.add(DeliverSecondDataAccountVO.builder()
                        .pkAccount(pkTransactionKey)
                        .amount(cuMemberTrade.getTradeAmount())
                        .build());
            }
            deliverSecondData.setAccountList(accountList);
        } else {
            // 在线支付
            deliverSecondData.setAccountList(Collections.singletonList(
                    DeliverSecondDataAccountVO.builder()
                            .pkAccountVal("在线支付")
                            .amount(saOrderExt.getOrderAmount().add(saOrderExt.getPostage()))
                            .build()
            ));
        }

        // 获取行政区划map
        Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();
        OrderUtil.handleOrderAddress(areaMap, deliverSecondData);

        return AjaxResult.success(deliverSecondData);
    }

    /**
     * 二次发货提交
     *
     * @param param 二次发货提交参数
     * @return
     */
    @Log(module = EOperationModule.DELIVER_ORDER, business = EOperationBusiness.DELIVER_SECOND, method = EOperationMethod.SUBMIT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody DeliverSecondSubmitParam param) {
        if (null == param.getSignType() || CollectionUtil.isEmpty(param.getUserIdList()) || null == param.getDataParam()) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        DeliverSecondDataParam dataParam = param.getDataParam();
        if (null == dataParam.getPkId() || StringUtils.isAnyEmpty(dataParam.getRecName(), dataParam.getRecPhone(), dataParam.getRecAddress())
                || null == dataParam.getRecProvince() || null == dataParam.getRecCity()
                || CollectionUtil.isEmpty(dataParam.getProductList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        // 校验计算奖项
        if (EYesNo.YES.getIntValue() == dataParam.getBonusFlag() && CollectionUtil.isEmpty(dataParam.getBonusList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        // 校验产品明细
        for (DeliverSecondSubmitProductParam productParam : dataParam.getProductList()) {
            if (null == productParam.getPkProduct() || null == productParam.getQuantity()
                    || StringUtils.isAnyEmpty(productParam.getSpecsNameId(), productParam.getSpecsName())) {
                // 缺少参数
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
        }

        // 计算价格
        BigDecimal price = null != dataParam.getPostage() ? dataParam.getPostage() : BigDecimal.ZERO;
        for (DeliverSecondSubmitProductParam productParam : dataParam.getProductList()) {
            price = price.add(null != productParam.getPrice() ? productParam.getPrice() : BigDecimal.ZERO);
        }
        if (price.compareTo(BigDecimal.ZERO) > 0) {
            // 订单有扣款金额，需要有扣款配置
            if (CollectionUtil.isEmpty(dataParam.getAccountList())) {
                // 扣款不能为空
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_NOT_NULL));
            }

            // 是否比例为0
            boolean zeroRatio = false;
            // 校验扣除比例
            BigDecimal deductRatio = BigDecimal.ZERO;
            for (DeliverSecondSubmitAccountParam accountParam : dataParam.getAccountList()) {
                if (null == accountParam.getPkAccount() || null == accountParam.getDeductRatio()) {
                    // 扣款不能为空
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_NOT_NULL));
                }

                deductRatio = deductRatio.add(accountParam.getDeductRatio());
                if (accountParam.getDeductRatio().compareTo(BigDecimal.ZERO) == 0) {
                    zeroRatio = true;
                }
            }
            if (deductRatio.compareTo(new BigDecimal("100")) > 0) {
                // 扣款比例不能大于 100%
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_RATIO_NOT_MORE_THAN) + "100%");
            }
            if (deductRatio.compareTo(new BigDecimal("100")) < 0 && !zeroRatio) {
                // 配置扣款比例不足 100%
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_RATIO_NOT_ENOUGH) + "100%");
            }
        }

        String str = iSaDeliverBusinessService.secondDeliverSubmit(param, userTokenService.getLoginUser());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.success(str);
    }

}
