package com.xhpc.charging.station.service;

import cn.hutool.core.date.DateUtil;
import com.xhpc.charging.station.dto.XhpcPlaceholderDto;
import com.xhpc.charging.station.dto.XhpcPlaceholderTimeDto;
import com.xhpc.charging.station.mapper.XhpcPlaceholderMapper;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.domain.XhpcPlaceholderTime;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yuyang
 * @Date 2025-04-22 22:31
 */
@Service
public class XhpcPlaceholderServiceImpl extends BaseService implements IXhpcPlaceholderService{

    @Resource
    XhpcPlaceholderMapper xhpcPlaceholderMapper;
    @Autowired
    private TokenService tokenService;
    @Override
    public List<Map<String, Object>> getXhpcPlaceholderList(HttpServletRequest request, Map<String, Object> params) {

        //获取登陆用户
        LoginUser loginUser = tokenService.getLoginUser(request);
        SysUser sysUser = loginUser.getSysUser();
        Long sysUserId = sysUser.getUserId();
        //桩的统计、该时段金额
        List<Map<String, Object>> list =new ArrayList<>();
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            if(UserTypeUtil.SYS_SUPER_TYPE_ONE == loginUser.getSuperType()){
                params.put("tenantId",loginUser.getTenantId());
                return  xhpcPlaceholderMapper.getXhpcPlaceholderList(params);
            }
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                params.put("logOperatorId",logOperatorId);
                params.put("type",1);
                //运营商看自己的场站
                list = xhpcPlaceholderMapper.getXhpcPlaceholderList(params);
            }else{
                params.put("type",2);
                params.put("logOperatorId",sysUserId);
                //查询赋值的场站
                list = xhpcPlaceholderMapper.getXhpcPlaceholderList(params);
            }
        }else{
            startPage();
            params.put("type",0);
            list = xhpcPlaceholderMapper.getXhpcPlaceholderList(params);
        }

        return list;
    }

    @Override
    public Map<String, Object> getXhpcPlaceholderDetail(Long placeholderId) {

        Map<String, Object> map = xhpcPlaceholderMapper.getXhpcPlaceholderDetail(placeholderId);

        if(map !=null && map.get("placeholderId") !=null){
            List<Map<String, Object>> xhpcPlaceholderTimeList = xhpcPlaceholderMapper.getXhpcPlaceholderTimeList(placeholderId);
            map.put("xhpcPlaceholderTimeList",xhpcPlaceholderTimeList);
        }
        return map;
    }

    @Override
    public R updateXhpcPlaceholder(XhpcPlaceholderDto xhpcPlaceholder) {
        Long chargingStationId =xhpcPlaceholder.getChargingStationId();
        //查询场站是否存在
        int num = xhpcPlaceholderMapper.getXhpcPlaceholderChargingStationId(chargingStationId,2,xhpcPlaceholder.getPlaceholderId());
        if(num>0){
            return R.fail("1003", "该场站已存在，请进行编辑");
        }
        int k = xhpcPlaceholderMapper.updateXhpcPlaceholder(xhpcPlaceholder);
        if(k>0){
            Long placeholderId = xhpcPlaceholder.getPlaceholderId();
            //删除之前所有的时间段，添加新的时间段
            xhpcPlaceholderMapper.updateXhpcPlaceholderTime(placeholderId);
            //添加时段段
            List<XhpcPlaceholderTimeDto> list = xhpcPlaceholder.getXhpcPlaceholderTimeList();

            //判断是否有重叠
            for (int i = 0; i < list.size(); i++) {
                XhpcPlaceholderTimeDto xhpcRateTimeOne = list.get(i);
                Date startOne = DateUtil.parse(xhpcRateTimeOne.getStartTime());
                Date endOne = DateUtil.parse(xhpcRateTimeOne.getEndTime());
                for (int j = i + 1; j < list.size(); j++) {
                    XhpcPlaceholderTimeDto xhpcRateTimeTwo = list.get(j);
                    Date startTwo = DateUtil.parse(xhpcRateTimeTwo.getStartTime());
                    Date endTwo = DateUtil.parse(xhpcRateTimeTwo.getEndTime());
                    if (DateUtil.compare(startOne, endTwo) < 0 && DateUtil.compare(startTwo, endOne) < 0) {
                        return R.fail("1004", "时间段有重叠");
                    }
                }
            }

            for (int n = 0; n <list.size() ; n++) {
                XhpcPlaceholderTimeDto xhpcPlaceholderTimeDto = list.get(n);
                String start = xhpcPlaceholderTimeDto.getStartTime();
                String end = xhpcPlaceholderTimeDto.getEndTime();
                String price = xhpcPlaceholder.getPrice();
                String pattern = "^([0-2][0-9]:([0]|[3])[0]:[0][0])";
                Pattern compile = Pattern.compile(pattern);
                Matcher m = compile.matcher(start);
                boolean isMatch = m.matches();
                if (!isMatch) {
                    return R.fail("1003", "时间格式不对");
                }
                Matcher m1 = compile.matcher(end);
                boolean isMatch1 = m1.matches();
                if (!isMatch1) {
                    return R.fail("1003", "时间格式不对");
                }
                //判断结束时间是否小于开始时间
                Date startTime = DateUtil.parse(start);
                Date endTime = DateUtil.parse(end);
                if (startTime.getTime() > endTime.getTime()) {
                    return R.fail("1002", "开始时间不能大于结束时间");
                }

                String rateValue = xhpcPlaceholderTimeDto.getPrice();
                if(list.size() == 1){
                    if(!"00:00:00".equals(xhpcPlaceholderTimeDto.getStartTime())){
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  R.fail("1004", "请填写默认时间段费率");
                        }
                        addXhpcPlaceholderTime("00:00:00",start,price,placeholderId,chargingStationId);
                    }
                    addXhpcPlaceholderTime(start,end,rateValue,placeholderId,chargingStationId);
                    if(!("24:00:00").equals(xhpcPlaceholderTimeDto.getEndTime())) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  R.fail("1004", "请填写默认时间段费率");
                        }
                        addXhpcPlaceholderTime(end,"24:00:00",price,placeholderId,chargingStationId);
                    }
                }else{
                    if(n == 0){
                        if(!"00:00:00".equals(xhpcPlaceholderTimeDto.getStartTime())){
                            if(rateValue ==null || "".equals(rateValue)){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return   R.fail("1004","请填写默认时间段费率");
                            }
                            addXhpcPlaceholderTime("00:00:00",start,price,placeholderId,chargingStationId);
                        }
                        addXhpcPlaceholderTime(start,end,rateValue,placeholderId,chargingStationId);
                    }else if(n < list.size()-1){
                        String endTimeK = list.get(n - 1).getEndTime();
                        if (!endTimeK.equals(start)) {
                            if(rateValue ==null || "".equals(rateValue)){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return   R.fail("1004","请填写默认时间段费率");
                            }
                            addXhpcPlaceholderTime(endTimeK,start,price,placeholderId,chargingStationId);
                        }
                        //并把本条数据也添加上
                        addXhpcPlaceholderTime(start,end,rateValue,placeholderId,chargingStationId);
                    }else{
                        String endTimeK = list.get(n - 1).getEndTime();
                        if (!endTimeK.equals(start)) {
                            if(rateValue ==null || "".equals(rateValue)){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return   R.fail("1004","请填写默认时间段费率");
                            }
                            //添加一条默认费率时段
                            addXhpcPlaceholderTime(endTimeK,start,price,placeholderId,chargingStationId);
                        }
                        //并把本条数据也添加上
                        addXhpcPlaceholderTime(start,end,rateValue,placeholderId,chargingStationId);
                        if (!("24:00:00").equals(xhpcPlaceholderTimeDto.getEndTime())) {
                            if(rateValue ==null || "".equals(rateValue)){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return   R.fail("1004","请填写默认时间段费率");
                            }
                            //添加一条默认费率时段
                            addXhpcPlaceholderTime(end,"24:00:00",price,placeholderId,chargingStationId);
                        }
                    }
                }
            }
        }
        return R.ok("修改成功");
    }

    @Override
    public R installXhpcPlaceholder(XhpcPlaceholderDto xhpcPlaceholder) {

        Long chargingStationId =xhpcPlaceholder.getChargingStationId();
        //查询场站是否存在
        int num = xhpcPlaceholderMapper.getXhpcPlaceholderChargingStationId(chargingStationId,1,null);
        if(num>0){
            return R.fail("1003", "该场站已存在，请进行编辑");
        }
        int k = xhpcPlaceholderMapper.insertXhpcPlaceholder(xhpcPlaceholder);
        if(k>0){
            Long placeholderId = xhpcPlaceholder.getPlaceholderId();
            //删除之前所有的时间段，添加新的时间段
            xhpcPlaceholderMapper.updateXhpcPlaceholderTime(placeholderId);
            //添加时段段
            List<XhpcPlaceholderTimeDto> list = xhpcPlaceholder.getXhpcPlaceholderTimeList();

            //判断是否有重叠
            for (int i = 0; i < list.size(); i++) {
                XhpcPlaceholderTimeDto xhpcRateTimeOne = list.get(i);
                Date startOne = DateUtil.parse(xhpcRateTimeOne.getStartTime());
                Date endOne = DateUtil.parse(xhpcRateTimeOne.getEndTime());
                for (int j = i + 1; j < list.size(); j++) {
                    XhpcPlaceholderTimeDto xhpcRateTimeTwo = list.get(j);
                    Date startTwo = DateUtil.parse(xhpcRateTimeTwo.getStartTime());
                    Date endTwo = DateUtil.parse(xhpcRateTimeTwo.getEndTime());
                    if (DateUtil.compare(startOne, endTwo) < 0 && DateUtil.compare(startTwo, endOne) < 0) {
                        return R.fail("1004", "时间段有重叠");
                    }
                }
            }

            for (int n = 0; n <list.size() ; n++) {
                XhpcPlaceholderTimeDto xhpcPlaceholderTimeDto = list.get(n);
                String start = xhpcPlaceholderTimeDto.getStartTime();
                String end = xhpcPlaceholderTimeDto.getEndTime();
                String price = xhpcPlaceholder.getPrice();
                String pattern = "^([0-2][0-9]:([0]|[3])[0]:[0][0])";
                Pattern compile = Pattern.compile(pattern);
                Matcher m = compile.matcher(start);
                boolean isMatch = m.matches();
                if (!isMatch) {
                    return R.fail("1003", "时间格式不对");
                }
                Matcher m1 = compile.matcher(end);
                boolean isMatch1 = m1.matches();
                if (!isMatch1) {
                    return R.fail("1003", "时间格式不对");
                }
                //判断结束时间是否小于开始时间
                Date startTime = DateUtil.parse(start);
                Date endTime = DateUtil.parse(end);
                if (startTime.getTime() > endTime.getTime()) {
                    return R.fail("1002", "开始时间不能大于结束时间");
                }

                String rateValue = xhpcPlaceholderTimeDto.getPrice();
                if(list.size() == 1){
                    if(!"00:00:00".equals(xhpcPlaceholderTimeDto.getStartTime())){
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  R.fail("1004", "请填写默认时间段费率");
                        }
                        addXhpcPlaceholderTime("00:00:00",start,price,placeholderId,chargingStationId);
                    }
                    addXhpcPlaceholderTime(start,end,rateValue,placeholderId,chargingStationId);
                    if(!("24:00:00").equals(xhpcPlaceholderTimeDto.getEndTime())) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  R.fail("1004", "请填写默认时间段费率");
                        }
                        addXhpcPlaceholderTime(end,"24:00:00",price,placeholderId,chargingStationId);
                    }
                }else{
                    if(n == 0){
                        if(!"00:00:00".equals(xhpcPlaceholderTimeDto.getStartTime())){
                            if(rateValue ==null || "".equals(rateValue)){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return   R.fail("1004","请填写默认时间段费率");
                            }
                            addXhpcPlaceholderTime("00:00:00",start,price,placeholderId,chargingStationId);
                        }
                        addXhpcPlaceholderTime(start,end,rateValue,placeholderId,chargingStationId);
                    }else if(n < list.size()-1){
                        String endTimeK = list.get(n - 1).getEndTime();
                        if (!endTimeK.equals(start)) {
                            if(rateValue ==null || "".equals(rateValue)){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return   R.fail("1004","请填写默认时间段费率");
                            }
                            addXhpcPlaceholderTime(endTimeK,start,price,placeholderId,chargingStationId);
                        }
                        //并把本条数据也添加上
                        addXhpcPlaceholderTime(start,end,rateValue,placeholderId,chargingStationId);
                    }else{
                        String endTimeK = list.get(n - 1).getEndTime();
                        if (!endTimeK.equals(start)) {
                            if(rateValue ==null || "".equals(rateValue)){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return   R.fail("1004","请填写默认时间段费率");
                            }
                            //添加一条默认费率时段
                            addXhpcPlaceholderTime(endTimeK,start,price,placeholderId,chargingStationId);
                        }
                        //并把本条数据也添加上
                        addXhpcPlaceholderTime(start,end,rateValue,placeholderId,chargingStationId);
                        if (!end.equals("24:00:00")) {
                            if(rateValue ==null || "".equals(rateValue)){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return   R.fail("1004","请填写默认时间段费率");
                            }
                            //添加一条默认费率时段
                            addXhpcPlaceholderTime(end,"24:00:00",price,placeholderId,chargingStationId);
                        }
                    }
                }
            }
        }else{
            return R.fail("添加失败");
        }
        return R.ok("添加成功");
    }

    @Override
    public R removeXhpcPlaceholderById(HttpServletRequest request,XhpcPlaceholderDto xhpcPlaceholder) {

        int i = xhpcPlaceholderMapper.updateXhpcPlaceholder(xhpcPlaceholder);
        if(i>0){
            //删除之前所有的时间段，添加新的时间段
            xhpcPlaceholderMapper.updateXhpcPlaceholderTime(xhpcPlaceholder.getPlaceholderId());
        }
        return R.ok("修改成功");
    }

    private void addXhpcPlaceholderTime(String startTime,String endTime,String price,Long placeholderId,Long chargingStationId){
        XhpcPlaceholderTime xhpcPlaceholderTime =new XhpcPlaceholderTime();
        Date start = DateUtil.parse(startTime);
        Date emd = DateUtil.parse(endTime);
        xhpcPlaceholderTime.setStartTime(start);
        xhpcPlaceholderTime.setEndTime(emd);
        xhpcPlaceholderTime.setPrice(new BigDecimal(price));
        xhpcPlaceholderTime.setPlaceholderId(placeholderId);
        xhpcPlaceholderTime.setChargingStationId(chargingStationId);
        xhpcPlaceholderMapper.insertXhpcPlaceholderTime(xhpcPlaceholderTime);
    }

}
