package com.dsk.monitor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsk.common.core.domain.R;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.helper.LoginHelper;
import com.dsk.common.utils.redis.RedisUtils;
import com.dsk.monitor.domain.dto.PushMonitorInfo;
import com.dsk.monitor.domain.dto.PushMonitorRules;
import com.dsk.monitor.domain.vo.*;
import com.dsk.monitor.mapper.PushMonitorInfoMapper;
import com.dsk.monitor.mapper.PushMonitorRulesMapper;
import com.dsk.monitor.service.MonitorService;
import com.dsk.system.utils.DskOpenApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;

/**
 * @ClassName MonitorServiceImpl
 * @Description
 * @Author Dgm
 * @Date 2023/12/9 10:04
 * @Version
 */
@Slf4j
@Service
public class MonitorServiceImpl implements MonitorService {

    @Resource
    private PushMonitorInfoMapper monitorInfoMapper;

    @Resource
    private PushMonitorRulesMapper rulesMapper;

    @Resource
    private DskOpenApiUtil dskOpenApiUtil;

    @Override
    public R insert(PushMonitorInfoVo pushMonitorInfoDto) {
        monitorInfoMapper.insert(pushMonitorInfoDto);
        return R.ok();
    }

    @Override
    public R rulesSelect(PushMonitorCompanyAddVo addVo) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/company/supplier/system/queryDimensionEnum", BeanUtil.beanToMap(addVo, false, false));
        return BeanUtil.toBean(map, R.class);
    }

    @Override
    public R insertRules(PushMonitorRulesVo monitorRulesDto) {
        // todo 20231211 规则是否与使用登录人强关联
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            monitorRulesDto.setUserId(userId);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", monitorRulesDto.getUserId());
        PushMonitorRules detail  = rulesMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(detail)) {
            rulesMapper.insert(monitorRulesDto);
        } else {
            monitorRulesDto.setId(detail.getId());
            rulesMapper.updateById(monitorRulesDto);
        }
        return R.ok();
    }

    @Override
    public R rulesDetail(PushMonitorRulesDetailVo detailVo) {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            detailVo.setUserId(userId);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", detailVo.getUserId());
        PushMonitorRules detail  = rulesMapper.selectOne(queryWrapper);
        return R.ok(detail);
    }

    @Override
    public TableDataInfo companyDynamicPage(PushMonitorDynamicPageVo pageVo) throws Exception {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            pageVo.setUserId(userId);
            pageVo.getCondition().setUserId(userId);
        }
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/company/info/companyDynamicList", BeanUtil.beanToMap(pageVo, false, false));
        return dskOpenApiUtil.responsePage(map);
    }

    @Override
    public R companyDynamicDetail(PushMonitorDynamicDetailVo detailVo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("source_id", detailVo.getSourceId());
        PushMonitorInfo detail  = monitorInfoMapper.selectOne(queryWrapper);
        return R.ok(detail);
    }

    @Override
    public TableDataInfo reportPage(PushMonitorReportPageVo pageVo) throws Exception {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            pageVo.setUserId(userId);
            pageVo.getCondition().setUserId(userId);
        }
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/company/info/monitor/report", BeanUtil.beanToMap(pageVo, false, false));
        return dskOpenApiUtil.responsePage(map);
    }

    @Override
    public TableDataInfo companyPage(PushMonitorCompanyPageVo pageVo) throws Exception {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            pageVo.setUserId(userId);
            pageVo.getCondition().setUserId(userId);
        }
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/company/supplier/system/paging", BeanUtil.beanToMap(pageVo, false, false));
        return dskOpenApiUtil.responsePage(map);
    }

    @Override
    public R systemAdd(PushMonitorCompanyAddVo addVo) {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            addVo.setUserId(userId);
        }
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/company/supplier/system/add", BeanUtil.beanToMap(addVo, false, false));
        return BeanUtil.toBean(map, R.class);
    }


    @Override
    public R systemCancel(PushMonitorCompanyCancelVo cancelVo) {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            cancelVo.setUserId(userId);
        }
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/company/supplier/system/cancel", BeanUtil.beanToMap(cancelVo, false, false));
        return BeanUtil.toBean(map, R.class);
    }

    @Override
    public R systemImport(MultipartFile file, PushMonitorCompanyImportAddVo importAddVo) {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            importAddVo.setUserId(userId);
        }
        //存放保单信息
        List<String> companyList = new ArrayList<String>();
        // 设置redisKey
        String lockKey = "stockKey" + userId;
        // 设置redisValue
        String value = UUID.randomUUID().toString();
        try {
            // 这里默认设置超时时间为30秒
            boolean hasKey = RedisUtils.setObjectIfAbsent(lockKey, value, Duration.ofMillis(1000 * 30));
            if (!hasKey) {
                return R.fail("数据正在上传请等待");
            }

            //如果文件不存在  则文件上传失败
            if (file == null){
                return R.fail("操作失敗，数据异常，請使用正确的模板");
            }
            if (file.isEmpty()){
                return R.fail("操作失敗，数据异常，請使用正确的模板");
            }

            //得到整个excel
            XSSFWorkbook wook = new XSSFWorkbook((file.getInputStream()));
            //得到第一个表单sheet
            Sheet sheet = wook.getSheetAt(0);
            //得到最后一行的行号
            int lastRowNum = sheet.getLastRowNum();
            //如果总行数小于等于2 （没有数据）提示数据异常
            if ((lastRowNum) < 1){
                return R.fail("未提供有效数据，请确认！");
            }

            //进行excel格式判定
            String name = sheet.getRow(0).getCell(0) + "";
            //只要其中一个不满足则格式有误
            if (!"企业名称".equals(name)){
                return R.fail("操作失败，数据异常，请使用正确的模板");
            }
            //行列皆从0开始
            for (int i = 1; i <= lastRowNum; i++) {
                String companyNameStr = "";
                // 统一社会信用代码
                Cell companyName = sheet.getRow(i).getCell(0);
                if (ObjectUtil.isNotEmpty(companyName)) {
                    String cn = companyName.toString();
                    companyNameStr = cn.trim();
                }
                companyList.add(companyNameStr);
            }
        } catch (Exception e) {
            log.error("",e.getMessage());
        } finally {
            RedisUtils.hasValueDelete(lockKey, value);
        }
        if (ObjectUtil.isEmpty(companyList)) {
            return R.fail("操作失败");
        }
        importAddVo.setNames(companyList);
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/company/supplier/system/addPatch", BeanUtil.beanToMap(importAddVo, false, false));
        log.info("systemImport==================================>" + map);
        return BeanUtil.toBean(map, R.class);

    }
}
