package com.hai.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.dao.HighDiscountPackageActualMapper;
import com.hai.dao.HighDiscountPackageDiscountActualMapper;
import com.hai.dao.HighDiscountPackageRecordMapper;
import com.hai.dao.HighDiscountUserRelMapper;
import com.hai.entity.*;
import com.hai.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service("hltUnionCardVipService")
public class HltUnionCardVipServiceImpl implements HltUnionCardVipService {

    @Resource
    private HighDiscountPackageRecordMapper highDiscountPackageRecordMapper;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighDiscountPackageService highDiscountPackageService;

    @Resource
    private CommonService commonService;

    @Resource
    private BsCompanyService bsCompanyService;

    @Resource
    private HighDiscountAgentCodeService highDiscountAgentCodeService;

    @Resource
    private HighDiscountUserRelMapper highDiscountUserRelMapper;

    @Resource
    private HighDiscountService highDiscountService;

    @Resource
    private HighDiscountPackageActualService discountPackageActualService;

    @Resource
    private HighDiscountPackageRecordService discountPackageRecordService;

    @Resource
    private HighDiscountPackageDiscountActualService discountPackageDiscountActualService;


    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public JSONObject GetMembershipLevel(String phone , String regionId)   throws Exception  {

        SecRegion region = commonService.getParentByRegion(Long.parseLong(regionId));

        BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());

        JSONObject consumptionRecord = HuiLianTongUnionCardConfig.checkEMsgUnionCardVipRights(phone);
        JSONObject cardInfoObject = HuiLianTongUnionCardConfig.resolveResponseMembership(consumptionRecord.getString("data"));


        HighUser highUser = highUserService.findByPhone(phone);

        if (highUser == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前用户不存在");
        }

        boolean isVip = false;
        boolean isFree = false;
        // 1: 1-E信通会员权益，2-工会卡会员权益
        int equityLevel = 0;

        if (cardInfoObject != null) {
            // 判断用户是否有会员权益
            for (Object dataObject : cardInfoObject.getJSONArray("data")) {
                JSONObject d = (JSONObject) dataObject;
                if (d.getInteger("level").equals(1) || d.getInteger("level").equals(12)) {
                    isVip = true;
                    equityLevel = 1;
                } else if (d.getInteger("level").equals(2)) {
                    isVip = true;
                    equityLevel = 2;
                } else if (d.getInteger("level").equals(3)) {
                    isVip = true;
                    isFree = true;
                    equityLevel = 1;
                }
            }
        }

        // 判断汇联通会员等级 1-E信通会员，2-工会卡会员，12-E信通和工会卡会员
        if (isVip) {

            List<HighDiscountPackageRecord> list = highDiscountPackageRecordMapper.CheckCouponsMonth(highUser.getId() , equityLevel);

            // 判断当月是否赠送会员权益
            if (list.size() > 0 ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "用户当月已赠送");
            } else {

                if (isFree && discountPackageRecordService.isGive(highUser.getId())) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "免费用户已赠送");
                }

                Map<String,Object> map = new HashMap<>();
                map.put("companyId", bsCompany.getId());
                map.put("usingAttribution", equityLevel);
                map.put("salesType", 2);
                map.put("status", 1);

                // 查询专属优惠券包
                List<HighDiscountPackage> highDiscountPackages =  highDiscountPackageService.getDiscountPackageList(map);

                    if (highDiscountPackages.size() == 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂未配置专属优惠券包");
                }

                HighDiscountPackage highDiscountPackage = highDiscountPackages.get(0);

                // 查询优惠券包实际库存
                HighDiscountPackageActual discountPackageActual = discountPackageActualService.getHighDiscountPackageActualList(highDiscountPackage.getId()).get(0);

                // 修改优惠券包实际库存状态
                discountPackageActual.setStatus(0);
                discountPackageActual.setUserId(highUser.getId().intValue());
                discountPackageActual.setAllocationTime(new Date());
                discountPackageActualService.updateHighDiscountPackageActual(discountPackageActual);

                // 查询优惠券包实际库存中实际优惠券数量
                List<HighDiscountPackageDiscountActual> discountPackageDiscountActual = discountPackageDiscountActualService.getHighDiscountPackageDiscountActualList(discountPackageActual.getId());

                // 循环赠送优惠券
                for (HighDiscountPackageDiscountActual actualList: discountPackageDiscountActual) {

                    HighDiscountUserRel highDiscountUserRel = new HighDiscountUserRel();
                    highDiscountUserRel.setDiscountId(actualList.getDiscountId());
                    highDiscountUserRel.setUserId(highUser.getId());
                    highDiscountUserRel.setAgentId(actualList.getAgentId());
                    highDiscountUserRel.setDiscountAgentCodeId(actualList.getAgentDiscountCodeId());
                    highDiscountUserRel.setStatus(1);
                    highDiscountUserRel.setCreateTime(new Date());

                    HighDiscount highDiscount  = highDiscountService.getDiscountById(actualList.getDiscountId());

                    // 计算使用有效期
                    Calendar userEndTime = Calendar.getInstance();
                    userEndTime.setTime(new Date());
                    userEndTime.set(Calendar.HOUR_OF_DAY, 23);
                    userEndTime.set(Calendar.MINUTE, 59);
                    userEndTime.set(Calendar.SECOND, 59);
                    userEndTime.add(Calendar.DATE, highDiscount.getEffectiveDay());
                    highDiscountUserRel.setUseEndTime(userEndTime.getTime());

                    HighDiscountAgentCode discountAgentCode = highDiscountAgentCodeService.getCodeById(actualList.getAgentDiscountCodeId());

                    // 修改优惠券二维码状态
                    discountAgentCode.setStatus(2);
                    highDiscountAgentCodeService.updateCode(discountAgentCode);

                    // 新增优惠券与用户的绑定关系
                    highDiscountUserRelMapper.insert(highDiscountUserRel);

                    // 修改优惠券包实际库存实际优惠券状态
                    actualList.setStatus(0);
                    discountPackageDiscountActualService.updateHighDiscountPackageDiscountActual(actualList);
                }

                // 增加赠送记录
                HighDiscountPackageRecord discountPackageRecord = new HighDiscountPackageRecord();
                discountPackageRecord.setDiscountPackageId(highDiscountPackage.getId());
                discountPackageRecord.setDiscountPackageTitle(highDiscountPackage.getTitle());
                discountPackageRecord.setCompanyId(highDiscountPackage.getCompanyId());
                discountPackageRecord.setStatus(1);
                discountPackageRecord.setUsingAttribution(1);
                discountPackageRecord.setRecordNo("DP" + DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + IDGenerator.nextId(5) );
                discountPackageRecord.setSalesType(2);
                discountPackageRecord.setUserId(highUser.getId().intValue());
                discountPackageRecord.setExt1(highUser.getPhone());
                discountPackageRecord.setCreatedTime(new Date());
                highDiscountPackageRecordMapper.insert(discountPackageRecord);
                }

            }

        if (isFree) {
            HuiLianTongUnionCardConfig.submitSms(phone , "“E信通春节关怀”3张4元话费券、99折加油券已到账，打开“嗨森逛”微信小程序>我的>我的优惠券即可直接使用，到账之日起1月内（30天）有效。");
        } else {
            if (equityLevel == 1) {
                HuiLianTongUnionCardConfig.submitSms(phone , "“E信通会员专属”3张4元话费券、2张99折加油券已到账，打开“嗨森逛”微信小程序>我的>我的优惠券即可直接使用，到账之日起1月内（30天）有效。");
            } else {
                HuiLianTongUnionCardConfig.submitSms(phone , "“工会卡用户专属”2元话费券、2张96折加油券已到账，打开“嗨森逛”微信小程序>我的>我的优惠券即可直接使用，到账之日起1月内（30天）有效。");
            }
        }

        return null;
    }
}
