package com.xhpc.charging.station.service;

import com.xhpc.charging.station.mapper.XhpcChargingPileMapper;
import com.xhpc.charging.station.mapper.XhpcChargingStationMapper;
import com.xhpc.charging.station.mapper.XhpcImgMapper;
import com.xhpc.charging.station.mapper.XhpcTerminalMapper;
import com.xhpc.charging.station.utils.img.QrImgUtils;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.domain.XhpcChargingPile;
import com.xhpc.common.domain.XhpcTerminal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author yuyang
 * @date 2021/7/27 14:36
 */
@Service
public class XhpcChargingPileServiceImpl implements IXhpcChargingPileService {

    @Autowired
    private XhpcChargingPileMapper xhpcChargingPileMapper;
    @Autowired
    private XhpcTerminalMapper xhpcTerminalMapper;
    @Autowired
    private PowerPileService powerPileService;

    @Autowired
    private Environment environment;
    @Autowired
    private XhpcImgMapper xhpcImgMapper;
    @Autowired
    private IXhpcChargingStationService xhpcChargingStationService;

    //字母集合
    private static Map letterMap;
    static{
        Character letter = 'A';
        letterMap = new HashMap<Integer,Character>();
        for (int i = 1;i<=26;i++){
            letterMap.put(i, letter);
            letter++;
        }
    }



    /**
     * 桩列表
     *
     * @param serialNumber 桩编号
     * @param type         桩类型
     * @param name         桩名称
     * @return
     */
    @Override
    public List<Map<String, Object>> selectXhpcChargingPileList(String name, Integer type, String serialNumber, Long chargingStationId) {

        //获取登陆用户

        Long userId = SecurityUtils.getUserId();
        //桩的统计、该时段金额
        List<Map<String, Object>> list =new ArrayList<>();
        if(userId !=1) {
            Map<String, Object> landUser = xhpcChargingStationService.getLandUser(userId);
            if(landUser !=null){
                if(landUser.get("userType") !=null){
                    if("01".equals(landUser.get("userType").toString())){
                        Long operatorId = Long.valueOf(landUser.get("operatorId").toString());
                        list= xhpcChargingPileMapper.selectXhpcChargingPileList(name, type, serialNumber, chargingStationId,operatorId,1);
                    }else{
                        list= xhpcChargingPileMapper.selectXhpcChargingPileList(name, type, serialNumber, chargingStationId,userId,2);
                    }
                }
            }
        }else{
            list= xhpcChargingPileMapper.selectXhpcChargingPileList(name, type, serialNumber, chargingStationId,userId,0);
        }


        return list;
    }

    @Override
    @Transactional
    public AjaxResult addXhpcChargingPile(XhpcChargingPile xhpcChargingPile) {

        if(xhpcChargingPile.getGunNumber() ==null || xhpcChargingPile.getGunNumber()>26){
            return AjaxResult.error("终端数量不能大于26");
        }
        if(xhpcChargingPile.getSerialNumber() ==null || xhpcChargingPile.getSerialNumber().length()!=14){
            return AjaxResult.error("桩编号14位");
        }
      Long chargingStationId = xhpcChargingPile.getChargingStationId();
        //获取计费模型id
        Map<String, Object> stringObjectMap = xhpcChargingPileMapper.selectXhpcChargingStationById(chargingStationId);
        Long rateModelId = Long.parseLong(StringUtils.valueOf(stringObjectMap.get("rateModelId")));
        xhpcChargingPile.setRateModelId(rateModelId);
        String serialNumber = xhpcChargingPile.getSerialNumber();
        xhpcChargingPile.setCreateTime(new Date());
        //判断桩编号是否重复
        int count = xhpcChargingPileMapper.getXhpcChargingPileSerialNumberCount(serialNumber);
        if (count > 0) {
            return AjaxResult.error("桩编号重复");
        }
        //桩
        xhpcChargingPileMapper.addXhpcChargingPile(xhpcChargingPile);
        //终端
        Long chargingPileId = xhpcChargingPile.getChargingPileId();

        if (xhpcChargingPile.getGunNumber() > 0) {
            int number = xhpcChargingPileMapper.countXhpcTerminal(chargingStationId);
            for (int i = 1; i <= xhpcChargingPile.getGunNumber(); i++) {
                addXhpcTerminal(xhpcChargingPile.getName(), chargingStationId, rateModelId, serialNumber, chargingPileId, i, number + 1, xhpcChargingPile.getConnectorType());
            }
        }

        //插入redis 桩的编号
        HashSet<String> noSet = new HashSet<>();
        noSet.add(serialNumber);
        powerPileService.addPileWhitelist(chargingStationId,xhpcChargingPile.getCommunicationProtocolVersion(), noSet);
        return AjaxResult.success();
    }

    private void addXhpcTerminal(String name, Long chargingStationId, Long rateModelId, String serialNumber, Long chargingPileId, int i, int number, int conType) {

        XhpcTerminal xhpcTerminal = new XhpcTerminal();
        xhpcTerminal.setChargingStationId(chargingStationId);
        xhpcTerminal.setChargingPileId(chargingPileId);
        xhpcTerminal.setName(name + "号桩" + "-" + letterMap.get(i) + "枪");
        if (i > 9) {
            xhpcTerminal.setSerialNumber(serialNumber + i);
        } else {
            xhpcTerminal.setSerialNumber(serialNumber + "0" + i);
        }
        xhpcTerminal.setPileSerialNumber(serialNumber);
        xhpcTerminal.setWorkStatus(2);
        xhpcTerminal.setStatus(0);
        xhpcTerminal.setRateModelId(rateModelId);
        xhpcTerminal.setNumber(number);
        xhpcTerminal.setConnectorType(conType);
        xhpcTerminalMapper.addXhpcTerminal(xhpcTerminal);

        //获取场站名称：

        String chargingStationName = xhpcChargingStationService.selectXhpcChargingStationById(xhpcTerminal.getChargingStationId()).getName();
        //生成最终的完整图片，并上传
        QrImgUtils.uploadImg(xhpcTerminal, xhpcTerminal.getSerialNumber(),environment,xhpcImgMapper,chargingStationName,i,letterMap,name);

    }

    @Override
    @Transactional
    public AjaxResult updateXhpcChargingPile(XhpcChargingPile xhpcChargingPile) {

        Long chargingPileId = xhpcChargingPile.getChargingPileId();
        XhpcChargingPile xhpc = xhpcChargingPileMapper.selectXhpcChargingPileById(chargingPileId);

        if (xhpcChargingPile.getSerialNumber() == null) {
            return AjaxResult.error("桩编号不能为空");
        }
        if (xhpc.getSerialNumber() != xhpc.getSerialNumber()) {
            return AjaxResult.error("桩编号不能编辑");
        }
        if(xhpcChargingPile.getGunNumber() ==null || xhpcChargingPile.getGunNumber()>26){
            return AjaxResult.error("终端数量不能大于26");
        }
        if (!xhpcChargingPile.getGunNumber().equals(xhpc.getGunNumber())) {
            //删除之前的终端
            xhpcChargingPileMapper.updateXhpcTerminal(chargingPileId);
            int number = xhpcChargingPileMapper.countXhpcTerminal(xhpcChargingPile.getChargingStationId());
            String serialNumber = xhpcChargingPile.getSerialNumber();
            Long rateModelId = xhpcChargingPile.getRateModelId();
            Long chargingStationId = xhpcChargingPile.getChargingStationId();
            if (xhpcChargingPile.getGunNumber() > 0) {
                for (int i = 1; i <= xhpcChargingPile.getGunNumber(); i++) {
                    addXhpcTerminal(xhpcChargingPile.getName(), chargingStationId, rateModelId, serialNumber, chargingPileId, i, number + 1, xhpcChargingPile.getConnectorType());
                }
            }
            //插入redis 桩的编号
            HashSet<String> noSet = new HashSet<>();
            noSet.add(serialNumber);
            powerPileService.addPileWhitelist(chargingStationId,xhpcChargingPile.getCommunicationProtocolVersion(), noSet);
        }
        xhpcChargingPileMapper.updaeXhpcChargingPile(xhpcChargingPile);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult selectXhpcChargingPile(Long chargingPileId) {

        XhpcChargingPile xhpc = xhpcChargingPileMapper.selectXhpcChargingPileById(chargingPileId);
        //终端信息
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = xhpcChargingPileMapper.selectXhpcTerminalList(chargingPileId);
        if(list !=null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> listMap =list.get(i);
                int pileSerialNumber = xhpcChargingStationService.getTerminalStatus(listMap.get("serialNumber").toString());
                listMap.put("workStatus",pileSerialNumber);
            }
        }
        map.put("chargingPile", xhpc);
        map.put("terminal", list);
        return AjaxResult.success(map);
    }


    @Override
    @Transactional
    public AjaxResult updateStatus(Long chargingPileId, Integer status) {
        XhpcChargingPile xhpc = xhpcChargingPileMapper.selectXhpcChargingPileById(chargingPileId);
        xhpc.setStatus(status);
        xhpcChargingPileMapper.updaeXhpcChargingPile(xhpc);
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public int updateXhpcChargingPileById(Long chargingPileId) {

        XhpcChargingPile xhpc = xhpcChargingPileMapper.selectXhpcChargingPileById(chargingPileId);
        int i = xhpcChargingPileMapper.updateXhpcChargingPileById(chargingPileId);
        if (i > 0) {
            //删除桩
            Set<String> set = new HashSet<>();
            set.add(xhpc.getSerialNumber());
            powerPileService.deletePileWhitelist(xhpc.getChargingStationId(), set);
            return 1;
        }
        return 0;
    }

    /**
     * 下载对应终端的二维码图片
     * @param terminalIds
     * @return
     */
    @Override
    public List<Map<String,Object>> downloadsTerminalImgs(List<Integer> terminalIds) {
        return xhpcImgMapper.selectImgUrlByTerminal_id(terminalIds);
    }

}
