package com.hai.service.impl;

import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.dao.HighCouponAgentCodeMapper;
import com.hai.dao.HighCouponAgentRecordMapper;
import com.hai.dao.HighCouponAgentRelMapper;
import com.hai.entity.*;
import com.hai.model.AgentSalesModel;
import com.hai.service.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/4/20 23:02
 */
@Service("highCouponAgentService")
public class HighCouponAgentServiceImpl implements HighCouponAgentService {

    @Resource
    private HighCouponAgentRelMapper highCouponAgentRelMapper;

    @Resource
    private HighMerchantService highMerchantService;

    @Resource
    private HighCouponAgentCodeMapper highCouponAgentCodeMapper;

    @Resource
    private HighCouponAgentRecordMapper highCouponAgentRecordMapper;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private HighAgentService highAgentService;

    @Override
    public void assignCouponAgent(HighCouponAgentRel highCouponAgentRel,Integer stockCount) {

        // 查询未销售的卡券
        List<HighCouponCode> codeList = highCouponCodeService.getNoSaleCode(highCouponAgentRel.getCouponId());
        if (stockCount > codeList.size()) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法分配，分配数量超过库存数量");
        }
        if (highCouponAgentRel.getId() != null) {
            highCouponAgentRelMapper.updateByPrimaryKey(highCouponAgentRel);
        } else {
            highCouponAgentRelMapper.insert(highCouponAgentRel);
        }

        // 查询代理商
        HighAgent highAgent = highAgentService.findByAgentMsgId(highCouponAgentRel.getAgentId());

        // 查询卡券
        HighCoupon highCoupon = highCouponService.getCouponById(highCouponAgentRel.getCouponId());

        // 库存记录
        HighCouponAgentRecord record = new HighCouponAgentRecord();
        record.setCouponAgentId(highCouponAgentRel.getId());
        record.setCouponId(highCouponAgentRel.getCouponId());
        record.setCouponName(highCoupon.getCouponName());
        record.setSalesPrice(highCoupon.getSalesPrice());
        record.setAgentId(highCouponAgentRel.getAgentId());
        record.setAgentName(highAgent.getAgentName());
        record.setStockCount(stockCount);
        record.setOperatorId(highCouponAgentRel.getOperatorId());
        record.setOperatorName(highCouponAgentRel.getOperatorName());
        record.setCreateTime(new Date());
        highCouponAgentRecordMapper.insert(record);

        List<HighCouponCode> assignCouponCodeList = codeList.stream().limit(stockCount).collect(Collectors.toList());
        HighCouponAgentCode highCouponAgentCode;
        for (HighCouponCode code : assignCouponCodeList) {
            code.setAgentId(highCouponAgentRel.getAgentId());
            code.setIsAssignAgent(true);
            highCouponCodeService.updateCouponCode(code);

            highCouponAgentCode = new HighCouponAgentCode();
            highCouponAgentCode.setCouponAgentId(highCouponAgentRel.getId());
            highCouponAgentCode.setCouponAgentRecordId(record.getId());
            highCouponAgentCode.setCouponId(code.getCouponId());
            highCouponAgentCode.setAgentId(highCouponAgentRel.getAgentId());
            highCouponAgentCode.setCouponCodeId(code.getId());
            highCouponAgentCode.setCouponCode(code.getSalesCode());
            highCouponAgentCode.setQrCode(code.getExt1());
            highCouponAgentCode.setStatus(1);
            highCouponAgentCode.setCreateTime(new Date());
            highCouponAgentCode.setOperatorId(highCouponAgentRel.getOperatorId());
            highCouponAgentCode.setOperatorName(highCouponAgentRel.getOperatorName());
            highCouponAgentCodeMapper.insert(highCouponAgentCode);
        }
    }

    @Override
    public void updateCouponAgentCode(HighCouponAgentCode highCouponAgentCode) {
        highCouponAgentCodeMapper.updateByPrimaryKey(highCouponAgentCode);
    }

    @Override
    public HighCouponAgentRel getRelByCouponAgent(Long couponId, Long agentId) {
        HighCouponAgentRelExample example = new HighCouponAgentRelExample();
        example.createCriteria().andCouponIdEqualTo(couponId).andAgentIdEqualTo(agentId);
        List<HighCouponAgentRel> list = highCouponAgentRelMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<HighCouponAgentRel> getCouponAgentList(Map<String, Object> map) {
        HighCouponAgentRelExample example = new HighCouponAgentRelExample();
        HighCouponAgentRelExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "couponId") != null) {
            criteria.andCouponIdEqualTo(MapUtils.getLong(map, "couponId"));
        }

        if (MapUtils.getLong(map, "agentId") != null) {
            criteria.andAgentIdEqualTo(MapUtils.getLong(map, "agentId"));
        }

        criteria.andStatusEqualTo(1);
        example.setOrderByClause("create_time desc");
        return highCouponAgentRelMapper.selectByExample(example);
    }

    @Override
    public List<HighCouponAgentCode> getCouponCodeList(Map<String, Object> map) {
        HighCouponAgentCodeExample example = new HighCouponAgentCodeExample();
        HighCouponAgentCodeExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "couponAgentId") != null) {
            criteria.andCouponAgentIdEqualTo(MapUtils.getLong(map, "couponAgentId"));
        }

        if (MapUtils.getLong(map, "couponId") != null) {
            criteria.andCouponIdEqualTo(MapUtils.getLong(map, "couponId"));
        }

        if (MapUtils.getLong(map, "agentId") != null) {
            criteria.andAgentIdEqualTo(MapUtils.getLong(map, "agentId"));
        }

        if (MapUtils.getLong(map, "createTimeS") != null) {
            criteria.andCreateTimeGreaterThanOrEqualTo(new Date(MapUtils.getLong(map, "createTimeS")));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            criteria.andCreateTimeLessThanOrEqualTo(new Date(MapUtils.getLong(map, "createTimeE")));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "status"))) {
            String[] strings = MapUtils.getString(map, "status").split(",");
            List<Integer> statusList = new ArrayList<>();
            for (String i : strings) {
                statusList.add(Integer.parseInt(i));
            }
            criteria.andStatusIn(statusList);
        }

        example.setOrderByClause("create_time desc");
        return highCouponAgentCodeMapper.selectByExample(example);
    }

    @Override
    public HighCouponAgentCode getCodeById(Long couponAgentCodeId) {
        return highCouponAgentCodeMapper.selectByPrimaryKey(couponAgentCodeId);
    }

    @Override
    public HighCouponAgentCode getAgentCodeByCodeIdAgent(Long codeId, Long agentId) {
        HighCouponAgentCodeExample example = new HighCouponAgentCodeExample();
        example.createCriteria().andCouponCodeIdEqualTo(codeId).andAgentIdEqualTo(agentId);
        List<HighCouponAgentCode> list = highCouponAgentCodeMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public Map<String, Object> generateCode(Long couponAgentCodeId,String remark) {
        // 查询卡券销售码
        HighCouponAgentCode couponAgentCode = getCodeById(couponAgentCodeId);
        if (couponAgentCode == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到销售码");
        }
        if (couponAgentCode.getStatus() != 1) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "销售码已被销售");
        }
        couponAgentCode.setStatus(2);  // 状态：1.待销售 2.未使用 3.已使用
        couponAgentCode.setRemark(remark);
        highCouponAgentCodeMapper.updateByPrimaryKey(couponAgentCode);

        HighCouponAgentRel couponAgent = getRelByCouponAgent(couponAgentCode.getCouponId(), couponAgentCode.getAgentId());
        couponAgent.setStockCount(couponAgent.getStockCount() - 1);
        couponAgent.setSalesCount(couponAgent.getSalesCount() + 1);
        highCouponAgentRelMapper.updateByPrimaryKey(couponAgent);

        HighCouponCode couponCode = highCouponCodeService.getCouponCodeById(couponAgentCode.getCouponCodeId());
        couponCode.setStatus(2);
        couponCode.setReceiveTime(new Date());
        highCouponCodeService.updateCouponCode(couponCode);

        Map<String, Object> map = new HashMap<>();
        map.put("couponInfo", highCouponService.getCouponById(couponAgentCode.getCouponId()));
        map.put("couponCode", couponCode);
        map.put("couponAgentCode", couponAgentCode);
        return map;
    }

    @Override
    public Map<String, Object> getSalesCountByAgent(Long agentId) throws Exception {
        BigDecimal surplusCountPrice = new BigDecimal("0");
        BigDecimal salesCountPrice = new BigDecimal("0");

        Map<String,Object> listMap = new HashMap<>();
        listMap.put("agentId", agentId);
        List<HighCouponAgentRel> list = getCouponAgentList(listMap).stream().sorted(Comparator.comparing(HighCouponAgentRel::getSalesPrice)).collect(Collectors.toList());
        for (HighCouponAgentRel highCouponAgentRel : list) {
            BigDecimal surplusPrice = new BigDecimal(highCouponAgentRel.getStockCount()).multiply((highCouponAgentRel.getSalesPrice()));
            surplusCountPrice = surplusCountPrice.add(surplusPrice);

            BigDecimal salesPrice = new BigDecimal(highCouponAgentRel.getSalesCount()).multiply((highCouponAgentRel.getSalesPrice()));
            salesCountPrice = salesCountPrice.add(salesPrice);
        }

        // 计算使用有效期
        Calendar consumeTimeS = Calendar.getInstance();
        consumeTimeS.setTime(new Date());
        consumeTimeS.set(Calendar.HOUR_OF_DAY, 00);
        consumeTimeS.set(Calendar.MINUTE, 00);
        consumeTimeS.set(Calendar.SECOND, 00);

        Calendar consumeTimeE = Calendar.getInstance();
        consumeTimeE.setTime(new Date());
        consumeTimeE.set(Calendar.HOUR_OF_DAY, 23);
        consumeTimeE.set(Calendar.MINUTE, 59);
        consumeTimeE.set(Calendar.SECOND, 59);

        AgentSalesModel agentSales = highCouponAgentRelMapper.getAgentSales(agentId, DateUtil.date2String(consumeTimeS.getTime(), "yyyy-MM-dd HH:mm:ss"), DateUtil.date2String(consumeTimeE.getTime(), "yyyy-MM-dd HH:mm:ss"));

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("orderCount", agentSales.getCount());
        returnMap.put("turnoverPrice", agentSales.getSalesCountPrice());

        returnMap.put("laveStockCount", highCouponAgentRelMapper.getAgentCodeCount(agentId, "1"));  // 库存数量
        returnMap.put("soldCount", highCouponAgentRelMapper.getAgentCodeCount(agentId, "2,3"));       // 销售数量

        returnMap.put("surplusCountPrice", surplusCountPrice); // 剩余总额
        returnMap.put("salesCountPrice", salesCountPrice);   // 销售总额
        returnMap.put("list", list);
        return returnMap;
    }

    @Override
    public List<HighCouponAgentRecord> getRecordList(Map<String, Object> map) {
        HighCouponAgentRecordExample example = new HighCouponAgentRecordExample();
        HighCouponAgentRecordExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "couponAgentId") != null) {
            criteria.andCouponAgentIdEqualTo(MapUtils.getLong(map, "couponAgentId"));
        }

        example.setOrderByClause("create_time desc");
        return highCouponAgentRecordMapper.selectByExample(example);
    }

    @Override
    public List<HighCouponAgentCode> getCouponAgentCodeList(Map<String, Object> map) {
        HighCouponAgentCodeExample example = new HighCouponAgentCodeExample();
        HighCouponAgentCodeExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "recordId") != null) {
            criteria.andCouponAgentRecordIdEqualTo(MapUtils.getLong(map, "recordId"));
        }

        example.setOrderByClause("create_time desc");
        return highCouponAgentCodeMapper.selectByExample(example);
    }

    @Override
    public List<HighCouponAgentCode> getAgentSalesCodeList(Long agentId, String consumeTimeS, String consumeTimeE) {
        List<HighCouponAgentCode> list = highCouponAgentRelMapper.getAgentSalesCodeList(agentId, consumeTimeS, consumeTimeE);
        if (list != null && list.size() > 0) {
            for (HighCouponAgentCode code : list) {
                code.setHighCoupon(highCouponService.getCouponDetail(code.getCouponId()));
                code.setHighCouponCode(highCouponCodeService.getCouponCodeById(code.getCouponCodeId()));
            }
            return list;
        }
        return new ArrayList<>();
    }
}
