package com.testor.ddd.safetyControl.interfaces.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.file.model.domain.SysFile;
import com.testor.biz.file.service.SysFileService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.core.utils.StringUtils;
import com.testor.ddd.safetyControl.application.service.riskMap.RiskMapManageService;
import com.testor.ddd.safetyControl.domain.riskMap.entity.TSafeRiskMapRepo;
import com.testor.ddd.safetyControl.infrastructure.repository.riskMap.dao.TSafeRiskMapDao;
import com.testor.ddd.safetyControl.infrastructure.repository.riskMap.entity.TSafeRiskMapDO;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskMap.TSafeRiskMapDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskMap.TSafeRiskMapDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskMap.TSafeRiskMapDelParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.riskMap.TSafeRiskMapVO;
import com.testor.module.sys.model.vo.SysOrgVo;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.supers.SuperModel;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 危险源Controller
 *
 * @author testor-framework
 * @date 2022-07-11 10:00:17
 */
@RestController
@RequestMapping("/risk/map")
@Api(value = "TSafeRiskMap", tags = "风险地图")
@Slf4j
public class TSafeRiskMapController extends SuperController
{
    @Autowired
    private RiskMapManageService riskMapManageService;

	@Autowired
	private TSafeRiskMapRepo tSafeRiskMapRepo;
	@Resource
	private SysOrgService orgService;
	@Autowired
	private SysFileService sysFileService;
	@Autowired
	private SysOrgService sysOrgService;

	@Autowired
	private TSafeRiskMapDao tSafeRiskMapDao;

	@Autowired
	private NewSysOrgService newSysOrgService;
//	/* Generated Method*/
//	@ApiOperation(value = "新增、修改危险源", notes = "Add TSafeRiskMap")
//	@PostMapping(value = "/add")
//	public BaseResponse addEntity(@RequestBody TSafeRiskMapDTO addRequest) throws BusinessException {
//	return riskMapManageService.editRiskMap(addRequest);
//	}
	/* 修改后*/
	@ApiOperation(value = "新增、修改危险源", notes = "Add TSafeRiskMap")
	@PostMapping(value = "/add")
	public BaseResponse addEntity(@RequestBody TSafeRiskMapDO tSafeRiskMapDO) throws BusinessException {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		UserInfo curUser = ContextUtils.getLoginUser();

		System.out.println("************curUser:"+curUser.getOrgId());
		if (StrUtil.isBlank(curUser.getOrgId())) {
			baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
			baseResponse.setMsg("用户信息错误");
			return baseResponse;
		}
		String curUserOrgId = curUser.getOrgId();
		tSafeRiskMapDO.setOrgId(curUserOrgId);

		// 处理区域公司 、 基层单位
		String orgStrs = orgAllPath(curUserOrgId);
		if(!StrUtil.isBlank(orgStrs)) {
			String[] orgArr = orgStrs.split(",");
			if(orgArr.length == 3) {
				tSafeRiskMapDO.setRegionOrgId(orgArr[2]);
			}
			if(orgArr.length > 3) {
				tSafeRiskMapDO.setRegionOrgId(orgArr[2]);
				tSafeRiskMapDO.setBasicOrgId(orgArr[orgArr.length-1]);
			}
		}
		String id = tSafeRiskMapDO.getId();
		if (ObjectUtil.isNotEmpty(id)){
			boolean b = tSafeRiskMapRepo.updateById(tSafeRiskMapDO);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(b)).build());
			return baseResponse;
		}
		Boolean aBoolean = tSafeRiskMapRepo.save(tSafeRiskMapDO);
		baseResponse.setData(
				BizGeneralResponse.builder().result(TypeHelper.castToString(aBoolean)).build());
		return baseResponse;
	}

	@ApiOperation(value = "首页轮询 ", notes = "delete TSafeRiskMap By Id")
	@GetMapping(value = "/poll")
	public BaseResponse poll(String orgId) throws BusinessException {
		BaseResponse<List<SysFile>> baseResponse=new BaseResponse<>();
		LambdaQueryWrapper<TSafeRiskMapDO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(TSafeRiskMapDO::getOrgId,orgId).eq(SuperModel::getStatus,0);
		List<TSafeRiskMapDO> list = tSafeRiskMapRepo.list(wrapper);
		List<String> imagId = list.stream().map(TSafeRiskMapDO::getImageId).collect(Collectors.toList());
		if (ObjectUtil.isNotEmpty(imagId)){
			LambdaQueryWrapper<SysFile> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.in(ObjectUtil.isNotEmpty(imagId),SysFile::getFileId,imagId);
			List<SysFile> sysFileList = sysFileService.list(queryWrapper);
			baseResponse.setData(sysFileList);
		}

		return baseResponse;
	}
	@ApiOperation(value = "删除 风险地图 ", notes = "delete TSafeRiskMap By Id")
	@PutMapping(value = "/delete")
	public BaseResponse deleteEntity(@RequestBody TSafeRiskMapDelParam deleteRequest) throws BusinessException {
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(deleteRequest)&& StringHelper.isNotEmpty(deleteRequest.getId())){
			baseResponse= riskMapManageService.deleteById(deleteRequest.getId());
		}
		return baseResponse;
	}

//	@ApiOperation(value = "获取 风险地图 分页列表", notes = "List TSafeRiskMap with page")
//	@PostMapping(value = "/list")
//	public  BaseResponse<BaseResponseList<TSafeRiskMapVO>>listEntity(@RequestBody TSafeRiskMapDTOParam param){
//		BaseResponse<BaseResponseList<TSafeRiskMapVO>>baseResponse=new BaseResponse<>();
//		BaseResponseList<TSafeRiskMapVO> resultList= riskMapManageService.listByPage(param);
//		baseResponse.setData(resultList);
//		return baseResponse;
//	}
	@ApiOperation(value = "获取 风险地图 分页列表", notes = "List TSafeRiskMap with page")
	@PostMapping(value = "/list")
	public  BaseResponse<IPage<TSafeRiskMapVO> >listEntity(@RequestBody TSafeRiskMapDTOParam param){
		if(StringUtils.isBlank(param.getOrgId())) {
			String loginUserId = ContextUtils.getLoginUser().getOrgId();
			param.setOrgId(loginUserId);
		}
		BaseResponse<IPage<TSafeRiskMapVO> >baseResponse=new BaseResponse<>();
		Page<TSafeRiskMapVO> page = new Page<>();
		page.setCurrent(Integer.valueOf(param.getPage()));
		page.setSize(Integer.valueOf(param.getLimit()));
		param.setOrderBy("rs.create_date");
		param.setOrderType("desc");
		IPage<TSafeRiskMapVO> tSafeRiskMapVOIPage = tSafeRiskMapDao.listPage(page, param);
		if(tSafeRiskMapVOIPage == null){
			return baseResponse;
		}
		List<TSafeRiskMapVO> records = tSafeRiskMapVOIPage.getRecords();
		if(records == null || records.size() == 0){
            return baseResponse;
        }
        for (TSafeRiskMapVO vo : records) {
			SysOrgVo sysOrgVo = newSysOrgService.lookOrg(vo.getOrgId());
			vo.setOrgFullName(sysOrgVo.getPath());
        }
		tSafeRiskMapVOIPage.setRecords(records);
		baseResponse.setData(tSafeRiskMapVOIPage);
		return baseResponse;
	}
	@ApiOperation(value = "获取 风险地图 列表(不分页)", notes = "List TSafeRiskMap with no page")
	@PostMapping(value = "/listAll")
	public  BaseResponse<List<TSafeRiskMapDTO>>listAll(@RequestBody TSafeRiskMapDTOParam param){
		BaseResponse<List<TSafeRiskMapDTO>>baseResponse=new BaseResponse<>();
		List<TSafeRiskMapDTO> resultList= riskMapManageService.listAll(param);
		baseResponse.setData(resultList);
		return baseResponse;
	}

//	@ApiOperation(value = "获取 风险地图 详情 ", notes = "Get TSafeRiskMap By Id")
//	@GetMapping(value = "/get")
//	public BaseResponse<TSafeRiskMapVO> getById(String id){
//		BaseResponse<TSafeRiskMapVO> baseResponse=new BaseResponse<>();
//		if(StringHelper.isNotEmpty(id)){
//			// TODO 按需求添加业务异常判断
//			TSafeRiskMapVO data= riskMapManageService.findDetailById(id);
//			baseResponse.setData(data);
//		}
//		return baseResponse;
//	}
	@ApiOperation(value = "获取 风险地图 详情 ", notes = "Get TSafeRiskMap By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TSafeRiskMapVO> getById(String id){
		BaseResponse<TSafeRiskMapVO> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			TSafeRiskMapDO tSafeRiskMapDO = tSafeRiskMapRepo.getById(id);
			SysFile sysFile = sysFileService.getById(tSafeRiskMapDO.getImageId());
			TSafeRiskMapVO tSafeRiskMapVO = BeanUtil.copyProperties(tSafeRiskMapDO, TSafeRiskMapVO.class);
			tSafeRiskMapVO.setSysFile(sysFile);
			baseResponse.setData(tSafeRiskMapVO);
		}
		return baseResponse;
	}
	public String orgAllPath(String orgId){
		if(StrUtil.isBlank(orgId)) {
			return null;
		}
		// 组装 组装机构全路径
		SysOrg org = orgService.getById(orgId);
		String orgAllPath = org.getParentIds() + "," + orgId;
		return orgAllPath;
	}
}
