package com.xhpc.activity.service.impl;

import com.xhpc.activity.domain.XhpcActivityFormulaDomain;
import com.xhpc.activity.domain.XhpcActivityInternetDomain;
import com.xhpc.activity.mapper.XhpcActivityFormulaMapper;
import com.xhpc.activity.mapper.XhpcActivityInternetMapper;
import com.xhpc.activity.service.XhpcActivityInternetService;
import com.xhpc.activity.utils.AreaCodeUtil;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.exception.CustomException;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.util.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service
@Transactional
public class XhpcActivityInternetServiceImpl implements XhpcActivityInternetService {

    @Resource
    XhpcActivityInternetMapper internetMapper;

    @Resource
    XhpcActivityFormulaMapper formulaMapper;


    @Override
    public List<XhpcActivityInternetDomain> getPage(Map<String, Object> params) {
        return internetMapper.selectByParams(params);
    }


    @Override
    public List<Map<String, Object>> getNameList(Map<String, Object> params) {
        return internetMapper.selectNameMapList(params);
    }


    @Override
    public XhpcActivityInternetDomain getDomainByPk(Integer activityId) {

        XhpcActivityInternetDomain domain = internetMapper.selectByPrimaryKey(activityId);
        domain.setFormulaList(formulaMapper.selectByActivityId(activityId));
        return domain;
    }


    @Override
    public R insertDomain(XhpcActivityInternetDomain domain) {
        //判断流量方时间段和场站时间段是否一致
        String s = AreaCodeUtil.removeAreaCode(domain.getStationList());
        List<XhpcActivityFormulaDomain> formulaList = domain.getFormulaList();
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (int i = 0; i <formulaList.size() ; i++) {
            XhpcActivityFormulaDomain xhpcActivityFormulaDomain = formulaList.get(i);
            Map<String,Object> map = new HashMap<>();
            map.put("startTime",xhpcActivityFormulaDomain.getStartTime());
            map.put("endTime",xhpcActivityFormulaDomain.getEndTime());
            mapList.add(map);
        }
//        String[] split = s.split(",");
//        for (int i = 0; i <split.length ; i++) {
//            Long chargingStationId = Long.valueOf(split[i]);
//            List<Map<String, Object>> xhpcRateTimes = internetMapper.getXhpcRateTimes(chargingStationId);
//            if(mapList.size() ==xhpcRateTimes.size()){
//                for (Map map:mapList) {
//                    boolean flag = false;
//                    for (Map rateMap:xhpcRateTimes) {
//                        if(rateMap.get("startTime").toString().equals(map.get("startTime").toString()) && rateMap.get("endTime").toString().equals(map.get("endTime").toString())){
//                            flag =true;
//                        }
//                    }
//                    if(!flag){
//                        String chargingStation = internetMapper.getChargingStation(chargingStationId);
//                        return R.fail("与"+chargingStation+"场站时间段不一致");
//                    }
//                }
//            }else{
//                String chargingStation = internetMapper.getChargingStation(chargingStationId);
//                return R.fail("与"+chargingStation+"场站时间段不一致");
//            }
//        }

        domain.setStationList(AreaCodeUtil.removeAreaCode(domain.getStationList()));
        internetMapper.insert(domain);

        List<XhpcActivityFormulaDomain> formulaDomainList = getFormulaFullList(domain);
        formulaMapper.insertBatch(formulaDomainList);
        return R.ok();
    }


    @Override
    public boolean updateDomain(XhpcActivityInternetDomain domain) {
        domain.setStationList(AreaCodeUtil.removeAreaCode(domain.getStationList()));
        internetMapper.updateByPrimaryKey(domain);
        formulaMapper.deleteByActivityId(domain.getActivityId());

        List<XhpcActivityFormulaDomain> formulaDomainList = getFormulaFullList(domain);
        formulaMapper.insertBatch(formulaDomainList);
        return true;
    }


    /**
     * 组装费率列表
     * @param domain 流量方活动对象
     * @return 费率列表
     */
    private List<XhpcActivityFormulaDomain> getFormulaFullList(XhpcActivityInternetDomain domain){

        boolean isFullDay = false;
        int index = 0;
        List<XhpcActivityFormulaDomain> formulaDomainList = domain.getFormulaList();
        List<XhpcActivityFormulaDomain> formulaDomains = new ArrayList<>();
        String startTime = "00:00", endTime="24:00";
        if (formulaDomainList.size() > 0){
            if (formulaDomainList.get(0).getStartTime().length() != 5){
                startTime = "00:00:00";
                endTime = "24:00:00";
            }
        }

        while (!isFullDay) {
            if (formulaDomainList == null || formulaDomainList.size() < 1) {
                XhpcActivityFormulaDomain formulaDomain = new XhpcActivityFormulaDomain();
                formulaDomain.setActivityId(domain.getActivityId());
                formulaDomain.setPowerPrice(domain.getPowerPrice());
                formulaDomain.setServicePrice(domain.getServicePrice());
                formulaDomain.setComputeFormula(domain.getComputeFormula());
                formulaDomain.setStartTime(startTime);
                formulaDomain.setEndTime(endTime);
                formulaDomain.setCreateBy(domain.getCreateBy());
                formulaDomain.setUpdateBy(domain.getUpdateBy());
                formulaDomains.add(formulaDomain);
                isFullDay = true;
            } else {
                XhpcActivityFormulaDomain formulaDomain;
                if(index>=formulaDomainList.size()){
                    formulaDomain = new XhpcActivityFormulaDomain();
                    formulaDomain.setPowerPrice(domain.getPowerPrice());
                    formulaDomain.setServicePrice(domain.getServicePrice());
                    formulaDomain.setComputeFormula(domain.getComputeFormula());
                    formulaDomain.setStartTime(startTime);
                    formulaDomain.setEndTime(endTime);

                } else if (!startTime.equals(formulaDomainList.get(index).getStartTime())) {
                    formulaDomain = new XhpcActivityFormulaDomain();
                    formulaDomain.setPowerPrice(domain.getPowerPrice());
                    formulaDomain.setServicePrice(domain.getServicePrice());
                    formulaDomain.setComputeFormula(domain.getComputeFormula());
                    formulaDomain.setStartTime(startTime);
                    formulaDomain.setEndTime(formulaDomainList.get(index).getStartTime());

                } else {
                    formulaDomain = formulaDomainList.get(index);
                    index ++;
                }
                formulaDomain.setActivityId(domain.getActivityId());
                formulaDomain.setCreateBy(domain.getCreateBy());
                formulaDomain.setUpdateBy(domain.getUpdateBy());
                formulaDomains.add(formulaDomain);

                startTime = formulaDomain.getEndTime();
                if(endTime.equals(startTime)){
                    isFullDay = true;
                }
            }
        }
        boolean checkFlag = checkFormulaList(formulaDomains);
        if(!checkFlag){
            System.out.println(formulaDomains);
            throw new CustomException("费率设置错误，请检查");
        }
        return formulaDomains;
    }


    /**
     * 检查费率设置正确
     * @param formulaDomains 费率列表
     * @return 标志位
     */
    private boolean checkFormulaList(List<XhpcActivityFormulaDomain> formulaDomains){
        boolean checkFlag = true;
        formulaDomains = formulaDomains.stream().sorted(Comparator.comparing(XhpcActivityFormulaDomain::getStartTime)).collect(Collectors.toList());

        int endTime = 0;
        for (XhpcActivityFormulaDomain domain: formulaDomains){
            Integer curStartTime = Integer.parseInt(domain.getStartTime().replaceAll(":", ""));
            Integer curEndTime = Integer.parseInt(domain.getEndTime().replaceAll(":", ""));

            if(domain.getStartTime().equals(domain.getEndTime()) || curStartTime.equals(curEndTime) || curStartTime < endTime){
                checkFlag = false; break;
            }
            endTime = curEndTime;
        }

        return checkFlag;
    }


    @Override
    public boolean updateDomainStatus(XhpcActivityInternetDomain domain) {
        return internetMapper.updateStatusByPrimaryKey(domain) > 0;
    }


    @Override
    public boolean checkDomain(XhpcActivityInternetDomain domain) {
        XhpcActivityInternetDomain internetDomain = internetMapper.selectByPrimaryKey(domain.getActivityId());
        if(internetDomain == null){
            throw new CustomException("活动不存在");
        }
        // 同一时间段内只能有一个活动有效
        String startTime = DateUtil.date2String(internetDomain.getStartTime(), "yyyy-MM-dd");
        String endTime = DateUtil.date2String(internetDomain.getEndTime(), "yyyy-MM-dd");

        List<String> stationList = new ArrayList<>();
        if(StringUtils.isNotEmpty(domain.getStationList()) && !"-1".equals(domain.getStationList())){
            stationList = Arrays.asList(domain.getStationList().split(","));
        }

        List<XhpcActivityInternetDomain> domainList = internetMapper.selectByDateBetween(domain.getInternetName(), stationList, startTime, endTime);
        if(domainList.size() > 0 && domain.getStatus().equals(Short.valueOf("3"))){
            throw new CustomException("生效时段存在其他已生效的活动");
        }

        return internetMapper.checkByPrimaryKey(domain) > 0;
    }


    @Override
    public boolean deleteByPk(Integer activityId) {
        return internetMapper.deleteLogicByPrimaryKey(activityId) > 0;
    }

}
