package com.fkzy.warn.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fkzy.warn.common.constants.EntityConstants;
import com.fkzy.warn.common.request.RequestParameter;
import com.fkzy.warn.common.response.ApiResponse;
import com.fkzy.warn.common.util.LawResearchUtil;
import com.fkzy.warn.mapper.MonitorUsersMapper;
import com.fkzy.warn.model.*;
import com.fkzy.warn.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangjing
 * @date 2023/10/16 18:17
 * @description
 */
@Service
public class MonitorUsersServiceImpl extends ServiceImpl<MonitorUsersMapper, MonitorUsers> implements
    MonitorUsersService {

    @Resource
    EnterpriseInfoService enterpriseInfoService;
    @Resource
    LawCaseService lawCaseService;
    @Resource
    AuthorizationService authorizationService;
    @Resource
    ReportService reportService;
    @Resource
    InvocationRecordService invocationRecordService;

    @Override
    public ApiResponse saveModel(MonitorUsers entity, String ticket) {
        save(entity);
        return new ApiResponse();
    }

    @Override
    public ApiResponse updateModel(MonitorUsers entity,String ticket) {
        this.updateById(entity);
        return new ApiResponse();
    }

    @Override
    public ApiResponse deleteModel(List<String> ids) {
        MonitorUsers entity = new MonitorUsers();
        entity.setIsDel(EntityConstants.DEL);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", ids);
        update(entity, wrapper);
        return new ApiResponse();
    }

    @Override
    public Page<MonitorUsers> queryPage(RequestParameter parameter) {
        MonitorUsers entity = parameter.getParameter().toJavaObject(MonitorUsers.class);
        Page<MonitorUsers> page = new Page<MonitorUsers>(parameter.getCurrent(), parameter.getSize());
        page.setSearchCount(true);
        page.setOptimizeCountSql(true);
        QueryWrapper<MonitorUsers> eWrapper = new QueryWrapper<MonitorUsers>(entity);
        Page<MonitorUsers> result = this.page(page, eWrapper);
        return result;
    }

    @Override
    public void checkMonitor() {
        List<MonitorUsers> monitorUsersList = list(new LambdaQueryWrapper<MonitorUsers>()
            .eq(MonitorUsers::getIsQuery,EntityConstants.NORMAL)
        );
        if (monitorUsersList.isEmpty()){
            return;
        }
        monitorUsersList.forEach(item ->{
            //添加至法研平台监控名单
            LawResearchUtil.addpublic(item.getCompanyName());
            //生成授权-临时
            setAuthorization(item);
            //查询企业信息  暂无
            setEnterpriseInfo(item);
            //获取司法信息
            setLawCase(item);
            //生成告警统计
            caseStatistics(item);
            //生成首次报告
            caseReport(item);

        });

    }

    private void caseReport(MonitorUsers item) {
        Report now = reportService.getOne(new LambdaQueryWrapper<Report>()
            .eq(Report::getCreditCode,item.getCreditCode())
            .eq(Report::getReportType,"first")
            ,false
        );
        if (now!=null){
            return;
        }
        Report report = new Report();
        report.setCompanyName(item.getCompanyName());
        report.setCreditCode(item.getCreditCode());
        report.setReportType("first");
        report.setName(item.getCompanyName());
        report.setReportTime(new Date());
        report.setBusinessId(item.getBindUserId());
        report.setIsDel(EntityConstants.NORMAL);
        reportService.save(report);
    }

    private void setAuthorization(MonitorUsers item) {
        Authorization now = authorizationService.getOne(new LambdaQueryWrapper<Authorization>()
            .eq(Authorization::getUserId,item.getBindUserId())
            .eq(Authorization::getCreditCode,item.getCreditCode())
            ,false
        );
        if (now!=null){
            return;
        }
        Authorization authorization = new Authorization();
        authorization.setUserId(item.getBindUserId());
        authorization.setCreditCode(item.getCreditCode());
        authorization.setIsDel(EntityConstants.NORMAL);
        authorization.setStatus(EntityConstants.NORMAL);
        authorizationService.save(authorization);
    }

    private void caseStatistics(MonitorUsers item) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("creditCode",item.getCreditCode());
        lawCaseService.caseStatistics(jsonObject);
    }

    private void setLawCase(MonitorUsers item) {
        InvocationRecord invocationRecord =  LawResearchUtil.querySxx(item.getCompanyName(),item.getCreditCode(),null);
        item.setIsQuery(1);
        updateById(item);
        invocationRecordService.saveModel(invocationRecord);
        JSONObject object = JSONObject.parseObject(invocationRecord.getApiResult());
        lawCaseService.judicialModelSave(object);
    }

    private void setEnterpriseInfo(MonitorUsers item) {
        EnterpriseInfo enterpriseInfo = new EnterpriseInfo();
        enterpriseInfo.setENTNAME(item.getCompanyName());
        enterpriseInfo.setCREDITCODE(item.getCreditCode());
        enterpriseInfo.setFRNAME(item.getLegalPerson());
        enterpriseInfo.setREGORGPROVINCE(item.getProvince());
        enterpriseInfo.setIsDel(EntityConstants.NORMAL);
        enterpriseInfoService.saveOrUpdate(enterpriseInfo);
    }
}
