package cn.cecep.talroad.service.impl;

import cn.cecep.talroad.common.core.domain.R;
import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.*;
import cn.cecep.talroad.enums.OperationTypeEnum;
import cn.cecep.talroad.feign.BaseRegionService;
import cn.cecep.talroad.mapper.BasDeviceSiteCoordinateOperationLogMapper;
import cn.cecep.talroad.mapper.BasDeviceSiteMapper;
import cn.cecep.talroad.service.IBasDeviceSiteService;
import cn.cecep.talroad.service.IMonElecOperationLogService;
import cn.cecep.talroad.system.api.domain.SysUser;
import cn.cecep.talroad.vo.BasDeviceSiteExcelVo;
import cn.cecep.talroad.vo.BasDeviceSiteVo;
import cn.cecep.talroad.vo.EChartsVO;
import cn.cecep.talroad.vo.MAmVideoDevFiVo;
import cn.cecep.talroad.vo.export.BasDeviceSiteExport;
import cn.cecep.talroad.vo.query.BasDeviceSiteQuery;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class BasDeviceSiteServiceImpl extends ServiceImpl<BasDeviceSiteMapper, BasDeviceSite> implements IBasDeviceSiteService {
    @Autowired
    private BasDeviceSiteMapper basDeviceSiteMapper;

    @Autowired
    private IMonElecOperationLogService monElecOperationLogService;

    @Autowired
    @Qualifier("baseRegionService")
    private BaseRegionService baseRegionService;

    @Override
    public List<BasDeviceSiteExcelVo> selectExportBasDeviceList(BasDeviceSite basDeviceSite) {
        return basDeviceSiteMapper.selectExportBasDeviceList(basDeviceSite);
    }


    @Override
    @Transactional
    public void editBatch(BasDeviceSiteVo[] basDeviceSiteVoArr) {
        List<BasDeviceSiteVo> basDeviceSiteVoList = Arrays.asList(basDeviceSiteVoArr);
        //赋值
        List<BasDeviceSite> basDeviceSiteList = new ArrayList<>();
        basDeviceSiteVoList.forEach(e -> {
            BasDeviceSite basDeviceSite = new BasDeviceSite();
            BeanUtil.copyProperties(e, basDeviceSite);
            basDeviceSiteList.add(basDeviceSite);
        });

        //记录操作日志
        List<MonElecOperationLog> mAmVideoCoordinateOperationLogList = new ArrayList<>();
        basDeviceSiteList.forEach(e -> {
            MonElecOperationLog monElecOperationLog = new MonElecOperationLog();

            BasDeviceSite basDeviceSite = this.getById(e.getId());
            String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
            monElecOperationLog.setLogId(uuid);
            monElecOperationLog.setFactoryId(basDeviceSite.getFactoryId());
            monElecOperationLog.setOperationTime(DateUtils.parseFormatDate("yyyy-MM-dd HH:mm:ss", new Date()));
//            monElecOperationLog.setOperationStatus(OperationTypeEnum.UPDATE_OPERATION.getName());
            monElecOperationLog.setOperator(SecurityUtils.getLoginUser().getSysUser().getUserName());
            monElecOperationLog.setOperatorId(SecurityUtils.getLoginUser().getSysUser().getUserId() + "");
            monElecOperationLog.setElecStationName(basDeviceSite.getName());
            monElecOperationLog.setDeviceName(basDeviceSite.getEquipName());
            monElecOperationLog.setBeforeModifyNormal(basDeviceSite.getNormalValue());
            monElecOperationLog.setAfterModifyNormal(e.getNormalValue());
            mAmVideoCoordinateOperationLogList.add(monElecOperationLog);

        });
        this.updateBatchById(basDeviceSiteList);
        monElecOperationLogService.saveBatch(mAmVideoCoordinateOperationLogList);
    }

    @Override
    public BasDeviceSiteVo.CountOverview getCountOverview() {
        String userRegionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();

        if (StringUtils.isEmpty(userRegionCode)) {
            return new BasDeviceSiteVo.CountOverview();
        }

        R<List<String>> r = baseRegionService.getRegionCodeListChild(userRegionCode);
        if (r.getCode() == R.SUCCESS) {
            BasDeviceSiteVo.CountOverview countOverview = basDeviceSiteMapper.selectCountOverview(r.getData());
            return countOverview;
        } else {
            return new BasDeviceSiteVo.CountOverview();
        }
    }

    @Override
    public EChartsVO getScatterChart(String type) {
        EChartsVO.SeriesObj ser = new EChartsVO.SeriesObj();
        ser.setName("分表计电点位分布");

        EChartsVO chartsVO = new EChartsVO();
        chartsVO.setSeries(Arrays.asList(ser));

        String userRegionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
        if (StringUtils.isEmpty(userRegionCode)) {
            return chartsVO;
        }
        R<List<String>> r = baseRegionService.getRegionCodeListChild(userRegionCode);
        if (r.getCode() != R.SUCCESS) {
            return chartsVO;
        }
        List<Map<String, Object>> dataList = basDeviceSiteMapper.selectScatterChart(type, r.getData());
        ser.setValues(dataList.stream().map(o -> o.get("count")).collect(Collectors.toList()));
        chartsVO.setXData(dataList.stream().map(o -> (String) o.get("name")).collect(Collectors.toList()));
        return chartsVO;
    }

    @Autowired
    BasDeviceSiteCoordinateOperationLogMapper basDeviceSiteCoordinateOperationLogMapper;

    @Override
    public IPage<BasDeviceSiteExport> selectDeviceNameById(Page<BasDeviceSite> page, QueryWrapper<BasDeviceSite> queryWrapper) {
        return basDeviceSiteMapper.selectDeviceNameById(page, queryWrapper);
    }

    @Override
    public List<BasDeviceSiteExport> selectBasDeviceSiteExportList(QueryWrapper<BasDeviceSite> queryWrapper) {
        return basDeviceSiteMapper.selectBasDeviceSiteExportList(queryWrapper);
    }
    @Override
    public List<BasDeviceSiteExport> selectBasDeviceSiteExportListT(QueryWrapper<BasDeviceSite> queryWrapper) {
        return basDeviceSiteMapper.selectBasDeviceSiteExportListT(queryWrapper);
    }
    @Override
    public List<BasDeviceSiteExport> selectBasDeviceList(QueryWrapper<BasDevice> queryWrapper) {
        return basDeviceSiteMapper.selectBasDeviceList(queryWrapper);
    }

    @Override
    public BasDeviceSiteExport getByExport(String id) {
        return basDeviceSiteMapper.getByExport(id);
    }

    @Override
    public void saveLog(List<BasDeviceSiteExport> basDeviceSiteVo, List<BasDeviceSiteExport> saveExportList) {
        List<BasDeviceSiteCoordinateOperationLog> list = new ArrayList<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        Date date = new Date();
        for (int i = 0; i < saveExportList.size(); i++) {
            BasDeviceSiteCoordinateOperationLog maioLog = new BasDeviceSiteCoordinateOperationLog();
            maioLog.setLogId(UUID.randomUUID().toString().trim().replaceAll("-", ""));
            maioLog.setOperationTime(DateUtils.parseFormatDate("yyyy-MM-dd HH:mm:ss", date));
            //旧数据
            maioLog.setElecStationName(saveExportList.get(i).getName());
            maioLog.setDeviceName(saveExportList.get(i).getDeviceName());
            if (saveExportList.get(i).getDeviceType() == null) {
                maioLog.setType("生产设施");
            } else {
                maioLog.setType(saveExportList.get(i).getDeviceType());
            }
            maioLog.setBeforeModifyLng(saveExportList.get(i).getPointLng());
            maioLog.setBeforeModifyLag(saveExportList.get(i).getPointLat());

            String sta = "";
            if(!org.apache.commons.lang3.StringUtils.isEmpty(saveExportList.get(i).getDeviceId()) && !org.apache.commons.lang3.StringUtils.isEmpty(basDeviceSiteVo.get(i).getDeviceId())){
                sta = OperationTypeEnum.UPDATE_OPERATION.getName();
            }else  if(!org.apache.commons.lang3.StringUtils.isEmpty(saveExportList.get(i).getDeviceId()) && org.apache.commons.lang3.StringUtils.isEmpty(basDeviceSiteVo.get(i).getDeviceId())){
                sta = OperationTypeEnum.DELETE_OPERATION.getName();
            }else{
                sta = OperationTypeEnum.INSERT_OPERATION.getName();
            }
            // 操作状态
            maioLog.setOperationStatus(sta);
            // 修改后对应许可证生产设施编号
            maioLog.setAfterModifyLng(basDeviceSiteVo.get(i).getPointLng());
            // 修改后对应许可证生产设施名称
            maioLog.setAfterModifyLag(basDeviceSiteVo.get(i).getPointLat());
            // 操作人
            maioLog.setOperator(sysUser.getNickName());
            // 操作人ID
            maioLog.setOperatorId(String.valueOf(sysUser.getUserId()));
            // 企业ID
            maioLog.setFactoryId(saveExportList.get(i).getFactoryId());
            list.add(maioLog);
        }
        basDeviceSiteCoordinateOperationLogMapper.batchInsert(list);
    }

    @Override
    public IPage<BasDeviceSiteCoordinateOperationLog> getBasDeviceSiteCoordinateOperationLogList(BasDeviceSiteQuery basDeviceSite) {
        Page<BasDeviceSiteCoordinateOperationLog> page = new Page<>(basDeviceSite.getPageNum(), basDeviceSite.getPageSize());
        List<BasDeviceSiteCoordinateOperationLog> list = basDeviceSiteCoordinateOperationLogMapper.selectListByParam(page, basDeviceSite,
                org.apache.commons.lang3.StringUtils.isEmpty(basDeviceSite.getStartTime()) ? null : Timestamp.valueOf(basDeviceSite.getStartTime()),
                org.apache.commons.lang3.StringUtils.isEmpty(basDeviceSite.getEndTime()) ? null : Timestamp.valueOf(basDeviceSite.getEndTime()));
        page.setRecords(list);
        return page;
    }
}
