package com.iformall.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxMall;
import com.iformall.domain.po.WxMerchant;
import com.iformall.domain.po.WxMerchantBUser;
import com.iformall.domain.po.WxMerchantTradeDaily;
import com.iformall.domain.vo.WxMerchantTradeDailyVo;
import com.iformall.mapper.WxMerchantTradeDailyMapper;
import com.iformall.service.WxMerchantTradeDailyService;
import com.iformall.service.WxMallService;
import com.iformall.service.WxMerchantBUserService;
import com.iformall.service.WxMerchantService;
import com.iformall.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.iformall.common.IdWorker;

@Service
public class WxMerchantTradeDailyServiceImpl implements WxMerchantTradeDailyService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxMerchantTradeDailyMapper wxMerchantTradeDailyMapper;

	@Autowired
    WxMerchantBUserService wxMerchantBUserService;

	@Autowired
    WxMerchantService wxMerchantService;

    @Autowired
    WxMallService wxMallService;

    @Override
    public PageInfo<WxMerchantTradeDaily> listAsPage(WxMerchantTradeDaily record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxMerchantTradeDailyMapper.findList(record));
    }

    @Override
    public WxMerchantTradeDaily getById(Long id) {
        return wxMerchantTradeDailyMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(WxMerchantTradeDaily record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
        	record.setId(idWorker.nextId());
            wxMerchantTradeDailyMapper.insertSelective(record);
        } else {
            wxMerchantTradeDailyMapper.updateByPrimaryKeySelective(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxMerchantTradeDailyMapper.deleteByPrimaryKey(id);
    }

    @Override
    public ResultData saveDailyTradingVolume(Long userId, Integer volume) {

        WxMerchantBUser user = wxMerchantBUserService.getById(userId);

        if (user==null)
            return new ResultData(ErrorCode.USER_IS_EMPTY);

        WxMerchant merchant = wxMerchantService.getById(user.getMerchantId());

        if (merchant==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);

        WxMall mall = wxMallService.getByTenantId(merchant.getTenantId());
        if (mall==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);


        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();

        wxMerchantTradeDaily.setMerchantId(merchant.getId());

        SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd");
        wxMerchantTradeDaily.setReportDate(fmt.format(new Date()));


        List<WxMerchantTradeDaily> tradeList = wxMerchantTradeDailyMapper.findList(wxMerchantTradeDaily);

        if (tradeList.size() > 0 ) {
            wxMerchantTradeDaily = tradeList.get(0);
            wxMerchantTradeDaily.setTradeAmt(volume);
            wxMerchantTradeDaily.setUpdateDate(new Date());
            wxMerchantTradeDailyMapper.updateByPrimaryKeySelective(wxMerchantTradeDaily);
            return new ResultData(wxMerchantTradeDaily);
        }

        final IdWorker idWorker = IdWorker.get();
        wxMerchantTradeDaily.setId(idWorker.nextId());
        wxMerchantTradeDaily.setTenantId(merchant.getTenantId());
        wxMerchantTradeDaily.setMerchantId(merchant.getId());
        wxMerchantTradeDaily.setbUserId(userId);
        wxMerchantTradeDaily.setTradeAmt(volume);
        wxMerchantTradeDaily.setCreateDate(new Date());
        wxMerchantTradeDaily.setUpdateDate(new Date());
        wxMerchantTradeDailyMapper.insert(wxMerchantTradeDaily);

        return new ResultData(wxMerchantTradeDaily);

    }


    @Override
    public PageInfo<WxMerchantTradeDailyVo> listAsPageVo(WxMerchantTradeDailyVo record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxMerchantTradeDailyMapper.findListVo(record));
    }

    @Override
    public ResultData updateYesterday(WxMerchantTradeDailyVo tradeDailyVo) {

        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();
        wxMerchantTradeDaily.setMerchantId(tradeDailyVo.getMerchantId());
        if (StringUtils.isEmpty(tradeDailyVo.getReportDate())) {
            wxMerchantTradeDaily.setReportDate(DateUtils.getTimeBefore(1, new Date()));
        } else {
            wxMerchantTradeDaily.setReportDate(tradeDailyVo.getReportDate());
        }
        List<WxMerchantTradeDaily> tradeList = wxMerchantTradeDailyMapper.findList(wxMerchantTradeDaily);

        if (tradeList.size() > 0) {
            wxMerchantTradeDaily = tradeList.get(0);
            wxMerchantTradeDaily.setTradeAmt(tradeDailyVo.getTradeAmt());
            wxMerchantTradeDaily.setUpdateDate(new Date());
            wxMerchantTradeDailyMapper.updateByPrimaryKeySelective(wxMerchantTradeDaily);
            return new ResultData(wxMerchantTradeDaily);
        }

        final IdWorker idWorker = IdWorker.get();
        wxMerchantTradeDaily.setId(idWorker.nextId());
        wxMerchantTradeDaily.setTenantId(tradeDailyVo.getTenantId());
        wxMerchantTradeDaily.setMerchantId(tradeDailyVo.getMerchantId());
        wxMerchantTradeDaily.setTradeAmt(tradeDailyVo.getTradeAmt());
        wxMerchantTradeDaily.setCreateDate(new Date());
        wxMerchantTradeDaily.setUpdateDate(new Date());
        wxMerchantTradeDailyMapper.insert(wxMerchantTradeDaily);

        return new ResultData(Result.SUCCESS, "操作成功");
    }

    @Override
    public ResultData queryTradeDaily(WxMerchantTradeDailyVo tradeDailyVo) {
        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();
        wxMerchantTradeDaily.setMerchantId(tradeDailyVo.getMerchantId());
        wxMerchantTradeDaily.setReportDate(tradeDailyVo.getReportDate());
        List<WxMerchantTradeDaily> tradeList = wxMerchantTradeDailyMapper.findList(wxMerchantTradeDaily);
        wxMerchantTradeDaily = tradeList.size() > 0 ? tradeList.get(0) : new WxMerchantTradeDaily();
        return new ResultData(wxMerchantTradeDaily);
    }

    @Override
    public ResultData getVolumeOfMonth(Long merchantId) {

        WxMerchant merchant = wxMerchantService.getById(merchantId);
        if (merchant==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);
        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();
        wxMerchantTradeDaily.setMerchantId(merchantId);

        List<WxMerchantTradeDailyVo> recordList = wxMerchantTradeDailyMapper.findListVoOfMonth(wxMerchantTradeDaily);
        Map<String,WxMerchantTradeDailyVo> recordMap = recordList.stream().collect(Collectors.toMap(WxMerchantTradeDailyVo::getReportDate, r -> r));

        List<WxMerchantTradeDailyVo> tradeList = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat fmtv = new SimpleDateFormat("MM/dd");
        cal.setTime(new Date());
        for (int i = 0; i < 30; i++) {
            cal.add(Calendar.DAY_OF_YEAR, -1);
            WxMerchantTradeDailyVo trade = recordMap.get(fmt.format(cal.getTime()));
            if (trade != null){
                trade.setReportDate(fmtv.format(cal.getTime()));
                trade.setTenantId(null);
                trade.setMerchantId(null);
                trade.setMerchantName(null);
                tradeList.add(trade);
            }else {
                trade = new  WxMerchantTradeDailyVo();
                trade.setTradeAmt(0);
                trade.setReportDate(fmtv.format(cal.getTime()));
                tradeList.add(trade);
            }
        }
        Collections.reverse(tradeList);
        return new ResultData(tradeList);
    }

    @Override
    public ResultData getVolumeTotalOfMonth(String tenantId) {


        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();
        wxMerchantTradeDaily.setTenantId(tenantId);

        List<WxMerchantTradeDaily> recordList = wxMerchantTradeDailyMapper.findTotalListOfMonth(wxMerchantTradeDaily);
        Map<String,WxMerchantTradeDaily> recordMap = recordList.stream().collect(Collectors.toMap(WxMerchantTradeDaily::getReportDate, r -> r));

        List<WxMerchantTradeDaily> tradeList = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat fmtv = new SimpleDateFormat("MM/dd");
        cal.setTime(new Date());
        for (int i = 0; i < 30; i++) {
            cal.add(Calendar.DAY_OF_YEAR, -1);
            WxMerchantTradeDaily trade = recordMap.get(fmt.format(cal.getTime()));
            if (trade != null){
                trade.setReportDate(fmtv.format(cal.getTime()));
                tradeList.add(trade);
            }else {
                trade = new  WxMerchantTradeDaily();
                trade.setTradeAmt(0);
                trade.setReportDate(fmtv.format(cal.getTime()));
                tradeList.add(trade);
            }
        }

        Collections.reverse(tradeList);
        return new ResultData(tradeList);
    }

    @Override
    public ResultData getVolume(Long userId) {

        WxMerchantBUser user = wxMerchantBUserService.getById(userId);

        if (user==null)
            return new ResultData(ErrorCode.USER_IS_EMPTY);

        WxMerchant merchant = wxMerchantService.getById(user.getMerchantId());

        if (merchant==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);

        WxMall mall = wxMallService.getByTenantId(merchant.getTenantId());
        if (mall==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);


        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();

        wxMerchantTradeDaily.setMerchantId(merchant.getId());

        SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd");
        wxMerchantTradeDaily.setReportDate(fmt.format(new Date()));


        List<WxMerchantTradeDaily> tradeList = wxMerchantTradeDailyMapper.findList(wxMerchantTradeDaily);

        if (tradeList.size() > 0 ) {
            wxMerchantTradeDaily = tradeList.get(0);
            return new ResultData(wxMerchantTradeDaily);
        }

        return new ResultData(ErrorCode.DALIY_REPORT_VOLUME_TODAY_NULL);

    }

    @Override
    public ResultData getVolumeOfWeek(Long userId) {

        WxMerchantBUser user = wxMerchantBUserService.getById(userId);

        if (user==null)
            return new ResultData(ErrorCode.USER_IS_EMPTY);

        WxMerchant merchant = wxMerchantService.getById(user.getMerchantId());

        if (merchant==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);

        WxMall mall = wxMallService.getByTenantId(merchant.getTenantId());
        if (mall==null)
            return new ResultData(ErrorCode.MERCHANT_INFO_NOT_FOUND);


        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();

        wxMerchantTradeDaily.setMerchantId(merchant.getId());

        SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd");
        wxMerchantTradeDaily.setReportDate(fmt.format(new Date()));

        return new ResultData(wxMerchantTradeDailyMapper.findListOfWeek(wxMerchantTradeDaily));

    }
    
    
    
    
    
}
