/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 运维系统
 * 创建日期:2023/9/13
 */
package org.springblade.modules.yjxt.base.map.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.oss.model.BladeFile;
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.utils.Func;
import org.springblade.jobtask.TaskManager;
import org.springblade.modules.baseinfo.org.entity.DeptRegionEntity;
import org.springblade.modules.baseinfo.org.service.IDeptRegionService;
import org.springblade.modules.baseinfo.region.whole.entity.BaseRegionInfoEntity;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springblade.modules.yjxt.base.map.dto.DangerAreaImportRecordDTO;
import org.springblade.modules.yjxt.base.map.dto.DangerAreaDTO;
import org.springblade.modules.yjxt.base.map.entity.DangerAreaImportRecordEntity;
import org.springblade.modules.yjxt.base.map.entity.DangerAreaEntity;
import org.springblade.modules.yjxt.base.map.entity.DangerAreaPointEntity;
import org.springblade.modules.yjxt.base.map.service.IDangerAreaImportServcie;
import org.springblade.modules.yjxt.base.map.task.DangerAreaImportTask;
import org.springblade.modules.yjxt.base.map.vo.DangerAreaImportRecordVO;
import org.springblade.modules.yjxt.base.map.vo.DangerAreaVO;
import org.springblade.modules.yjxt.base.map.wrapper.DangerAreaWrapper;
import org.springblade.modules.yjxt.base.map.service.IDangerAreaPointService;
import org.springblade.modules.yjxt.base.map.service.IDangerAreaService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.FutureTask;

/***
 * Date:2023/9/13
 * Title:危险区地图数据管理模块
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
@RestController
@RequestMapping("galaxy-business/map/dangerarea")
@RequiredArgsConstructor
@Api(value = "危险区地图数据管理模块", tags = "危险区")
public class MapDangerAreaController extends BladeController {

    private final IDangerAreaService dangerAreaService;

    private final IDangerAreaPointService pointService;

    private final IDangerAreaImportServcie danagerAreaImportServcie;

//    private final IDangerAreaLeaveLineService leaveLineService;
//
//    private final IMvAttStBaseService mvAttStBaseService;
//
//    private final IDangerAreaResidentService dangerAreaResidentService;

    private final IDangerAreaPointService dangerAreaPointService;

    private final IDeptRegionService deptRegionService;

    @Resource
    private OssBuilder ossBuilder;

    @Resource
    private TaskManager taskManager;

    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adName", value = "行政区名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "dangerAreaName", value = "危险区名称", paramType = "query", dataType = "string"),
    })
    @ApiOperation(value = "分页")
    public R<IPage<DangerAreaVO>> getPage(@ApiIgnore DangerAreaDTO dto, Query query) {
        BladeUser user = AuthUtil.getUser();
        if (Func.isNull(dto.getAdcd())) {
            if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
                dto.setAdcd(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("查询失败");
                }
                dto.setAdcd(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("查询失败");
                }
                dto.setAdcd(deptRegionEntity.getAdcd());
            } else {
                return R.fail("查询失败");
            }
        }
        IPage<DangerAreaVO> pages = dangerAreaService.selectPage(Condition.getPage(query), dto);
        List<DangerAreaVO> voList = pages.getRecords();
        for (DangerAreaVO vo : voList) {
            DangerAreaWrapper.build().entityVO(vo);
        }
        return R.data(pages);
    }

    /**
     * 不分页查询危险区，根据行政区或危险区名称查询
     *
     * @param dto
     * @return
     */
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adcd", value = "行政区编码", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "dangerAreaName", value = "危险区名称", paramType = "query", dataType = "string"),
    })
    @ApiOperation(value = "分页")
    public R<List<DangerAreaVO>> list(@ApiIgnore DangerAreaDTO dto) {
        List<DangerAreaVO> voList = dangerAreaService.selectAdDangerArea(dto);
        for (DangerAreaVO vo : voList) {
            DangerAreaWrapper.build().entityVO(vo);
        }
        return R.data(voList);
    }

    @GetMapping("/select")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adcd", value = "行政区编码", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "dangerAreaName", value = "危险区名称", paramType = "query", dataType = "string"),
    })
    @ApiOperation(value = "分页")
    public R<List<DangerAreaVO>> selectList(@ApiIgnore DangerAreaDTO dto) {
        List<DangerAreaVO> voList = dangerAreaService.selectAdDangerArea(dto);

        return R.data(voList);
    }


    @GetMapping("/import/page")
    @ApiOperation(value = "分页")
    public R<IPage<DangerAreaImportRecordVO>> getImportPage(Query query) {
        return R.data(danagerAreaImportServcie.selectPage(Condition.getPage(query)));
    }

    /**
     * 查询危险区多边形地理信息
     *
     * @param entity
     * @return
     */
    @GetMapping("/polygon")
    @ApiOperation(value = "列表")
    public R<List<DangerAreaPointEntity>> getPolygon(DangerAreaEntity entity) {
        LambdaQueryWrapper<DangerAreaPointEntity> wrapper = Wrappers.<DangerAreaPointEntity>query().lambda();
        wrapper.eq(DangerAreaPointEntity::getDangerAreaId, entity.getId());
        List<DangerAreaPointEntity> points = pointService.list(wrapper);
        return R.data(points);
    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperation(value = "详情", notes = "传入DangerAreaEntity")
    public R<DangerAreaVO> detail(DangerAreaEntity entity) {
        if (Func.isNull(entity.getId()) && Func.isNull(entity.getDangerAreaPid())) {
            return R.fail("参数错误");
        }
        if (Func.notNull(entity.getId())) {
            DangerAreaEntity detail = dangerAreaService.getById(entity.getId());
            DangerAreaVO vo = DangerAreaWrapper.build().entityVO(detail);
            List<DangerAreaPointEntity> list = this.getDangerAreaPoints(vo.getId());
            if (Func.notNull(list)) {
                vo.setPoints(list);
            }
            return R.data(vo);
        } else if (Func.notNull(entity.getDangerAreaPid())) {
            LambdaQueryWrapper<DangerAreaEntity> wrapper = Wrappers.<DangerAreaEntity>query().lambda();
            wrapper.eq(DangerAreaEntity::getDangerAreaPid, entity.getDangerAreaPid());
            wrapper.last("limit 1");
            DangerAreaEntity detail = dangerAreaService.getOne(wrapper);
            if (Func.isNull(detail)) {
                return R.fail("查询失败");
            }
            DangerAreaVO vo = DangerAreaWrapper.build().entityVO(detail);
            List<DangerAreaPointEntity> list = this.getDangerAreaPoints(vo.getId());
            if (Func.notNull(list)) {
                vo.setPoints(list);
            }
            return R.data(vo);
        }
        return R.fail("查询失败");
    }

    private List<DangerAreaPointEntity> getDangerAreaPoints(Long id) {
        LambdaQueryWrapper<DangerAreaPointEntity> wrapper = Wrappers.<DangerAreaPointEntity>query().lambda();
        wrapper.eq(DangerAreaPointEntity::getDangerAreaId, id);
        return dangerAreaPointService.list(wrapper);
    }

    /**
     * 危险区二维码
     */
    @GetMapping("/qr")
    @ApiOperation(value = "二维码", notes = "")
    public R<DangerAreaVO> getDangerAreaQr(DangerAreaEntity entity) {
        if (Func.isNull(entity.getDangerAreaPid())) {
            return R.fail("参数错误");
        }
        DangerAreaVO vo = new DangerAreaVO();
        LambdaQueryWrapper<DangerAreaEntity> wrapper = Wrappers.<DangerAreaEntity>query().lambda();
        wrapper.eq(DangerAreaEntity::getDangerAreaPid, entity.getDangerAreaPid());
        wrapper.last("limit 1");
        DangerAreaEntity detail = dangerAreaService.getOne(wrapper);
        if (Func.notNull(detail)) {
            vo.setDangerAreaName(detail.getDangerAreaName());
            if (Func.notNull(detail.getQrUrl())) {
                vo.setQrUrl(detail.getQrUrl());
            } else {
                String qr = dangerAreaService.createDangerAreaQr(entity.getDangerAreaPid());
                if (Func.notNull(qr)) {
                    vo.setQrUrl(qr);
                    detail.setQrUrl(qr);
                    dangerAreaService.updateById(detail);
                }
            }
        }
        return R.data(vo);
    }

    /**
     * 群众注册二维码
     *
     * @param entity
     * @return
     */
    @GetMapping("/resident/reg/qr")
    @ApiOperation(value = "二维码", notes = "")
    public R<DangerAreaVO> getDangerAreaResidentQr(DangerAreaEntity entity) {
        if (Func.isNull(entity.getDangerAreaPid())) {
            return R.fail("参数错误");
        }
        DangerAreaVO vo = new DangerAreaVO();
        LambdaQueryWrapper<DangerAreaEntity> wrapper = Wrappers.<DangerAreaEntity>query().lambda();
        wrapper.eq(DangerAreaEntity::getDangerAreaPid, entity.getDangerAreaPid());
        wrapper.last("limit 1");
        DangerAreaEntity detail = dangerAreaService.getOne(wrapper);
        if (Func.notNull(detail)) {
            vo.setDangerAreaName(detail.getDangerAreaName());
            if (Func.notNull(detail.getResidentRegQrUrl())) {
                vo.setResidentRegQrUrl(detail.getResidentRegQrUrl());
            } else {
                String qr = dangerAreaService.createResidentRegQr(entity.getDangerAreaPid());
                if (Func.notNull(qr)) {
                    vo.setResidentRegQrUrl(qr);
                    detail.setResidentRegQrUrl(qr);
                    dangerAreaService.updateById(detail);
                }
            }
        }
        return R.data(vo);
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ApiOperation(value = "逻辑删除", notes = "传入ID数组")
    public R remove(@ApiParam(value = "主键集合") @RequestParam String ids) {
        boolean temp = dangerAreaService.deleteLogic(Func.toLongList(ids));
        return R.status(temp);
    }

    @ApiLog("危险区信息-导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "remark", value = "导入说明", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "saveType", value = "操作类型", paramType = "query", dataType = "int"),
    })
    @PostMapping(value = "/import/json")
    @ApiOperation(value = "导入测站信息", notes = "")
    public R importDangerAreaTable(@ApiIgnore DangerAreaImportRecordDTO dto, MultipartFile file) {
        try {
            BladeFile bladeFile = ossBuilder.template().putFile(file);
            if (null == bladeFile) {
                return R.fail("导入失败");
            }
            DangerAreaImportRecordEntity recordEntity = new DangerAreaImportRecordEntity();
            recordEntity.setImportStatus(0L);
            recordEntity.setRemark(dto.getRemark());
            recordEntity.setSaveType(dto.getSaveType());
            recordEntity.setImportTime(Func.formatDateTime(new Date()));
            recordEntity.setFileName(file.getOriginalFilename());
            danagerAreaImportServcie.save(recordEntity);
            DangerAreaImportTask task = new DangerAreaImportTask(bladeFile, recordEntity, dangerAreaService, pointService, danagerAreaImportServcie);
            FutureTask<Integer> futureTask = new FutureTask<>(task);
            taskManager.submitTask(futureTask);
            return R.success("导入任务提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("导入错误 " + e.getMessage());
        }
    }

}
