/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 运维系统
 * 创建日期:2023/11/12
 */
package org.springblade.modules.yjxt.business.warn.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.baseinfo.org.entity.DeptRegionEntity;
import org.springblade.modules.baseinfo.org.service.IDeptRegionService;
import org.springblade.modules.yjxt.business.warn.dto.OriginalWarningInfoDTO;
import org.springblade.modules.yjxt.business.warn.entity.OriginalWarningInfoEntity;
import org.springblade.modules.yjxt.business.warn.entity.WarnResponseInfoEntity;
import org.springblade.modules.yjxt.business.warn.service.IOriginalWarningService;
import org.springblade.modules.yjxt.business.warn.vo.OriginalWarningInfoVO;
import org.springblade.modules.yjxt.business.warn.entity.WarnDetailInfoEntity;
import org.springblade.modules.yjxt.business.warn.vo.WarnDetailInfoVO;
import org.springblade.modules.yjxt.business.warn.vo.WarnResponseInfoVO;
import org.springblade.modules.yjxt.business.warn.wrapper.OriginalWarningWrapper;
import org.springblade.modules.yjxt.business.warn.wrapper.YjWarnInfoWrapper;
import org.springblade.utils.HttpRequestUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

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

/***
 * Date:2023/11/12
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
@RestController
@RequestMapping("galaxy-business/yj/warn")
@RequiredArgsConstructor
@Api(value = "应急系统预警信息管理接口", tags = "查")
public class YjWarnController extends BladeController {

    @Resource
    private IOriginalWarningService originalWarningService;

    @Resource
    private final IDeptRegionService deptRegionService;

    @Value("${spring.yjxt.etl-server-url}")
    private String etlServerUrl;

    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "warnStatus", value = "预警状态", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "type", value = "预警状态", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "warnName", value = "预警名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "dangerAreaName", value = "危险政区名称", paramType = "query", dataType = "string"),
    })
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页")
    public R<IPage<OriginalWarningInfoVO>> page(@ApiIgnore OriginalWarningInfoDTO entity, Query query) {
        BladeUser user = AuthUtil.getUser();
        if (Func.isNull(entity.getWarnAdcd())) {
            if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
                entity.setWarnAdcd(BusinessConstant.REGION_NM_ADCODE);
            } else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)) {
                    return R.fail("查询失败");
                }
                entity.setWarnAdcd(deptRegionEntity.getAdcd());
            } else if (BusinessConstant.ROLE_YJ_SERVICE_PERSON.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)) {
                    return R.fail("查询失败");
                }
                entity.setWarnAdcd(deptRegionEntity.getAdcd());
            } else if (BusinessConstant.ROLE_QI_ADMIN.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)) {
                    return R.fail("查询失败");
                }
                entity.setWarnAdcd(deptRegionEntity.getAdcd());
            } else {
                return R.fail("查询失败");
            }
        }
        entity.setReviewStatus("1");
        entity.setType("4");
        IPage<OriginalWarningInfoEntity> pages = originalWarningService.selectPage(Condition.getPage(query), entity);
        return R.data(YjWarnInfoWrapper.build().pageVO(pages));
    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "")
    public R<OriginalWarningInfoVO> detail(OriginalWarningInfoEntity entity) {
        if (entity.getId() == null) {
            return R.fail("参数错误");
        }
        OriginalWarningInfoEntity detail = originalWarningService.getById(entity.getId());
        return R.data(OriginalWarningWrapper.build().entityVO(detail));
    }

    /**
     * 从宏图数据库读取完整数据
     *
     * @param entity
     * @return
     */
    @GetMapping("/detail/all")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "")
    public R<WarnDetailInfoVO> allDetail(OriginalWarningInfoEntity entity) {
        if (Func.isNull(entity.getId()) && Func.isNull(entity.getWarnId())) {
            return R.fail("参数错误");
        }
        OriginalWarningInfoEntity detail = new OriginalWarningInfoEntity();
        if (Func.notNull(entity.getId())) {
            detail = originalWarningService.getById(entity.getId());
            if (Func.isNull(detail)) {
                return R.fail("查询失败");
            }
        } else if (Func.notNull(entity.getWarnId())) {
            LambdaQueryWrapper<OriginalWarningInfoEntity> warnwrapper = Wrappers.<OriginalWarningInfoEntity>query().lambda();
            warnwrapper.eq(OriginalWarningInfoEntity::getWarnId, entity.getWarnId());
            warnwrapper.last("limit 1");
            detail = originalWarningService.getOne(warnwrapper);
            if (Func.isNull(detail)) {
                return R.fail("查询失败");
            }
        } else {
            return R.fail("查询失败");
        }
        try {
            String url = etlServerUrl + detail.getWarnId();
            JSONObject res = HttpRequestUtil.doHttpGetRequest("查询预警详情", url, null, null, 20 * 1000);
            if (res.getIntValue("code") == 200 && res.getBooleanValue("success")) {
                JSONObject data = res.getJSONObject("data");
                if (Func.notNull(data)) {
                    WarnDetailInfoEntity warnDetailInfoEntity = JsonUtil.parse(data.toJSONString(), WarnDetailInfoEntity.class);
                    WarnDetailInfoVO vo = Objects.requireNonNull(BeanUtil.copy(warnDetailInfoEntity, WarnDetailInfoVO.class));
                    if (Func.notNull(vo.getWarnResponseInfoList())) {
                        List<WarnResponseInfoEntity> warnResponseInfoList = vo.getWarnResponseInfoList();
                        List<WarnResponseInfoVO> voList = new ArrayList<>(warnResponseInfoList.size());
                        for (WarnResponseInfoEntity warnResponseInfoEntity : warnResponseInfoList) {
                            WarnResponseInfoVO warnResponseInfoVO = Objects.requireNonNull(BeanUtil.copy(warnResponseInfoEntity, WarnResponseInfoVO.class));
                            if (Func.notNull(warnResponseInfoVO.getVariableOut())) {
                                JSONObject json = JSONObject.parseObject(warnResponseInfoVO.getVariableOut());
                                if (json.containsKey("DXJS")) {
                                    warnResponseInfoVO.setDxjs(json.getString("DXJS"));
                                }
                                if (json.containsKey("RYSW")) {
                                    warnResponseInfoVO.setRysw(json.getString("RYSW"));
                                }
                                if (json.containsKey("GDSH")) {
                                    warnResponseInfoVO.setGdsh(json.getString("GDSH"));
                                }
                                if (json.containsKey("JYCX")) {
                                    warnResponseInfoVO.setJycx(json.getString("JYCX"));
                                }
                                if (json.containsKey("SFCG")) {
                                    warnResponseInfoVO.setSfcg(json.getString("SFCG"));
                                }
                                if (json.containsKey("RYZY")) {
                                    warnResponseInfoVO.setRyzy(json.getString("RYZY"));
                                }
                                if (json.containsKey("SFQR")) {
                                    warnResponseInfoVO.setSfqr(json.getString("SFQR"));
                                }
                            }
                            voList.add(warnResponseInfoVO);
                        }
                        vo.setWarnResponseList(voList);
                    }
                    return R.data(vo);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        WarnDetailInfoVO warnDetailInfoVO = new WarnDetailInfoVO();
        warnDetailInfoVO.setWarnId(detail.getWarnId());
        warnDetailInfoVO.setWarnInfo(detail.getWarnInfo());
        warnDetailInfoVO.setWarnTime(detail.getWarnTime());
        warnDetailInfoVO.setWarnName(detail.getWarnName());
        warnDetailInfoVO.setInsideWarnInfoList(new ArrayList<>(0));
        warnDetailInfoVO.setOusideWarnStatus(0);
        warnDetailInfoVO.setWarnResponseStatus(0);
        return R.data(warnDetailInfoVO);
    }

}
