package com.huimv.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huimv.admin.common.utils.ExcelImportSheet;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.entity.EnergyEnvDevice;
import com.huimv.admin.entity.EnvDevice;
import com.huimv.admin.entity.vo.EnergyUpdateVo;
import com.huimv.admin.mapper.EnergyEnvDeviceMapper;
import com.huimv.admin.service.IEnergyEnvDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-21
 */
@Service
public class EnergyEnvDeviceServiceImpl extends ServiceImpl<EnergyEnvDeviceMapper, EnergyEnvDevice> implements IEnergyEnvDeviceService {
    @Autowired
    private EnergyEnvDeviceMapper energyEnvDeviceMapper;

    @Override
    public Result list(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String pageSize = paramsMap.get("pageSize");
        String pageNo = paramsMap.get("pageNum");
        if (pageSize==null||pageSize=="") {
            pageSize = "10";
        }
        if (pageNo==null||pageNo=="") {
            pageNo = "1";
        }
        QueryWrapper<EnergyEnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        Page<EnergyEnvDevice> page = new Page(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        return new Result(ResultCode.SUCCESS,energyEnvDeviceMapper.selectPage(page, queryWrapper));
    }

    @Override
    public Result add(HttpServletRequest httpServletRequest, EnergyEnvDevice energyEnvDevice) {
        QueryWrapper<EnergyEnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_name", energyEnvDevice.getDeviceName()).eq("farm_id",energyEnvDevice.getFarmId());
        Integer count = energyEnvDeviceMapper.selectCount(queryWrapper);
        if (count>0) {
            return new Result(10001,"设备名称已存在",false);
        }
        queryWrapper.clear();
        queryWrapper.eq("device_code", energyEnvDevice.getDeviceCode()).eq("farm_id",energyEnvDevice.getFarmId());
        Integer count1= energyEnvDeviceMapper.selectCount(queryWrapper);
        if (count1>0) {
            return new Result(10001,"设备id已存在",false);
        }
        queryWrapper.clear();
        queryWrapper.eq("unit_id", energyEnvDevice.getUnitId()).eq("farm_id",energyEnvDevice.getFarmId());
        Integer count2= energyEnvDeviceMapper.selectCount(queryWrapper);
        if (count2>0) {
            return new Result(10001,"该单元已绑定设备",false);
        }
        energyEnvDeviceMapper.insert(energyEnvDevice);
        return new Result(ResultCode.SUCCESS,"添加成功");
    }

    @Override
    public Result edit(HttpServletRequest httpServletRequest,  EnergyEnvDevice energyEnvDevice) {
        String deviceName = energyEnvDevice.getDeviceName();

        QueryWrapper<EnergyEnvDevice> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq(StringUtils.isNotBlank(deviceName),"device_name", deviceName).ne("id",energyEnvDevice.getId()) .eq("farm_id",energyEnvDevice.getFarmId());

        Integer count = energyEnvDeviceMapper.selectCount(queryWrapper1);
        if (count>0) {
            return new Result(10001,"设备名称已存在",false);
        }
        queryWrapper1.clear();
        queryWrapper1.eq("device_code", energyEnvDevice.getDeviceCode()).eq("farm_id",energyEnvDevice.getFarmId()).ne("id",energyEnvDevice.getId());
        Integer count1= energyEnvDeviceMapper.selectCount(queryWrapper1);
        if (count1>0) {
            return new Result(10001,"设备id已存在",false);
        }
        queryWrapper1.clear();
        queryWrapper1.eq("unit_id", energyEnvDevice.getUnitId()).eq("farm_id",energyEnvDevice.getFarmId()).ne("id",energyEnvDevice.getId());
        Integer count2= energyEnvDeviceMapper.selectCount(queryWrapper1);
        if (count2>0) {
            return new Result(10001,"该单元已绑定设备",false);
        }
         energyEnvDeviceMapper.updateById(energyEnvDevice);
        return new Result(ResultCode.SUCCESS);
    }

    @Override
    public Result delete(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String id = paramsMap.get("id");
        QueryWrapper<EnergyEnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("farm_id", farmId);
        energyEnvDeviceMapper.delete(queryWrapper);
        return new Result(ResultCode.SUCCESS,"删除成功");
    }

    @Override
    public Result bandingUnitId(HttpServletRequest httpServletRequest, EnergyEnvDevice envDevice) {
        Integer unitId = envDevice.getUnitId();
        int count = this.count(new QueryWrapper<EnergyEnvDevice>().eq("unit_id", unitId));
        if (count>0){
            return new Result(10001,"绑定失败，该栋舍已有设备",false);
        }
        return new Result(10000,"绑定成功",true);
    }

    @Override
    public Result deviceCount(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        QueryWrapper<EnergyEnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        Integer count = energyEnvDeviceMapper.selectCount(queryWrapper);
        JSONObject jsonObject = new JSONObject();
        if (count == 0) {
            jsonObject.put("DeviceCount", 0);
            jsonObject.put("OnDeviceCount", 0);
            jsonObject.put("OffDeviceCount", 0);
            jsonObject.put("OnDeviceRate", 0);
        } else {
            QueryWrapper<EnergyEnvDevice> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("device_status", 1).eq("farm_id",farmId);
            Integer count1 = energyEnvDeviceMapper.selectCount(queryWrapper1);
            Integer OffDeviceCount = count- count1;
            //创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            //设置精确到小数点后两位
            numberFormat.setMaximumFractionDigits(2);
            String onDeviceRate = numberFormat.format((float)count1 / (float) count* 100) + "%";
            jsonObject.put("DeviceCount", count);
            jsonObject.put("OnDeviceCount", count1);
            jsonObject.put("OffDeviceCount", OffDeviceCount);
            jsonObject.put("OnDeviceRate", onDeviceRate);
        }
        return new Result(ResultCode.SUCCESS, jsonObject);
    }

    @Override
    public Result listDevice(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");
        QueryWrapper<EnergyEnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).eq("remark",type);
        return new Result(ResultCode.SUCCESS,energyEnvDeviceMapper.selectList(queryWrapper));
    }
    @Override
    public Result updateName(HttpServletRequest httpServletRequest, MultipartFile files) throws Exception {
        Map<String, String> map = new HashMap<>();
        //表头与键值对的映射关系
        map.put("序号", "id");
        map.put("确认后区域名称", "name");
        map.put("现场核对表号", "deviceCode");
        try (
                //这里面的对象会自动关闭
                InputStream in = files.getInputStream();
                Workbook workbook = ExcelImportSheet.getTypeFromExtends(in, files.getOriginalFilename())
        ) {

            //根据名称获取单张表对象 也可以使用getSheetAt(int index)获取单张表的对象 获取第一张表
            Sheet sheet = workbook.getSheetAt(0);
            List<EnergyUpdateVo> list = ExcelImportSheet.getListFromExcel(sheet, EnergyUpdateVo.class, map);
            QueryWrapper<EnergyEnvDevice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("remark", 0);
            List<EnergyEnvDevice> envDevices = energyEnvDeviceMapper.selectList(queryWrapper);
            for (EnergyUpdateVo energyUpdateVo : list) {
                if (StringUtils.isNotBlank(energyUpdateVo.getDeviceCode())) {
                    for (EnergyEnvDevice envDevice : envDevices) {
                        if (envDevice.getDeviceCode().equals(energyUpdateVo.getDeviceCode())) {
                            envDevice.setDeviceName(energyUpdateVo.getName());
                            envDevice.setUnitName(energyUpdateVo.getName());
                            energyEnvDeviceMapper.updateById(envDevice);
                        }
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            return new Result(10001, "数据格式异常！", false);
        } finally {
            //写着好看的
        }
        return new Result(10000, "保存成功！", true);
    }
}
