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.*;
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.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 javax.validation.Valid;
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;

@RestController
@RequestMapping("/api/assess")
public class ApiCuMemberAssessController extends BaseController {

    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

    @Autowired
    private ICuMemberAssessService cuMemberAssessService;

    /**
     * 考核明细（复购考核、分红考核）
     * 考核默认考核当月
     *
     * @return AjaxResult
     */
    @GetMapping("/assessList")
    public TableDataInfo assessList(@Valid CuMemberAssessVO cuMemberAssessVO) {
        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.NO_ASSESSMENT.getValue()) {
            cuMemberAssessVO.setAssessType(EAssessmentType.REPURCHASE_ASSESS.getValue());
        }
        if (cuMemberAssessVO.getAssessType() == EAssessmentType.REPURCHASE_ASSESS.getValue()) {
            // 复购考核
            orderTypeList.add(EOrderType.REPURCHASE_ORDER.getValue());
            orderTypeList.add(EOrderType.MALL_ORDER.getValue());
        }

        //默认查询当月
        if (StringUtils.isNull(cuMemberAssessVO.getStartDate()) ||
                StringUtils.isNull(cuMemberAssessVO.getEndDate())) {
            //订单查询当前月第一天和当前日期后一天
            cuMemberAssessVO.setStartDate(DateUtils.currentMonthFirstDate(date));
            cuMemberAssessVO.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, date));
            cuMemberAssessVO.setStartTradeTime(DateUtils.currentMonthFirstDate(date));
            cuMemberAssessVO.setEndDateTradeTime(DateUtils.afterDate(1, ChronoUnit.DAYS, date));
        } else if (DateUtils.compareDateBefore(DateUtils.currentMonthFirstDate(date), cuMemberAssessVO.getEndDate())) {
            //只有查询日期包含当前月，才会查询当前月的订单
            cuMemberAssessVO.setStartTradeTime(DateUtils.currentMonthFirstDate(date));
            cuMemberAssessVO.setEndDateTradeTime(DateUtils.afterDate(1, ChronoUnit.DAYS, date));
        }

        List<CuMemberAssessVO> monthList = cuMemberAssessService.getMemberAssessMonthList(cuMemberAssessVO);

        startPage();
        List<CuMemberAssessVO> list = cuMemberAssessService.selectAssessList(cuMemberAssessVO, orderTypeList);
        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);
                        if (mo.getAssessStatus() != null && mo.getAssessStatus() == EAssessStatus.EXEMPT_PASS.getValue()) {
                            ca.setAssessStatus(EAssessStatus.EXAMINE_PASS.getValue());
                        } else {
                            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;
            list.forEach(item -> {
                // 交易类型
                Integer changeType = item.getChangeType();
                // 订单类型
                Integer orderType = item.getOrderType();
                // 交易额度
                BigDecimal tradeAchieve = BigDecimal.ZERO;

                if (cuMemberAssessVO.getAssessType() == EAssessmentType.REPURCHASE_ASSESS.getValue()) {
                    // 复购考核
                    if (StringUtils.isNull(changeType)) {
                        changeType = purAsseAdd.getValue();
                    }
                    if (StringUtils.isNull(item.getTradeAchieve())) {
                        tradeAchieve = item.getOrderAchieve();
                    } else {
                        tradeAchieve = item.getTradeAchieve();
                    }
                    if (pkCountry.equals(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 == EOrderType.REPURCHASE_ORDER.getValue()) {
                        // 复购订单
                        item.setChangeType(purAsseAdd.getValue());
                        item.setTradeAchieveSign("+" + tradeAchieve);
                    }
                }
            });
        }
        List<CuMemberAssessVO> listNew = new ArrayList<>();
        if (cuMemberAssessVO.getAssessStatus() != null ||
                cuMemberAssessVO.getChangeType() != null) {
            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(itm -> {
                    if (cuMemberAssessVO.getAssessStatus() != null &&
                            itm.getAssessStatus() != null) {
                        if (itm.getAssessStatus().equals(cuMemberAssessVO.getAssessStatus())) {
                            listNew.add(itm);
                        }
                    }
                    if (cuMemberAssessVO.getChangeType() != null) {
                        if (itm.getChangeType().equals(cuMemberAssessVO.getChangeType())) {
                            listNew.add(itm);
                        }
                    }
                });
            }
        }
        TableDataInfo tableDataInfo = getDataTable(list);
        if (cuMemberAssessVO.getChangeType() != null || cuMemberAssessVO.getAssessStatus() != null
                || CollectionUtil.isNotEmpty(listNew)) {
            tableDataInfo.setRows(listNew);
        } else {
            tableDataInfo.setRows(list);
        }
        return tableDataInfo;
    }


    /**
     * 查询考核积分
     **/
    @GetMapping("/assAchieve")
    public AjaxResult assAchieve(CuMemberAssessVO cuMemberAssessVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        cuMemberAssessVO.setPkMember(SecurityUtils.getUserId());
        cuMemberAssessVO.setPkCountry(pkCountry);
        //只有查询日期包含当前月，才会查询当前月的订单
        Date date = DateUtils.currentDate();
        cuMemberAssessVO.setStartDate(DateUtils.currentMonthFirstDate(date));
        cuMemberAssessVO.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, date));

        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());
        }
        if (StringUtils.isNotNull(cuMemberAssessVO.getEndDate())) {
            cuMemberAssessVO.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, cuMemberAssessVO.getEndDate()));
        }

        List<Integer> orderTypeList = new ArrayList<>();

        int assessType = Optional.ofNullable(cuMemberAssessVO.getAssessType()).orElse(0);
        if (EAssessmentType.REPURCHASE_ASSESS.getValue() == assessType) {
            // 复购考核
            orderTypeList.add(EOrderType.REPURCHASE_ORDER.getValue());
            orderTypeList.add(EOrderType.MALL_ORDER.getValue());
            cuMemberAssessVO.setOrderTypeList(orderTypeList);

            CuMemberAssessVO order = cuMemberAssessService.getOrderAssessList(cuMemberAssessVO);
            if (StringUtils.isNotNull(order)) {
                monthSurplus = monthSurplus.add(order.getOrderAchieve());
            }
            if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                R<CurrencyDTO> currency = currencyServiceApi.getCurrency(pkCountry);
                monthSurplus = monthSurplus.multiply(currency.getData().getInExchangeRate());
            }
        }
        return AjaxResult.success(monthSurplus);
    }


}
