package com.hzs.member.detail.controller.api;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EAssessmentType;
import com.hzs.common.core.enums.EChangeType;
import com.hzs.common.core.enums.EOrderType;
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.security.utils.SecurityUtils;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.detail.service.ICuMemberAssessService;
import com.hzs.member.detail.vo.CuMemberAssessVO;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Description:
 * @Author: zhangjing
 * @Time: 2022/11/8 13:50
 * @Classname: CuMemberAssessController
 * @PackageName: com.hzs.member.detail.controller.manage
 */
@RestController
@RequestMapping("/api/assess")
public class ApiCuMemberAssessController extends BaseController {

    private ICuMemberAssessService cuMemberAssessService;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

    @Autowired
    public void setCuMemberAssessService(ICuMemberAssessService cuMemberAssessService) {
        this.cuMemberAssessService = cuMemberAssessService;
    }

    @Autowired
    ICuMemberBaseService cuMemberBaseService;

    /**
     * 考核明细（复购考核、分红考核）
     * 考核默认考核当月
     *
     * @return AjaxResult
     */
    @GetMapping("/assessList")
    public TableDataInfo assessList(CuMemberAssessVO cuMemberAssessVO) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (StringUtils.isNotNull(cuMemberAssessVO.getEndDate())) {
            cuMemberAssessVO.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, cuMemberAssessVO.getEndDate()));
        }
        cuMemberAssessVO.setPkMember(SecurityUtils.getUserId());
        cuMemberAssessVO.setPkCountry(pkCountry);
        Date date = DateUtils.currentDate();
        List<Integer> orderTypeList = new ArrayList<>();
        if (cuMemberAssessVO.getAssessType() == EAssessmentType.REPURCHASE_ASSESS.getValue()) {
            orderTypeList.add(EOrderType.REPURCHASE_ORDER.getValue());
        }
        //默认查询当月
        if (StringUtils.isNull(cuMemberAssessVO.getStartDate()) ||
                StringUtils.isNull(cuMemberAssessVO.getEndDate())) {
            //订单查询当前月第一天和当前日期后一天
            cuMemberAssessVO.setStartDate(DateUtils.currentMonthFirstDate(date));
            cuMemberAssessVO.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, date));
        }
        if (cuMemberAssessVO.getAssessType() == EAssessmentType.REPURCHASE_ASSESS.getValue()) {
            cuMemberAssessVO.setOrderType(EOrderType.REPURCHASE_ORDER.getValue());
        }
        List<CuMemberAssessVO> list = cuMemberAssessService.selectAssessList(cuMemberAssessVO, orderTypeList);
        List<CuMemberAssessVO> monthList = cuMemberAssessService.getMemberAssessMonthList(cuMemberAssessVO);
        if (!monthList.isEmpty() && !list.isEmpty()) {
            for (CuMemberAssessVO mo : monthList) {
                for (CuMemberAssessVO ca : list) {
                    if (null != ca.getPkAssess() && ca.getPkAssess().intValue() == mo.getPkId().intValue()) {
                        String settleMonth = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, mo.getCreationTime());
                        ca.setSettleMonth(settleMonth);
                        ca.setAssessStatus(mo.getAssessStatus());
                        break;
                    }
                }
            }
        }

        if (!list.isEmpty()) {
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            final EChangeType purAsseAdd = EChangeType.PURCHASE_ASSESSMENT_ADD;
            final EChangeType purAsseDeduct = EChangeType.PURCHASE_ASSESSMENT_DEDUCT;
            final EChangeType shareAsseAdd = EChangeType.SHARE_ASSESSMENT_ADD;
            final EChangeType shareAsseDeduct = EChangeType.SHARE_ASSESSMENT_DEDUCT;
            final EOrderType repurchaseOrder = EOrderType.REPURCHASE_ORDER;
            list.forEach(item -> {
                Integer changeType = item.getChangeType();

                if (StringUtils.isNull(changeType)) {
                    if (cuMemberAssessVO.getAssessType() == EAssessmentType.REPURCHASE_ASSESS.getValue()) {
                        changeType = 0;
                    } else if (cuMemberAssessVO.getAssessType() == EAssessmentType.SHARE_ASSESS.getValue()) {
                        changeType = 2;
                    }
                }
                Integer orderType = item.getOrderType();
                BigDecimal tradeAchieve = BigDecimal.ZERO;
                if (cuMemberAssessVO.getAssessType() == EAssessmentType.REPURCHASE_ASSESS.getValue()) {
                    if (StringUtils.isNull(item.getTradeAchieve())) {
                        tradeAchieve = item.getOrderAchieve();
                    } else {
                        tradeAchieve = item.getTradeAchieve();
                    }
                    if (pkCountry == CountryConstants.CHINA_COUNTRY) {
                        tradeAchieve = tradeAchieve.multiply(currency.getData().getInExchangeRate());
                    }
                } else if (cuMemberAssessVO.getAssessType() == EAssessmentType.SHARE_ASSESS.getValue()) {
                    if (StringUtils.isNull(item.getTradeAchieve())) {
                        tradeAchieve = item.getOrderAssAchieve();
                    } else {
                        tradeAchieve = item.getTradeAchieve();
                    }
                    // 列表显示目前没问题，不需要处理汇率
//                    if(pkCountry== CountryConstants.CHINA_COUNTRY){
//                        tradeAchieve=tradeAchieve.multiply(currency.getData().getInExchangeRate());
//                    }
                }
                if (StringUtils.isNotNull(changeType)) {
                    if (changeType == purAsseAdd.getValue()) {
                        item.setChangeType(purAsseAdd.getValue());
                        item.setTradeAchieveSign("+" + tradeAchieve);
                    } else if (changeType == purAsseDeduct.getValue()) {
                        item.setTradeAchieveSign("-" + tradeAchieve);
                    } else if (changeType == shareAsseAdd.getValue() || StringUtils.isNotNull(orderType)) {
                        item.setChangeType(shareAsseAdd.getValue());
                        item.setTradeAchieveSign("+" + tradeAchieve);
                    } else if (changeType == shareAsseDeduct.getValue()) {
                        item.setTradeAchieveSign("-" + tradeAchieve);
                    }
                } else if (StringUtils.isNotNull(orderType)) {
                    if (orderType == repurchaseOrder.getValue()) {
                        item.setChangeType(purAsseAdd.getValue());
                        item.setTradeAchieveSign("+" + tradeAchieve);
                    }
                }
            });
        }
        //list 重新排序
//        list.sort((t1, t2) -> t2.getTradeTime().compareTo(t1.getTradeTime()));
        return getDataTable(list);
    }


    /**
     * @description: 查询考核积分
     * @author: zhang jing
     * @date: 2023/3/14 17:14
     * @param: [cuMemberAssessVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @GetMapping("/assAchieve")
    public AjaxResult assAchieve(CuMemberAssessVO cuMemberAssessVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        cuMemberAssessVO.setPkMember(SecurityUtils.getUserId());
        cuMemberAssessVO.setPkCountry(pkCountry);
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(pkCountry);
        Integer assessType = Optional.ofNullable(cuMemberAssessVO.getAssessType()).orElse(0);
        BigDecimal monthSurplus = BigDecimal.ZERO;
        List<CuMemberAssessVO> list = cuMemberAssessService.getMemberAssessMonth(cuMemberAssessVO);
        if (CollectionUtil.isNotEmpty(list)) {
            for (CuMemberAssessVO ca : list) {
                monthSurplus = ca.getMonthSurplus();
            }
        }
        if (StringUtils.isNull(cuMemberAssessVO.getStartDate()) ||
                StringUtils.isNull(cuMemberAssessVO.getEndDate())) {
            cuMemberAssessVO.setStartDate(DateUtils.currentMonthFirstDate(new Date()));
            cuMemberAssessVO.setEndDate(new Date());
        }
        List<Integer> orderTypeList = new ArrayList<>();
        if (EAssessmentType.REPURCHASE_ASSESS.getValue() == assessType) {
            orderTypeList.add(EOrderType.REPURCHASE_ORDER.getValue());
            cuMemberAssessVO.setOrderTypeList(orderTypeList);
            CuMemberAssessVO order = cuMemberAssessService.getOrderAssessList(cuMemberAssessVO);
            if (StringUtils.isNotNull(order)) {
                monthSurplus = monthSurplus.add(order.getOrderAchieve());
            }
            if (pkCountry == CountryConstants.CHINA_COUNTRY) {
                monthSurplus = monthSurplus.multiply(currency.getData().getInExchangeRate());
            }
        } else if (EAssessmentType.SHARE_ASSESS.getValue() == assessType) {
            cuMemberAssessVO.setOrderTypeList(orderTypeList);
            CuMemberAssessVO order = cuMemberAssessService.getOrderAssessList(cuMemberAssessVO);
            BigDecimal orderAchieve = BigDecimal.ZERO;
            if (StringUtils.isNotNull(order)) {
                monthSurplus = monthSurplus.add(order.getOrderAssAchieve()).add(orderAchieve);
            }
        }

        return AjaxResult.success(monthSurplus);
    }


}
