package com.casic.missiles.modular.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.casic.missiles.core.application.context.AbstractPermissionContext;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.modular.system.dao.ThirdPartyDataMapper;
import com.casic.missiles.modular.system.enums.DeviceDataTableEnum;
import com.casic.missiles.modular.system.model.GasDectorDataDto;
import com.casic.missiles.modular.system.model.PantiltDataDto;
import com.casic.missiles.modular.system.service.ThirdPartyDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class ThirdPartyDataServiceImpl implements ThirdPartyDataService {

    private final ThirdPartyDataMapper thirdPartyMapper;
    private final AbstractPermissionContext permissionService;

    public ThirdPartyDataServiceImpl(ThirdPartyDataMapper thirdPartyMapper, AbstractPermissionContext permissionService) {
        this.thirdPartyMapper = thirdPartyMapper;
        this.permissionService = permissionService;
    }

    @Override
    public ResponseData getGasDectorListPage(Page<GasDectorDataDto> page, DataScope dataScope,
                                             String deptid, String endTime, String beginTime, String keyWords) {
        ResponseData responseData = new ResponseData();
        try {
            List<GasDectorDataDto> gasDectorDataDtoList = thirdPartyMapper.getGasDectorListPage(page, dataScope,  StrUtil.isEmpty(deptid)?-1:Long.valueOf(deptid), endTime, beginTime, keyWords);
            gasDectorDataDtoList.forEach(gasDectorDataDto -> {
                gasDectorDataDto.setDeptName(permissionService.getDeptService().getDeptName(gasDectorDataDto.getDeptid()));
            });
            page.setRecords(gasDectorDataDtoList);
            responseData.setData(page);
            responseData.setMessage("查询成功");
            responseData.setCode(200);
        } catch (DataAccessException dex) {
            log.error("主题：查询燃气探测仪设备数据出现数据异常,部门编号{},关键字{},异常信息{}", deptid, keyWords, dex);
            responseData.setMessage("查询异常");
            responseData.setCode(500);
        }
        return responseData;
    }

    @Override
    public ResponseData getPantiltDataListPage(Page<PantiltDataDto> page, DataScope dataScope,
                                               String deptid, String endTime, String beginTime, String keyWords) {
        ResponseData responseData = new ResponseData();
        try {
            List<PantiltDataDto> pantiltDtoList = thirdPartyMapper.getPantiltDataListPage(page, dataScope,  StrUtil.isEmpty(deptid)?-1:Long.valueOf(deptid), endTime, beginTime, keyWords);
            page.setRecords(pantiltDtoList);
            responseData.setData(page);
            responseData.setMessage("查询成功");
            responseData.setCode(200);
        } catch (DataAccessException dex) {
            log.error("主题：查询燃气探测仪设备数据出现数据异常,部门编号{},关键字{},异常信息{}", deptid, keyWords, dex);
            responseData.setMessage("查询异常");
            responseData.setCode(500);
        }
        return responseData;
    }


    /**
     * （1）权限查询,查出所属部门的权限
     * （2）根据权限范围，遍利表
     * （3）封装结果
     *
     * @return
     */
    public ResponseData countThirdPartyData(DataScope dataScope, String endTime, String beginTime) {
        ResponseData responseData = new ResponseData();
        try {
            Long deptId = permissionService.getAuthService().getLoginUser().getDeptId();
            String deviceTypes = thirdPartyMapper.getDeviceType(deptId);
            List<Map<String, String>> result = countThirdRecord(dataScope, deviceTypes, beginTime, endTime);
            responseData.setData(result);
            responseData.setMessage("查询成功");
            responseData.setCode(200);
        } catch (DataAccessException dex) {
            log.error("主题：查询历史设备数据出现数据异常,开始时间：{},结束时间{},异常信息{}", beginTime, endTime, dex);
            responseData.setMessage("查询异常");
            responseData.setCode(500);
        }
        return responseData;
    }

    /**
     * （1）权限查询,查出所属部门的权限
     * （2）根据权限范围，遍利表,时间限制为今天
     * （3）封装结果
     *
     * @return int 数据条数
     */
    public ResponseData countThirdPartyDataToday(DataScope dataScope) {
        ResponseData responseData = new ResponseData();
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String today = formatter.format(date);
        String beginTime = today + " 00:00:00";
        String endTime = today + " 23:59:59";
        try {
            Long deptId = permissionService.getAuthService().getLoginUser().getDeptId();//根绝当前角色获取所在部门
//            String deviceTypes = thirdPartyMapper.getDeviceType(deptId);    //根据所在部门获取已授权的设备类型
//            List<String> deviceList = new ArrayList<>();
//            //转化为列表类型
//            for (Object deviceType : JSON.parseObject(deviceTypes, List.class)) {
//                deviceList.add(deviceType.toString());
//          }
            int num = thirdPartyMapper.countRecordsToday(dataScope, endTime, beginTime); //
            responseData.setData(num);
            responseData.setMessage("查询成功");
            responseData.setCode(200);
        } catch (DataAccessException dex) {
            log.error("主题：查询燃气探测仪设备数据出现数据异常,开始时间：{},结束时间{},异常信息{}", beginTime, endTime, dex);
            responseData.setMessage("查询异常");
            responseData.setCode(500);
        }
        return responseData;
    }

    private List<Map<String, String>> countThirdRecord(DataScope dataScope, String deviceTypes, String beginTime, String endTime) {
        List<Map<String, String>> countRecordList = new ArrayList<>();
        HashMap<String, String> countRecords = null;
        for (Object deviceType : JSON.parseObject(deviceTypes, List.class)) {
            countRecords = new HashMap<>();
            Integer typeId = Integer.valueOf(deviceType.toString());
            DeviceDataTableEnum deviceDataTableEnum = DeviceDataTableEnum.DEVICE_TYPE_TABLE.getTableNameMap().get(typeId);
            if (deviceDataTableEnum == null) {
                continue;
            }
            String tableName = deviceDataTableEnum.getTableName();
            Map<String, Object> recordCounts = thirdPartyMapper.countRecordsByTime(dataScope, beginTime, endTime, tableName);
            countRecords.put("countRecords", recordCounts == null || recordCounts.get("recodCounts") == null ? "0" : recordCounts.get("recodCounts").toString());
            countRecords.put("deviceName", DeviceDataTableEnum.DEVICE_TYPE_TABLE.getTableNameMap().
                    get(Integer.valueOf(deviceType.toString())).getTypeName());
            countRecordList.add(countRecords);
        }
        return countRecordList;
    }

}
