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.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.*;
import java.util.concurrent.TimeUnit;

/**
 * @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() {
        // todo 20231209 产品出细致 具体全部类型
        Map<String, Object> objectMap = new HashMap<>(2);
        List<String> riskType = new ArrayList<>(2);
        riskType.add("工商风险");
        riskType.add("司法风险");
        objectMap.put("riskType", riskType);
        // 维度
        List<String> dimension = new ArrayList<>(10);
        dimension.add("法院公告");
        dimension.add("裁判文书");
        dimension.add("开庭公告");
        dimension.add("股权冻结");
        dimension.add("限制高消费");
        dimension.add("被执行人");
        dimension.add("失信被执行人");
        dimension.add("限制高消费");
        objectMap.put("dimension", dimension);
        return R.ok(objectMap);
    }

    @Override
    public R insertRules(PushMonitorRulesVo monitorRulesDto) {
        // todo 20231211 规则是否与使用登录人强关联
        if (ObjectUtil.isEmpty(monitorRulesDto.getId())) {
            rulesMapper.insert(monitorRulesDto);
        } else {
            rulesMapper.updateById(monitorRulesDto);
        }
        return R.ok();
    }

    @Override
    public R rulesDetail(PushMonitorRulesDetailVo detailVo) {
        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 {
        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 {
        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 {
        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) {
        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) {
        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 importGuarantee(MultipartFile file) {

        //存放保单信息
        List<PushMonitorImportCompanyVo> companyVoListList = new ArrayList<PushMonitorImportCompanyVo>();
        String userId = "98";
        // 设置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++) {
                PushMonitorImportCompanyVo vo = new PushMonitorImportCompanyVo();
                // 统一社会信用代码
                Cell companyName = sheet.getRow(i).getCell(0);
                if (ObjectUtil.isNotEmpty(companyName)) {
                    String cn = companyName.toString();
                    vo.setCompanyName(cn.trim());
                }
                companyVoListList.add(vo);
            }
        } catch (Exception e) {
            log.error("",e.getMessage());
        } finally {
            RedisUtils.hasValueDelete(lockKey, value);
        }
        if (ObjectUtil.isEmpty(companyVoListList)) {
            return R.fail("操作失败");
        }
        Map<String, Object> param = new HashMap<>(1);
        param.put("names", companyVoListList);
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/company/supplier/system/addPatch", param);
        return BeanUtil.toBean(map, R.class);

    }
}
