package com.hai.service.impl;

import com.hai.common.QRCodeGenerator;
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.IDGenerator;
import com.hai.dao.HighChildOrderMapper;
import com.hai.dao.HighCouponCodeMapper;
import com.hai.dao.HighCouponCodeMapperExt;
import com.hai.entity.*;
import com.hai.model.GzSinopecModel;
import com.hai.model.UserInfoModel;
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.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/14 17:45
 */
@Service("highCouponCodeService")
public class HighCouponCodeServiceImpl implements HighCouponCodeService {

    @Resource
    private HighCouponCodeMapper highCouponCodeMapper;

    @Resource
    private HighCouponCodeMapperExt highCouponCodeMapperExt;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private HighUserCouponService highUserCouponService;

    @Resource
    private HighCouponAgentService highCouponAgentService;

    @Resource
    private HighChildOrderMapper highChildOrderMapper;

    @Override
    public void insertCouponCode(HighCouponCode highCouponCode) {
        highCouponCodeMapper.insert(highCouponCode);
    }

    @Override
    public void insertList(List<HighCouponCode> list) throws Exception {
        for (HighCouponCode highCouponCode: list) {
            // 生成二维码
            String qrCodeImg = DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + IDGenerator.nextId(10) +".png";
            String qrCodeUrl = "/home/project/hsg/filesystem/couponCode/" + qrCodeImg;
            QRCodeGenerator.generateQRCodeImage(highCouponCode.getSalesCode(), 350, 350, qrCodeUrl);
            highCouponCode.setExt1(qrCodeImg);
        }
        highCouponCodeMapperExt.insertList(list);
    }

    @Override
    public void updateCouponCode(HighCouponCode highCouponCode) {
        highCouponCodeMapper.updateByPrimaryKey(highCouponCode);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void useCouponCode(String code, UserInfoModel userInfoModel) {

        // 查询销售码
        HighCouponCode salesCode = getCouponCodeBySalesCode(code);
        if (salesCode == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON_CODE, "");
        }

        // 状态：1.待销售 2.未使用 3.已使用  99.预支付
        if (salesCode.getStatus() != 2) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_CODE_STATUS, "");
        }

        // 使用时间已到期
        if (salesCode.getUseEndTime().compareTo(new Date()) == -1) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_CODE_OVERDUE, "");
        }

        // 卡券信息
        HighCoupon coupon = highCouponService.getCouponById(salesCode.getCouponId());
        if (coupon == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_DISCOUNT, "");
        }
        // 卡券来源：1.中石化
        if (coupon.getCouponSource() == 1) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "中石化卡券无法消核，请前往中石化门店");
        }
        salesCode.setStoreId(userInfoModel.getMerchantStore().getId());
        salesCode.setStoreName(userInfoModel.getMerchantStore().getStoreName());
        salesCode.setConsumeTime(new Date());
        salesCode.setStatus(3);
        updateCouponCode(salesCode);

        // 代理商
        if (salesCode.getIsAssignAgent() == true) {
            HighCouponAgentCode couponAgentCode = highCouponAgentService.getAgentCodeByCodeIdAgent(salesCode.getId(), salesCode.getAgentId());
            if (couponAgentCode != null) {
                couponAgentCode.setStatus(3);
                highCouponAgentService.updateCouponAgentCode(couponAgentCode);
            }
        }

        //修改 用户与卡卷的关系
        HighUserCoupon userCoupon = highUserCouponService.getDetailByCodeId(salesCode.getId());
        // 可能是分卡卡券，分发卡券没有绑定用户
        if (userCoupon != null) {
            HighChildOrder order = highOrderService.getChildOrderByUserGoods(userCoupon.getUserId(), 1, userCoupon.getCouponId());
            if (order == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单");
            }
            userCoupon.setStoreId(userInfoModel.getMerchantStore().getId());
            userCoupon.setConsumeTime(new Date());
            userCoupon.setStatus(2);  // 状态  0:已过期  1：未使用  2：已使用
            highUserCouponService.updateUserCoupon(userCoupon);
            //highOrderService.childOrderComplete(order.getId());
        }
    }

    @Override
    @Transactional
    public void cnpcCallbackCouponCode(String codeKey, Date useTime,String nodeName) {
        HighCouponCode code = getCouponCodeByKey(codeKey);
        if (code != null && code.getStatus() != 3) {
            code.setStatus(3);
            code.setConsumeTime(useTime);
            code.setStoreName(nodeName);
            updateCouponCode(code);

            Map<String, Object> map = new HashMap<>();
            map.put("status", "1");
            map.put("couponCodeId", code.getId());

            // 代理商
            if (code.getIsAssignAgent() == true) {
                HighCouponAgentCode couponAgentCode = highCouponAgentService.getAgentCodeByCodeIdAgent(code.getId(), code.getAgentId());
                if (couponAgentCode != null) {
                    couponAgentCode.setStatus(3);
                    highCouponAgentService.updateCouponAgentCode(couponAgentCode);
                }
            }

            List<HighUserCoupon> list = highUserCouponService.getUserCouponList(map);
            if (list.size() > 0) {
                for (HighUserCoupon userCoupon : list) {
                    userCoupon.setConsumeTime(useTime);
                    userCoupon.setStatus(2);  // 状态  0:已过期  1：未使用  2：已使用
                    highUserCouponService.updateUserCoupon(userCoupon);

                    if (code.getChildOrderId() != null) {
                        highOrderService.childOrderComplete(code.getChildOrderId());
                    }
                    /*HighChildOrderExample example = new HighChildOrderExample();
                    example.createCriteria().andMemIdEqualTo(userCoupon.getUserId()).andGoodsTypeEqualTo(1).andGoodsIdEqualTo(userCoupon.getCouponId()).andChildOrdeStatusEqualTo(2);
                    List<HighChildOrder> childOrderList = highChildOrderMapper.selectByExample(example);
                    if (childOrderList.size() > 0) {
                        highOrderService.childOrderComplete(childOrderList.get(0).getId());
                    }
                     HighChildOrder order = highOrderService.getChildOrderByUserGoods(userCoupon.getUserId(), 1, userCoupon.getCouponId());
                    if (order == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单");
                    }*/
                }
            }
        }
    }

    @Override
    public HighCouponCode getCouponCodeByOrderId(Long childOrderId) {
        HighCouponCodeExample example = new HighCouponCodeExample();
        example.createCriteria().andChildOrderIdEqualTo(childOrderId);

        List<HighCouponCode> codes = highCouponCodeMapper.selectByExample(example);
        if (codes != null && codes.size() > 0) {
            return codes.get(0);
        }
        return null;
    }

    @Override
    public HighCouponCode getCouponCodeByUserDiscount(Long discountUserRelId) {
        return null;
    }

    @Override
    public HighCouponCode getCouponCodeBySalesCode(String code) {
        HighCouponCodeExample example = new HighCouponCodeExample();
        example.createCriteria().andSalesCodeEqualTo(code);
        List<HighCouponCode> codes = highCouponCodeMapper.selectByExample(example);
        if (codes != null && codes.size() > 0) {
            return codes.get(0);
        }
        return null;
    }

    @Override
    public HighCouponCode getCouponCodeByKey(String codeKey) {
        HighCouponCodeExample example = new HighCouponCodeExample();
        example.createCriteria().andCodeKeyEqualTo(codeKey);
        List<HighCouponCode> codes = highCouponCodeMapper.selectByExample(example);
        if (codes != null && codes.size() > 0) {
            return codes.get(0);
        }
        return null;
    }

    @Override
    public HighCouponCode getCouponCodeById(Long id) {
        return highCouponCodeMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer getStockCountByCoupon(Long couponId) {
        HighCouponCodeExample example = new HighCouponCodeExample();
        example.createCriteria().andCouponIdEqualTo(couponId).andStatusEqualTo(1).andSalesEndTimeGreaterThan(new Date()).andIsAssignAgentEqualTo(false);
        return highCouponCodeMapper.selectByExample(example).size();
    }

    @Override
    public List<HighCouponCode> getNoSaleCode(Long couponId) {
        HighCouponCodeExample example = new HighCouponCodeExample();
        example.createCriteria().andCouponIdEqualTo(couponId).andStatusEqualTo(1).andIsAssignAgentEqualTo(false).andSalesEndTimeGreaterThan(new Date());
        return highCouponCodeMapper.selectByExample(example);
    }

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

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

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

        if (MapUtils.getInteger(map, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(map, "status"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "salesCode"))) {
            criteria.andSalesCodeLike("%" + MapUtils.getString(map, "salesCode") + "%");
        }

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

        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 (MapUtils.getBoolean(map, "isAssignAgent") != null) {
            criteria.andIsAssignAgentEqualTo(MapUtils.getBoolean(map, "isAssignAgent"));
        }

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

    @Override
    public List<GzSinopecModel> getGzSinopecAssignList(Map<String, Object> map) throws Exception {
        if (MapUtils.getLong(map, "assignTimeS") != null) {
            map.put("assignTimeS", DateUtil.date2String(new Date(MapUtils.getLong(map, "assignTimeS")), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getLong(map, "assignTimeE") != null) {
            map.put("assignTimeE", DateUtil.date2String(new Date(MapUtils.getLong(map, "assignTimeE")), "yyyy-MM-dd HH:mm:ss"));
        }
        return highCouponCodeMapper.selectGzSinopecAssignList(map);
    }


}
