package com.testor.module.video.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceManageService;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTO;
import com.testor.module.video.model.domain.TVideoEquipmentCare;
import com.testor.module.video.model.domain.TVideoEquipmentInfo;
import com.testor.module.video.model.dto.TVideoEquipmentInfoDelParam;
import com.testor.module.video.model.dto.TVideoEquipmentInfoParam;
import com.testor.module.video.service.TVideoEquipmentCareService;
import com.testor.module.video.service.TVideoEquipmentInfoService;
import com.testor.module.video.util.ListUtils;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
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.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
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 com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 视频监控——设备信息Controller
 *
 * @author testor-framework
 * @date 2022-11-18 11:41:23
 */
@RestController
@RequestMapping("/module/video")
@Api(value = "TVideoEquipmentInfo", tags = "视频监控——设备信息")
@Slf4j
public class TVideoEquipmentInfoController extends SuperController
{
    @Autowired
    private TVideoEquipmentInfoService tVideoEquipmentInfoService;

	@Autowired
	private SysOrgService sysOrgService;

	@Autowired
	private SpaceManageService spaceManageService;

	@Autowired
	private TVideoEquipmentCareService tVideoEquipmentCareService;

    /* Generated Method*/
	@ApiOperation(value = "新增 视频监控——设备信息", notes = "Add TVideoEquipmentInfo")
	@PostMapping(value = "/add")
	public BaseResponse<TVideoEquipmentInfo>addEntity(@RequestBody TVideoEquipmentInfo addRequest) throws BusinessException {
		BaseResponse<TVideoEquipmentInfo> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			// 判断必填字段和当前登录用户是否为粮库
			this.verifyData(addRequest);
			String id = IdHelper.getId32bit();
            TVideoEquipmentInfo data=BeanHelper.beanToBean(addRequest,  TVideoEquipmentInfo.class);
			data.setId(id);
			data.setDeviceId(data.getDeviceId().trim());
			boolean result= tVideoEquipmentInfoService.save(data);
			if(result){
                TVideoEquipmentInfo newEntity = new TVideoEquipmentInfo();
				newEntity.setId(id);
				baseResponse.setData(newEntity);
			}
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 视频监控——设备信息 ", notes = "Get TVideoEquipmentInfo By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TVideoEquipmentInfo> getById(String id){
		BaseResponse<TVideoEquipmentInfo> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            TVideoEquipmentInfo data= tVideoEquipmentInfoService.getById(id);
			baseResponse.setData(data);
		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 视频监控——设备信息 ", notes = "Update TVideoEquipmentInfo By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TVideoEquipmentInfo updateRequest) throws BusinessException {
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			if (updateRequest.getMonitorLocation() != null){
				//根据地点id获取
				String[] split =updateRequest.getMonitorLocation().split(",");
				if (split.length>1){
					List<String> typeList = new ArrayList<>();
					List<String> spaceList = new ArrayList<>();
					for (int j = 0; j < split.length; j++) {
						//根据地点id获取空间信息
						TSafeSpaceDTO space = spaceManageService.findById(split[j]);
						if (space == null || space.getLevel() !=2){
							throw new BusinessException("空间地址不正确");
						}
						typeList.add(space.getSpaceTypeId());
						spaceList.add(space.getSpaceId());
					}
					String typeStr = ListUtils.parseListToStr(ListUtils.removeDuplicationByHashSet(typeList));
					String spaceStr = ListUtils.parseListToStr(ListUtils.removeDuplicationByHashSet(spaceList));
					updateRequest.setSpaceId(spaceStr);
					updateRequest.setSpaceTypeId(typeStr);
				}else{
					for (int j = 0; j < split.length; j++) {
						//根据地点id获取空间信息
						TSafeSpaceDTO space = spaceManageService.findById(split[j]);
						if (space == null || space.getLevel() !=2){
							throw new BusinessException("空间地址不正确");
						}
						updateRequest.setSpaceId(space.getSpaceId());
						updateRequest.setSpaceTypeId(space.getSpaceTypeId());
					}
				}
			}
			TVideoEquipmentInfo byId = tVideoEquipmentInfoService.getById(updateRequest.getId());
			if (StringUtils.isNotBlank(updateRequest.getDeviceId())){
				updateRequest.setDeviceId(updateRequest.getDeviceId().trim());
				if (!byId.getDeviceId().equals(updateRequest.getDeviceId())){
					QueryWrapper<TVideoEquipmentInfo> queryWrapper = new QueryWrapper<>();
					queryWrapper.eq("status","0");
					queryWrapper.eq("device_id",updateRequest.getDeviceId());
					int count = tVideoEquipmentInfoService.count(queryWrapper);
					if (count>0){
						throw new BusinessException("监控设备编号不能重复");
					}
				}
			}
			if (StringUtils.isNotBlank(updateRequest.getEquipmentName())){
				if (!byId.getEquipmentName().equals(updateRequest.getEquipmentName())) {
					QueryWrapper<TVideoEquipmentInfo> queryWrapper = new QueryWrapper<>();
					queryWrapper.eq("status","0");
					queryWrapper.eq("equipment_name",updateRequest.getEquipmentName());
					int count = tVideoEquipmentInfoService.count(queryWrapper);
					if (count>0){
						throw new BusinessException("监控设备名称不能重复");
					}
				}
			}
            TVideoEquipmentInfo data=BeanHelper.beanToBean(updateRequest, TVideoEquipmentInfo.class);
			boolean result= tVideoEquipmentInfoService.updateById(data);
			//如果转盯防添加记录
			if(updateRequest.getIsEye() != null ){
				if (1 == updateRequest.getIsEye()) {
					TVideoEquipmentCare tVideoEquipmentCare = new TVideoEquipmentCare();
					tVideoEquipmentCare.setUserId(getUserId());
					tVideoEquipmentCare.setDeviceId(updateRequest.getId());
					tVideoEquipmentCareService.save(tVideoEquipmentCare);
				}else {
					tVideoEquipmentCareService.remove(new LambdaQueryWrapper<TVideoEquipmentCare>().eq(TVideoEquipmentCare::getUserId,getUserId()).eq(TVideoEquipmentCare::getDeviceId,updateRequest.getId()));
				}
			}
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "删除 视频监控——设备信息 ", notes = "delete TVideoEquipmentInfo By Id")
	@PutMapping(value = "/delete")
	public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TVideoEquipmentInfoDelParam deleteRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(deleteRequest)&&StringHelper.isNotEmpty(deleteRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TVideoEquipmentInfo data= new TVideoEquipmentInfo();
			data.setId(deleteRequest.getId());
			data.setStatus(BizConstants.STATUS_DELETE);
			boolean result= tVideoEquipmentInfoService.updateById(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "批量删除视频监控——设备信息", notes = "delete TVideoEquipmentInfo by batch Id")
	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody TVideoEquipmentInfoDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<TVideoEquipmentInfo> tVideoEquipmentInfoList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                TVideoEquipmentInfo data= new TVideoEquipmentInfo();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tVideoEquipmentInfoList.add(data);
			}
			boolean result = tVideoEquipmentInfoService.updateBatchById(tVideoEquipmentInfoList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 视频监控——设备信息 分页列表", notes = "List TVideoEquipmentInfo with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<TVideoEquipmentInfo>>listEntity(TVideoEquipmentInfoParam param) throws BusinessException {
		BaseResponse<BaseResponseList<TVideoEquipmentInfo>>baseResponse=new BaseResponse<>();
		Long page=
				StringHelper.isEmpty(param.getPage())?BizConstants.PAGE:Long.valueOf(param.getPage());
		Long limit=
				StringHelper.isEmpty(param.getLimit())?BizConstants.LIMIT:Long.valueOf(param.getLimit());
		Page<TVideoEquipmentInfo> resultPage=new Page<>(page,limit);
		//获取登录用户信息id
		UserInfo loginUser = ContextUtils.getLoginUser();
		//判断登录用户属于组织的那一集别
		String loginOrgId = loginUser.getOrgId();
		SysOrg orgInfo= sysOrgService.getById(loginOrgId);
		if (orgInfo != null) {
			BigDecimal treeLevel = orgInfo.getTreeLevel();
			int flag = treeLevel.compareTo(BigDecimal.valueOf(3));
			String childrenOrgId;
			if (flag == -1) {
				//总公司,获取粮库列表
				List<SysOrg> childrenById = this.getChildrenById(loginOrgId);
				childrenOrgId = childrenById.get(0).getOrgId();
			} else if (flag == 1) {
				//粮库下面的分部门，通过parneids里面获取粮库id
				String[] split =orgInfo.getParentIds().split(",");
				childrenOrgId = split[2];
			} else {
				childrenOrgId = loginOrgId;
			}
			param.setOrgId(childrenOrgId);
		}else{
			throw new BusinessException("数据异常");
		}
		// TODO 根据需求修改查询条件及查询参数
		IPage<TVideoEquipmentInfo> resultList= tVideoEquipmentInfoService.myList(resultPage,param);
		BaseResponseList<TVideoEquipmentInfo> baseResponseList=new BaseResponseList<>();
		List<TVideoEquipmentInfo> records = resultList.getRecords();
		for (TVideoEquipmentInfo record : records) {
			if (StringUtils.isBlank(record.getMonitorLocation())||"NULL".equals(record.getMonitorLocation())) {
				List<String> list =new ArrayList<>();
				record.setMonitorLocationName(list);
				record.setMonitorLocation("");
				continue;
			}
			//根据位置id返回位置名称
			String[] split = record.getMonitorLocation().split(",");
			List<String> monitorLocationName = new ArrayList<>();
			for (int i = 0; i < split.length; i++) {
				String s = split[i];
				//获取区域
				TSafeSpaceDTO byId = spaceManageService.findById(s);
				//获取场所
				TSafeSpaceDTO byId1 = spaceManageService.findById(byId.getSpaceId());
				monitorLocationName.add(byId1.getName()+" > "+byId.getName());
			}
			record.setMonitorLocationName(monitorLocationName);
		}
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}
	private List<SysOrg> getChildrenById(String orgId) {
		QueryWrapper<SysOrg> queryWrapper = new QueryWrapper();
		queryWrapper.eq("is_dept", 0);
		queryWrapper.like("parent_ids", orgId);
		return sysOrgService.list(queryWrapper);
	}
	@ApiOperation(value = "获取 视频监控——设备信息 列表", notes = "List TVideoEquipmentInfo all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<TVideoEquipmentInfo>>listAllEntity(TVideoEquipmentInfoParam param){
		BaseResponse<BaseResponseList<TVideoEquipmentInfo>>baseResponse=new BaseResponse<>();
		// TODO 根据需求修改查询条件及查询参数
		QueryWrapper<TVideoEquipmentInfo> queryWrapper=this.createQuery(param);
		List<TVideoEquipmentInfo> resultList=tVideoEquipmentInfoService.list(queryWrapper);
		BaseResponseList<TVideoEquipmentInfo> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "批量导入设备信息", notes = "")
	@PostMapping("/import")
	public BaseResponse imports(@RequestParam("file") MultipartFile file) throws Exception {
		return tVideoEquipmentInfoService.imports(file);
	}

	@ApiOperation(value = "下载监控视频批量导入模板（视频监控设备量导入模板_1669626232243.xlsx）")
	@GetMapping(value = "/downloadWorkareaTemplate")
	public void downloadWorkareaTemplate(HttpServletResponse response, String fileDowName) {
		UserInfo curUser = ContextUtils.getLoginUser();
		String curUserOrgId = curUser.getOrgId();
		tVideoEquipmentInfoService.downloadWorkareaTemplate(response, fileDowName, curUserOrgId);
	}
    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TVideoEquipmentInfo> createQuery(TVideoEquipmentInfoParam queryParam){
		QueryWrapper<TVideoEquipmentInfo> queryWrapper=new QueryWrapper<>();
		if(StringHelper.isNotEmpty(queryParam.getRefId())){
			queryWrapper.eq(TVideoEquipmentInfo.REF_ID,queryParam.getRefId());
		}
		if(StringHelper.isNotEmpty(queryParam.getParentId())){
			queryWrapper.eq(TVideoEquipmentInfo.PARENT_ID,queryParam.getParentId());
		}
		if(StringHelper.isNotEmpty(queryParam.getTenantId())){
			queryWrapper.eq(TVideoEquipmentInfo.TENANT_ID,queryParam.getTenantId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessId())){
			queryWrapper.eq(TVideoEquipmentInfo.PROCESS_ID,queryParam.getProcessId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessStatus())){
			queryWrapper.eq(TVideoEquipmentInfo.PROCESS_STATUS,queryParam.getProcessStatus());
		}
		if(StringHelper.isNotEmpty(queryParam.getOrgId())){
			queryWrapper.eq(TVideoEquipmentInfo.ORG_ID,queryParam.getOrgId());
		}
		if(StringHelper.isNotEmpty(queryParam.getOrgName())){
			queryWrapper.like(TVideoEquipmentInfo.ORG_NAME,queryParam.getOrgName());
		}
		if(StringHelper.isNotEmpty(queryParam.getEquipmentName())){
			queryWrapper.like(TVideoEquipmentInfo.EQUIPMENT_NAME,queryParam.getEquipmentName());
		}
		if(StringHelper.isNotEmpty(queryParam.getInstallationLocation())){
			queryWrapper.eq(TVideoEquipmentInfo.INSTALLATION_LOCATION,queryParam.getInstallationLocation());
		}
		if(StringHelper.isNotEmpty(queryParam.getDeviceId())){
			queryWrapper.eq(TVideoEquipmentInfo.DEVICE_ID,queryParam.getDeviceId());
		}
		if(StringHelper.isNotEmpty(queryParam.getMonitorLocation())){
			queryWrapper.eq(TVideoEquipmentInfo.MONITOR_LOCATION,queryParam.getMonitorLocation());
		}
		if(ObjectHelper.isNotEmpty(queryParam.getIsEye())){
			queryWrapper.eq(TVideoEquipmentInfo.IS_EYE,queryParam.getIsEye());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TVideoEquipmentInfo.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TVideoEquipmentInfo.STATUS, BizConstants.STATUS_DELETE);
		}
		if (StringHelper.isNotEmpty(queryParam.getOrderBy())){
			if(StringHelper.isNotEmpty(queryParam.getOrderType())
					&&BizConstants.ASC.equals(queryParam.getOrderType())){
				queryWrapper.orderByAsc(queryParam.getOrderBy());
			}else{
				queryWrapper.orderByDesc(queryParam.getOrderBy());
			}
		}else{
			queryWrapper.orderByDesc(TVideoEquipmentInfo.UPDATE_DATE);
		}
		return queryWrapper;
	}

	private void verifyData(TVideoEquipmentInfo addRequest) throws BusinessException {
		if (!StringUtils.isNotBlank(addRequest.getEquipmentName())){
			throw new BusinessException("请求参数有误");
		}
		if (StringUtils.isBlank(addRequest.getInstallationLocation())){
			throw new BusinessException("请求参数有误");
		}
		if (StringUtils.isBlank(addRequest.getDeviceId())){
			throw new BusinessException("请求参数有误");
		}
		String orgId = ContextUtils.getLoginUser().getOrgId();
		SysOrg byId = sysOrgService.getById(orgId);
		String orgName = byId.getOrgName();
		BigDecimal treeLevel = byId.getTreeLevel();
		int i = treeLevel.compareTo(new BigDecimal("3"));
		if (i < 0){
			throw new BusinessException("只有粮库才能创建视频设备信息");
		}else if (i>0){
			String[] split = byId.getParentIds().split(",");
			String parentId = split[2];
			SysOrg byId1 = sysOrgService.getById(parentId);
			orgId=parentId;
			orgName = byId1.getOrgName();
		}
		addRequest.setOrgId(orgId);
		addRequest.setOrgName(orgName);
		//校验监控设备名称，监控设备编号不能重复
		QueryWrapper<TVideoEquipmentInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("status","0").eq("org_id",orgId)
				.and(wrapper->wrapper.eq("equipment_name",addRequest.getEquipmentName()).or().eq("device_id",addRequest.getDeviceId()));
		int count = tVideoEquipmentInfoService.count(queryWrapper);
		if (count>0){
			throw new BusinessException("监控设备和监控设备编号不能重复");
		}
		//根据地点id获取
		String[] split = addRequest.getMonitorLocation().split(",");
		if (split.length>1){
			List<String> typeList = new ArrayList<>();
			List<String> spaceList = new ArrayList<>();
			for (int j = 0; j < split.length; j++) {
				//根据地点id获取空间信息
				TSafeSpaceDTO space = spaceManageService.findById(split[j]);
				if (space == null || space.getLevel() !=2){
					throw new BusinessException("空间地址不正确");
				}
				typeList.add(space.getSpaceTypeId());
				spaceList.add(space.getSpaceId());
			}
			String typeStr = ListUtils.parseListToStr(ListUtils.removeDuplicationByHashSet(typeList));
			String spaceStr = ListUtils.parseListToStr(ListUtils.removeDuplicationByHashSet(spaceList));
			addRequest.setSpaceId(spaceStr);
			addRequest.setSpaceTypeId(typeStr);
		}else{
			for (int j = 0; j < split.length; j++) {
				//根据地点id获取空间信息
				TSafeSpaceDTO space = spaceManageService.findById(split[j]);
				if (space == null || space.getLevel() !=2){
					throw new BusinessException("空间地址不正确");
				}
				addRequest.setSpaceId(space.getSpaceId());
				addRequest.setSpaceTypeId(space.getSpaceTypeId());
			}
		}
	}

//	@GetMapping("getspacelist")
//	@ApiOperation("获取空间台账树形列表")
//	public BaseResponse<List<SpaceInfo>> getSpaceList() throws BusinessException {
//		//根据登录用户企业id获取空间台账信息
//		UserInfo loginUser = ContextUtils.getLoginUser();
//		if (loginUser == null){
//			throw new BusinessException("登录用户为空");
//		}
//		spaceManageService.findLisByOrgId()
//	}
}
