package com.xhpc.charging.station.service;

import cn.hutool.core.date.DateUtil;
import com.xhpc.charging.station.mapper.XhpcTerminalMapper;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.domain.XhpcTerminal;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.LogUserUtils;
import com.xhpc.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 终端Service业务层处理
 *
 * @author yuyang
 * @date 2021-07-20
 */
@Service
public class XhpcTerminalServiceImpl extends BaseService implements IXhpcTerminalService {

    @Autowired
    private XhpcTerminalMapper xhpcTerminalMapper;

    @Autowired
    private IXhpcRateTimeService xhpcRateTimeService;

    @Autowired
    private IXhpcChargingStationService xhpcChargingStationService;
    @Autowired
    private LogUserUtils logUserUtils;

    @Autowired
    private TokenService tokenService;
    /**
     * PC端页面统计
     *
     * @param chargingStationId 电站id
     * @return
     */
    @Override
    public Map<String, Object> countXhpcTerminalWorkStatus(Long chargingStationId) {

        return xhpcTerminalMapper.countXhpcTerminalWorkStatus(chargingStationId);
    }

    @Override
    public List<Map<String, Object>> getXhpcTerminalList(HttpServletRequest request, String serialNumber, Integer type, Integer status, String workStatus, Long chargingStationId) {
        LoginUser logUser = logUserUtils.getLogUser(request);
        startPage();
        List<Map<String, Object>> list = xhpcTerminalMapper.getXhpcTerminalList(serialNumber, type, status, workStatus, chargingStationId,logUser.getTenantId());
        if(list !=null && list.size()>0){
            for (int i = 0; i <list.size() ; i++) {
                Map<String, Object> map = list.get(i);
                //状态
                int pileSerialNumber = xhpcChargingStationService.getTerminalStatus(map.get("serialNumber").toString());
                map.put("workStatus",pileSerialNumber);
            }
        }
        return list;
    }

    @Override
    public AjaxResult updateStatus(Long terminalId, Integer status,String prompt) {

        System.out.println(">>>>>>>>>>terminalId>>>>>>>>>"+terminalId);
        System.out.println(">>>>>>>>>>status>>>>>>>>>"+status);
        xhpcTerminalMapper.updateXhpcTerminal(null,null,null,status,terminalId,prompt);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult updateStatusAll(Long chargingStationId, Integer status,String prompt) {

        System.out.println(">>>>>>>>>>chargingStationId>>>>>>>>>"+chargingStationId);
        System.out.println(">>>>>>>>>>status>>>>>>>>>"+status);
        xhpcTerminalMapper.updateXhpcTerminalAll(null,null,null,status,chargingStationId,prompt);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult selectXhpcTerminalMessage(Long terminalId) {

        XhpcTerminal xhpcTerminal = xhpcTerminalMapper.selectXhpcTerminalById(terminalId);
        return AjaxResult.success(xhpcTerminal);
    }

    @Override
    public AjaxResult updateXhpcTerminalName(Long terminalId, String name, String serialNumber,int connectorType) {

        xhpcTerminalMapper.updateXhpcTerminal(name,serialNumber,connectorType,null,terminalId,null);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult selectXhpcTerminalPileMessage(Long terminalId) {

        Map<String, Object> map = xhpcTerminalMapper.selectXhpcTerminalPileMessage(terminalId);
        if (map != null && map.get("chargingStationId") != null && map.get("serialNumber") != null) {
            Long chargingStationId = Long.parseLong(map.get("chargingStationId").toString());
            //费率时段,先反设置时段，在反默认时段
            List<Map<String, Object>> xhpcRateTimeTypeList = xhpcTerminalMapper.getXhpcRateTimeTypeList(chargingStationId, 1);
            xhpcRateTimeTypeList.addAll(xhpcTerminalMapper.getXhpcRateTimeTypeList(chargingStationId, 2));
            map.put("rateTimeList", xhpcRateTimeTypeList);

            //统计终端（充redis获取终端信息）
            map.putAll(xhpcTerminalMapper.getXhpcRateTimeOrderStatistics(chargingStationId, terminalId));

            if(map.get("chargingDegreeSum")==null || map.get("chargingDegreeSum").toString()==null || "".equals(map.get("chargingDegreeSum").toString())){
                map.put("chargingDegreeSum",0);
            }
            int status = xhpcChargingStationService.getTerminalStatus(map.get("serialNumber").toString());

            map.put("workStatus",status);

            return AjaxResult.success(map);
        }




        return AjaxResult.error("无效终端");
    }

    @Override
    public AjaxResult getWXpNumMessage(String pNum) {

        Map<String, Object> map = xhpcTerminalMapper.getWXpNumMessage(pNum);
        if (map == null || map.get("chargingStationId") == null) {
            return AjaxResult.error(1007, "无效的终端编码");
        }
        String tiem = DateUtil.formatTime(new Date());

        //获取桩的状态
        Long chargingStationId = Long.parseLong(map.get("chargingStationId").toString());
        //HH:mm:ss
        //获取该时段占位费电费
        Map<String, Object> placeholderTime = xhpcTerminalMapper.getPlaceholderTime(tiem, chargingStationId);
        if(placeholderTime !=null){
            map.putAll(placeholderTime);
        }
        Map<String, Object> xhpcRateTime = xhpcRateTimeService.getXhpcRateTime(tiem, chargingStationId);

        LoginUser loginUser = tokenService.getLoginUser();
        if (xhpcRateTime != null) {
            if(loginUser !=null){
                BigDecimal serviceFee =new BigDecimal(xhpcRateTime.get("serviceFee").toString());
                BigDecimal powerFee =new BigDecimal(xhpcRateTime.get("powerFee").toString());
                Map<String, Object> objectMap = xhpcChargingStationService.activityDiscountTime(loginUser.getUserid(), new Date(),loginUser.getUserType(), chargingStationId, loginUser.getTenantId());
                if("1".equals(objectMap.get("state").toString())){
                    if("1".equals(objectMap.get("totalDiscountType").toString())||"3".equals(objectMap.get("totalDiscountType").toString())){
                        BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                        serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                        powerFee = powerFee.subtract(powerFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                        map.put("activityServiceFee", serviceFee);
                        map.put("activityPowerFee", powerFee);
                        map.put("activityMoney", serviceFee.add(powerFee));
                    }else if ("3".equals(objectMap.get("totalDiscountType").toString())){
                        BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                        serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                        map.put("activityServiceFee", serviceFee);
                        map.put("activityPowerFee", powerFee);
                        map.put("activityMoney", serviceFee.add(powerFee));
                    }else{
                        BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                        serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                        map.put("activityServiceFee", serviceFee);
                        map.put("activityPowerFee", powerFee);
                        map.put("activityMoney", serviceFee.add(powerFee));
                    }
                    if(objectMap.get("appletActivityName") !=null && !"".equals(objectMap.get("appletActivityName").toString())){
                        map.put("appletActivityName", objectMap.get("appletActivityName").toString());
                    }else{
                        map.put("appletActivityName", "");
                    }
                    map.put("activityState", 1);
                }
            }else{
                map.put("activityState", 0);
            }
            map.putAll(xhpcRateTime);
        }
        //图片信息
        List<String> imgList = new ArrayList<>();
        if (map.get("imgId") != null && map.get("imgId").toString() != "") {
            String[] split = map.get("imgId").toString().split(",");
            imgList = Arrays.asList(split);
            List<Map<String, Object>> imgLists = xhpcTerminalMapper.getImageList(imgList);
            map.put("imgIdList", imgLists);
        } else {
            map.put("imgIdList", new ArrayList<>());
        }
        return AjaxResult.success(map);
    }

    @Override
    public List<Map<String, Object>> getXhpcPileNameAndStationNameAndTerminalNumList(String terminalSerialNumber, String pileName, String stationName) {

        return xhpcTerminalMapper.getXhpcPileNameAndStationNameAndTerminalNumList(terminalSerialNumber, pileName, stationName);
    }

    @Override
    public List<String> getTerminal(Long chargingStationId,Integer status) {
        return xhpcTerminalMapper.getTerminal(chargingStationId,status);
    }

}
