package com.xhpc.activity.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xhpc.common.core.exception.CustomException;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.activity.domain.XhpcStationDeviceDomain;
import com.xhpc.activity.domain.XhpcWorkStationDomain;
import com.xhpc.activity.mapper.XhpcStationDeviceMapper;
import com.xhpc.activity.mapper.XhpcWorkStationMapper;
import com.xhpc.activity.service.WorkStationService;
import com.xhpc.activity.vo.XhpcStationDeviceVo;
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.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class WorkStationServiceImpl extends BaseService implements WorkStationService {

    @Resource
    XhpcStationDeviceMapper deviceMapper;

    @Resource
    XhpcWorkStationMapper stationMapper;

    @Resource
    RedisService redisService;
    @Autowired
    private TokenService tokenService;

    private int getTerminalStatus(String serialNumber) {
        //0离线 1故障 2空闲 3充电 4 已插枪 5未知
        // Integer status =5;
        //终端状态用 redis数据
        if(!"".equals(serialNumber) && serialNumber!=null){
            Map<String, Object> cacheMap =redisService.getCacheMap("gun:"+serialNumber);
            if(cacheMap !=null && cacheMap.get("status") !=null){
                if ("离线".equals(cacheMap.get("status").toString())){
                    return 0;
                }else if("故障".equals(cacheMap.get("status").toString())){
                    return 1;
                }else if("空闲".equals(cacheMap.get("status").toString()) || "插枪".equals(cacheMap.get("status").toString())){
                    if("是".equals(cacheMap.get("vehicleGunStatus").toString())){
                        return 4;
                    }else{
                        return 2;
                    }
                }else{
                    //充电桩
                    return 3;
                }
            }
            return 5;
        }else{
            return 5;
        }
    }



    @Override
    public List<Map<String, Object>> getStationDevice(Map<String, Object> params){
        LoginUser loginUser = tokenService.getLoginUser();
        Long sysUserId = loginUser.getUserid();
        List<Map<String, Object>> deviceList = new ArrayList<>();
        SysUser sysUser = loginUser.getSysUser();
        //获取登陆用户
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                params.put("type", 1);
                params.put("userId", logOperatorId);

                //运营商看自己的场站
                deviceList =deviceMapper.selectStationGunDeviceListByParams(params);
            }else{
                params.put("type", 2);
                params.put("userId", sysUserId);
                //查询赋值的场站
                deviceList=deviceMapper.selectStationGunDeviceListByParams(params);
            }
        }else{
            params.put("type", 0);
            params.put("userId", sysUserId);
            deviceList=deviceMapper.selectStationGunDeviceListByParams(params);
        }
        for(Map<String, Object> map : deviceList){
            //状态
            int pileSerialNumber = getTerminalStatus(map.get("gunSerialNumber").toString());
            map.put("workStatus",pileSerialNumber);
        }
        return deviceList;
    }


    @Override
    public List<Map<String, Object>> getStationDeviceByParent(Map<String, Object> params){
        return deviceMapper.selectListByParent(params);
    }


    @Override
    public List<XhpcWorkStationDomain> getStationList(Map<String, Object> params){
        LoginUser loginUser = tokenService.getLoginUser();
        Long sysUserId = loginUser.getUserid();
        List<Map<String, Object>> list = new ArrayList<>();
        SysUser sysUser = loginUser.getSysUser();
        //获取登陆用户
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                params.put("type", 1);
                params.put("userId", logOperatorId);

                //运营商看自己的场站
                return stationMapper.selectListByParams(params);
            }else{
                params.put("type", 2);
                params.put("userId", sysUserId);
                //查询赋值的场站
                return stationMapper.selectListByParams(params);
            }
        }else{
            params.put("type", 0);
            params.put("userId", sysUserId);
            return stationMapper.selectListByParams(params);
        }
    }


    @Override
    public List<Map<String, Object>> getStationDeviceTree(Map<String, Object> params){
        Map<String, Object> stationParams = new HashMap<>();
        stationParams.put("name", params.get("stationName"));
        stationParams.put("tenantId", params.get("tenantId"));
        stationParams.put("status", 0);
        stationParams.put("delFlag", 0);

        List<Map<String, Object>> stationDomainList = stationMapper.selectMapListByParams(stationParams);
        for (Map<String, Object> stationMap: stationDomainList){
                params.put("stationName", stationMap.get("name"));
            List<Map<String, Object>> resultData = deviceMapper.selectStationGunDeviceTreeByParams(params);
            for (Map<String, Object> resultMap: resultData){
                List<Map<String, Object>> childData = deviceMapper.selectStationGunDeviceTreeByParent(resultMap.get("id").toString());
                if(childData != null){
                    resultMap.put("children", childData);
                }
            }
            stationMap.put("children", resultData);
        }
        return stationDomainList;
    }


    @Override
    public String importDevice(List<XhpcStationDeviceDomain> deviceDomainList, Boolean updateSupport){

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (XhpcStationDeviceDomain domain: deviceDomainList){
            if (StringUtils.isEmpty(domain.getStationName())){
                failureNum ++;
                failureMsg.append("<br/>电站名称: ").append(domain.getStationName()).append(" ,设备编码: ").append(domain.getSerialNumber()).append(" 导入失败; 失败原因: 场站名称为空。");
                continue;
            }
            XhpcWorkStationDomain stationDomain = stationMapper.selectByName(domain.getStationName());
            if (stationDomain == null){
                failureNum ++;
                failureMsg.append("<br/>电站名称: ").append(domain.getStationName()).append(" ,设备编码: ").append(domain.getSerialNumber()).append(" 导入失败; 失败原因: 场站未找到。");
                continue;
            } else {
                domain.setDeviceId(stationDomain.getWorkStationId());
            }
            if(!StrUtil.hasBlank(domain.getParentSerialNumber())){
                XhpcStationDeviceDomain parentDomain = deviceMapper.selectStationGunDeviceBySerialNumber(domain.getParentSerialNumber());
                if(parentDomain != null){
                    domain.setParentDeviceId(parentDomain.getDeviceId());
                }
            }

            deviceMapper.insertSelective(domain);
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    @Override
    public Map<String, Object> getDeviceDetail(Long deviceId){
        return deviceMapper.selectByDeviceId(deviceId);
    }


    @Override
    public Boolean insertDevice(XhpcStationDeviceDomain domain) throws Exception{

        if ("".equals(domain.getStationName())){
            throw new Exception("所属场站不能为空");
        }
        XhpcWorkStationDomain stationDomain = stationMapper.selectByName(domain.getStationName());
        if (stationDomain == null){
            throw new Exception("所属场站不存在");
        } else {
            domain.setDeviceId(stationDomain.getWorkStationId());
        }
        if(!StrUtil.hasBlank(domain.getParentSerialNumber())){
            XhpcStationDeviceDomain parentDomain = deviceMapper.selectStationGunDeviceBySerialNumber(domain.getParentSerialNumber());
            if(parentDomain != null){
                domain.setParentDeviceId(parentDomain.getDeviceId());
            }
        }
        deviceMapper.insertSelective(domain);
        return true;
    }


    @Override
    public Boolean insertSimpleDevice(XhpcStationDeviceVo vo) throws Exception{

        if(StringUtils.isEmpty(vo.getParentDeviceId())){
            // 增加的场站
            XhpcWorkStationDomain stationDomain = new XhpcWorkStationDomain();
            stationDomain.setName(vo.getDeviceName());
            stationDomain.setTenantId(vo.getTenantId());
            stationDomain.setCreateBy(vo.getUserId());
            stationDomain.setUpdateBy(vo.getUserId());

            stationMapper.insertSelective(stationDomain);
        } else {
            XhpcStationDeviceDomain deviceDomain = new XhpcStationDeviceDomain();
            deviceDomain.setDeviceName(vo.getDeviceName());
            deviceDomain.setCreateBy(vo.getUserId());
            deviceDomain.setUpdateBy(vo.getUserId());

            deviceMapper.insertSelective(deviceDomain);
        }

        return true;
    }


    @Override
    public Boolean updateDevice(XhpcStationDeviceDomain domain){
        deviceMapper.updateByPrimaryKeySelective(domain);
        return true;
    }


    @Override
    public Boolean deleteDevice(Long deviceId) throws Exception {
        XhpcStationDeviceDomain deviceDomain = deviceMapper.selectByPrimaryKey(deviceId);
        if(deviceDomain != null){
            throw new Exception("设备不存在");
        }
        deviceMapper.deleteByPrimaryKey(deviceId);
        return true;
    }
}
