package com.yeejoin.precontrol.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.precontrol.common.dto.StudioPageableDto;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.RewardExchange;
import com.yeejoin.precontrol.common.fileparser.utils.DateUtil;
import com.yeejoin.precontrol.common.service.IRewardExchangeService;
import com.yeejoin.precontrol.common.service.IRewardService;
import com.yeejoin.precontrol.common.utils.DateUtils;
import com.yeejoin.precontrol.common.utils.LocalDateTimeUtils;
import com.yeejoin.precontrol.common.utils.Response;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.vo.RewardExchangeVo;
import com.yeejoin.precontrol.common.vo.RewardExchangeWechatVo;
import com.yeejoin.precontrol.common.vo.RewardListVo;
import com.yeejoin.precontrol.common.vo.RewardVo;
import com.yeejoin.precontrol.controller.publics.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 奖励兑换api
 *
 * @author wbin
 * @date 2021-04-06
 */
@RestController
@Api(tags = "奖励兑换api")
@RequestMapping(value = "/reward/exchange", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class RewardExchangeController extends BaseController {

    @Autowired
    IRewardExchangeService iRewardExchangeService;

    @Autowired
    IRewardService rewardService;

    /**
     * 奖励兑换
     */
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "奖励兑换", notes = "奖励兑换")
    public boolean saveExchange(@RequestBody RewardExchangeVo rewardExchangeVo) {
        AgencyUserModel userInfo = getUserInfo();
        if (userInfo != null) {
            rewardExchangeVo.setCreateUserId(Long.valueOf(getUserId()));
        }
        return iRewardExchangeService.saveExchange(rewardExchangeVo);
    }

    /**
     * 奖励兑换统计图
     */
    @GetMapping(value = "/report")
    @ApiOperation(httpMethod = "GET", value = "奖励兑换统计图", notes = "奖励兑换统计图")
    public Object report(Integer count) throws Exception {
        if (count == null) {
            count = 30;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        // 统计的日期 数据
        List<String> dateList = DateUtils.getAfterDateByNowDate(count);
        Person person = getPerson();
        String startDate = dateList.get(0);
        String endDate = dateList.get(dateList.size() - 1);
        List<RewardExchange> list = iRewardExchangeService.reportByUserIdAndBetweenDate(startDate, endDate, person.getId());
        List<String> moneyList = new ArrayList();
        for (String date : dateList) {
            moneyList.add(processList(list, date));
        }
        // 日期
        map.put("dateList", dateList);
        // 金额
        map.put("moneyList", moneyList);
        //累计奖励总金额
        String total = rewardService.selectTotalMoney(person.getId());
        //已兑换总金额
        String money = iRewardExchangeService.selectTotalMoney(person.getId());
        processMoney(total, money, map);
        return new Response(map);
    }

    /**
     * 累计奖励总金额,已兑换总金额
     *
     * @param count
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/report/money")
    @ApiOperation(httpMethod = "GET", value = "累计奖励总金额,已兑换总金额 ", notes = "累计奖励总金额,已兑换总金额")
    public Object moneyTotal(Integer count) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Person person = getPerson();
        //累计奖励总金额
        String total = rewardService.selectTotalMoney(person.getId());
        //已兑换总金额
        String money = iRewardExchangeService.selectTotalMoney(person.getId());
        processMoney(total, money, map);
        return new Response(map);
    }

    /**
     * 处理金额
     * @param total
     * @param money
     * @param map
     */
    public static void processMoney(String total,String money, Map<String, Object> map){
        if (StringUtil.isNotEmpty(total)) {
            map.put("moneyTotal", new BigDecimal(total).setScale( 0, BigDecimal.ROUND_DOWN ).toPlainString());
        } else {
            map.put("moneyTotal", "0");
        }
        if(StringUtil.isNotEmpty(money)){
            map.put("rewardTotal", new BigDecimal(money).setScale( 0, BigDecimal.ROUND_DOWN ).toPlainString());
        }else{
            map.put("rewardTotal", "0");
        }
    }

    /**
     * 计算每个日期兑换的金额总和
     *
     * @param dataList
     * @param date
     * @return
     */
    public String processList(List<RewardExchange> dataList, String date) {
        BigDecimal total = new BigDecimal("0");
        if (dataList != null && dataList.size() > 0) {
            List<BigDecimal> collect = dataList.stream().filter(item -> LocalDateTimeUtils.format(item.getCreateDate()).substring(0, 10).replace("-", "").equals(date.replace("-", "")))
                    .map(RewardExchange::getMoney).collect(Collectors.toList());
            if (collect != null && collect.size() > 0) {
                for (BigDecimal bigDecimal : collect) {
                    total = total.add(bigDecimal);
                }
            }
        }
        return total.toPlainString();
    }

    /**
     * 选择日期的奖励兑换详情
     */
    @GetMapping(value = "/report/detail")
    @ApiOperation(httpMethod = "POST", value = "选择日期的奖励兑换详情", notes = "选择日期的奖励兑换详情")
    public Object rewardDate(String date) {
        Person person = getPerson();
        List<RewardExchangeWechatVo> list = iRewardExchangeService.selectByDate(date, person.getId());
        List<Object> retList = new ArrayList<Object>();
        if (list != null && list.size() > 0) {
            Map<String, List<RewardExchangeWechatVo>> collect = list.stream().collect(Collectors.groupingBy(RewardExchangeWechatVo::getBatchNo));
            for (List<RewardExchangeWechatVo> arr : collect.values()) {
                Map<String, Object> objectMap = new HashMap<String, Object>();
                BigDecimal total = new BigDecimal("0");
                if (arr != null && arr.size() > 0) {
                    for (RewardExchangeWechatVo bigDecimal : arr) {
                        total = total.add(bigDecimal.getMoney());
                    }
                }
                objectMap.put("count", arr.size());
                objectMap.put("sumMoeny", total);
                objectMap.put("list", arr);
                retList.add(objectMap);
            }
        }
        return new Response(retList);
    }
    
    @GetMapping(value = "/record")
    @ApiOperation(httpMethod = "GET", value = "发放记录", notes = "发放记录")
    public IPage<RewardExchangeWechatVo> exchangeRecord (StudioPageableDto pageable, Long personId) 
    {
    	IPage<RewardExchangeWechatVo> list = iRewardExchangeService.exchangeRecord(pageable, personId);
        return list;
    }
}


