package com.yeejoin.amos.boot.module.common.biz.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.constants.BizConstant;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.module.common.api.core.framework.PersonIdentify;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.dto.KeySiteDateDto;
import com.yeejoin.amos.boot.module.common.api.dto.KeySiteDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgMenuDto;
import com.yeejoin.amos.boot.module.common.api.entity.KeySite;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.service.IKeySiteService;
import com.yeejoin.amos.boot.module.common.api.service.IOrgUsrService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.KeySiteServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.SourceFileServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.WaterResourceServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 重点部位
 *
 * @author system_generator
 * @date 2021-07-26
 */
@RestController
@Api(tags = "重点部位Api")
@RequestMapping(value = "/common/key-site")
public class KeySiteController extends BaseController {

	@Autowired
	KeySiteServiceImpl keySiteServiceImpl;
	@Autowired
	IKeySiteService keySiteService;

	@Autowired
	IOrgUsrService iOrgUsrService;

	@Autowired
	SourceFileServiceImpl sourceFileService;

	@Autowired
	EquipFeignClient equipFeignClient;

	@Value("${auth-key-key-site:key_site_info}")
	private String authKey;

	/**
	 * 新增重点部位
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增重点部位", notes = "新增重点部位")
	public ResponseModel<KeySiteDto> save(@RequestBody KeySiteDto model) {
//		JSONObject json = getBulid(model.getBuildingId());
//		if (json != null && StringUtils.isNotBlank(json.getString("latitude"))
//				&& StringUtils.isNotBlank(json.getString("longitude"))) {
//			model.setLatitude(Double.parseDouble(json.getString("latitude")));
//			model.setLongitude(Double.parseDouble(json.getString("longitude")));
//		}
		model.setIsDelete(false);
		if (model.getAddressDesc() != null) {
			JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(model.getAddressDesc());
			model.setAddressDesc(address.getString(BizConstant.ADDRESS));
			if (!"0".equals(address.getString(BizConstant.LONGITUDE))) {
				model.setLongitude(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
			}
			if (!"0".equals(address.getString(BizConstant.LATITUDE))) {
				model.setLatitude(Double.valueOf(address.getString(BizConstant.LATITUDE)));
			}
		}
		List<String> ids = new ArrayList<String>();
		ids.add(model.getBuildingId().toString());
		Map<String, String> map3 = keySiteService.getNodeAllParentIds(ids);
		model.setParentBuildingId(map3.get(model.getBuildingId().toString()));
		KeySiteDto entity = keySiteService.save(model);
		return ResponseHelper.buildResponse(entity);
	}

	public static JSONObject getLongLatFromAddress(String address) {
		JSONObject result = new JSONObject();
		result.put(BizConstant.ADDRESS, "");
		result.put(BizConstant.LONGITUDE, "0");
		result.put(BizConstant.LATITUDE, "0");
		if (StringUtils.isNotEmpty(address)) {
			String[] addressData = address.split("@address@");
			if (addressData.length > 1) {
				result.put(BizConstant.ADDRESS, addressData[0]);
				JSONObject langLatObj = JSON.parseObject(addressData[1]);
				if (StringUtils.isNotEmpty(langLatObj.getString(BizConstant.LONGITUDE))) {
					result.put(BizConstant.LONGITUDE, langLatObj.getString(BizConstant.LONGITUDE));
				} else {
					result.put(BizConstant.LONGITUDE, "0");
				}
				if (StringUtils.isNotEmpty(langLatObj.getString(BizConstant.LATITUDE))) {
					result.put(BizConstant.LATITUDE, langLatObj.getString(BizConstant.LATITUDE));
				} else {
					result.put(BizConstant.LATITUDE, "0");
				}
			} else {
				result.put(BizConstant.ADDRESS, addressData[0]);
			}
		}
		return result;
	}

	public JSONObject getBulid(Long id) {
		ResponseModel<Object> equipObj = equipFeignClient.getOne(id);
		JSONObject equipjSONObject = JSONObject.parseObject(JSONObject.toJSONString(equipObj.getResult()));
		if (!equipjSONObject.containsKey("parentId")) {
			return null;
		}
		if (!"0".equals(equipjSONObject.getString("parentId"))) {
			String parentId = equipjSONObject.getString("parentId");
			if (StringUtils.isNotBlank(parentId)) {
				return getBulid(Long.parseLong(parentId));
			}
		}
		return equipjSONObject;
	}

	/**
	 * 根据sequenceNbr更新
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "update/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新重点部位", notes = "根据sequenceNbr更新重点部位")
	public ResponseModel<Boolean> updateBySequenceNbrKeySite(@RequestBody KeySiteDto model) {
//		JSONObject json = getBulid(model.getBuildingId());
//		if (json != null) {
//			model.setLatitude(Double.parseDouble(json.getString("latitude")));
//			model.setLongitude(Double.parseDouble(json.getString("longitude")));
//		}
		if (model.getAddressDesc() != null) {
			JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(model.getAddressDesc());
			model.setAddressDesc(address.getString(BizConstant.ADDRESS));
			if (!"0".equals(address.getString(BizConstant.LONGITUDE))) {
				model.setLongitude(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
			}
			if (!"0".equals(address.getString(BizConstant.LATITUDE))) {
				model.setLatitude(Double.valueOf(address.getString(BizConstant.LATITUDE)));
			}
		}
		return ResponseHelper.buildResponse(keySiteService.update(model, getUserInfo()));
	}

	/**
	 * 根据sequenceNbr删除
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@DeleteMapping(value = "delete")
	@ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除重点部位", notes = "根据sequenceNbr删除重点部位")
	public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request,
			@RequestParam(value = "ids") String ids) {
		List<Long> sequenceNbrList = new ArrayList<>();
		/* BUG 2670 litw start */
		String[] idsArr = ids.split(",");
		for (String str : idsArr) {
			sequenceNbrList.add(Long.valueOf(str));
		}
		/* BUG 2670 end */
		return ResponseHelper.buildResponse(keySiteService.deleteById(sequenceNbrList));
	}

	/**
	 * 根据sequenceNbr查询
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "find/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个重点部位", notes = "根据sequenceNbr查询单个重点部位")
	public ResponseModel<KeySiteDto> selectOne(@PathVariable Long sequenceNbr) {
		List<String> list = new ArrayList<String>();
		Map<String, List<AttachmentDto>> files = sourceFileService.getAttachments(sequenceNbr);
		KeySiteDto dto = keySiteService.getSequenceNbr(sequenceNbr);
		if (files != null && dto != null) {
			dto.setAttachments(files);
			JSONArray array = JSONArray.parseArray(JSONArray.toJSONString(files.get("keySitePhoto")));
			if (array != null && array.size() > 0) {
				for (Object i : array) {
					JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(i));
					list.add(object.getString("url"));
				}
			}
		}
		dto.setAttachmentsList(list);

		if(null != dto.getLongitude() && null != dto.getLatitude()) {
			dto.setAddressDesc(dto.getAddressDesc().concat("@address@").concat("{\"longitude\":").
					concat(dto.getLongitude().toString().concat(",\"latitude\":").concat(dto.getLatitude().toString().concat("}"))));
		}

		return ResponseHelper.buildResponse(dto);
	}

	/**
	 * 列表分页查询
	 *
	 * @return //
	 */
//	@TycloudOperation(ApiLevel = UserType.AGENCY)
//	@GetMapping(value = "/page")
//	@ApiOperation(httpMethod = "GET", value = "重点部位分页查询", notes = "重点部位分页查询")
//	public ResponseModel<IPage<KeySiteDto>> queryForPage(@RequestParam(value = "current") int current,
//			@RequestParam(value = "size") int size, @RequestParam(required = false) String name,
//			@RequestParam(required = false) Long buildingId, @RequestParam(required = false) String fireEnduranceRate,
//			@RequestParam(required = false) String useNature, @RequestParam(required = false) String fireFacilitiesInfo,
//			@RequestParam(required = false) String bizOrgCode) {
//		Page<KeySiteDto> page = new Page<KeySiteDto>();
//		page.setCurrent(current);
//		page.setSize(size);
//		return ResponseHelper.buildResponse(keySiteServiceImpl.getPageList(page, name, buildingId, fireEnduranceRate,
//				useNature, fireFacilitiesInfo, bizOrgCode));
//	}

	@PersonIdentify
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "机场单位部门部位统计树", notes = "机场单位部门部位统计树")
	@GetMapping(value = "/getOrguserTree")
	public ResponseModel<List<OrgMenuDto>> getOrgUserTree() {
		// 获取登陆人角色
		ReginParams reginParams = getSelectedOrgInfo();
		// 权限赋值
		PermissionInterceptorContext.setDataAuthRule(authKey);
		List<OrgMenuDto> list = keySiteService.getOrgUserTree(reginParams);
		return ResponseHelper.buildResponse(list);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "建筑部位树", notes = "建筑部位树")
	@GetMapping(value = "/getBuildTree/{buildingId}")
	public ResponseModel<List<OrgMenuDto>> getBuildTree(@PathVariable Long buildingId) {
		return ResponseHelper.buildResponse(keySiteService.getBuildAndKeyTree(buildingId));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "部位", notes = "部位")
	@GetMapping(value = "/getKeySiteDate")
	public ResponseModel<List<KeySiteDateDto>> getKeySiteDate(@RequestParam(required = false) Long id) {
		return ResponseHelper.buildResponse(keySiteService.getKeySiteDate(id));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "通过名称模糊查询重点部位的信息", notes = "通过名称模糊查询重点部位的信息")
	@GetMapping(value = "/getKeySiteDateByNameLike")
	public ResponseModel<List<KeySite>> getKeySiteDateByNameLike(@RequestParam(required = false) Long companyId) {
		return ResponseHelper.buildResponse(keySiteService.getKeySiteDateByNameLike(companyId));
	}

	@PersonIdentify
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/companyTreeByUserAndType", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据登录人及类型获取公司树", notes = "根据登录人及类型获取公司树")
	public ResponseModel<List<OrgMenuDto>> companyTreeByUserAndType(String type) {
		// 获取登陆人角色
		ReginParams reginParams = getSelectedOrgInfo();
		// 权限赋值
		PermissionInterceptorContext.setDataAuthRule(authKey);
		if ("all".equals(type)) {
			List<OrgMenuDto> menus = iOrgUsrService.companyTreeByUserAndType(reginParams, null, null);
			return ResponseHelper.buildResponse(menus);
		} else {
			List<OrgMenuDto> menus = iOrgUsrService.companyTreeByUserAndType(reginParams, OrgPersonEnum.公司.getKey(), null);
			return ResponseHelper.buildResponse(menus);
		}
	}

	/**
	 * 列表分页查询
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET", value = "重点部位分页查询", notes = "重点部位分页查询")
	public ResponseModel<IPage<KeySiteDto>> queryForPage(@RequestParam(value = "current") int current,
			@RequestParam(value = "size") int size, @RequestParam(required = false) String name,
			@RequestParam(required = false) Long buildingId, @RequestParam(required = false) String fireEnduranceRate,
			@RequestParam(required = false) String useNature, @RequestParam(required = false) String fireFacilitiesInfo,
			@RequestParam(required = false) String bizOrgCode,@RequestParam(required = false) String belongId) {
		Page<KeySiteDto> page = new Page<KeySiteDto>();
		page.setCurrent(current);
		page.setSize(size);

		return ResponseHelper.buildResponse(keySiteServiceImpl.getPageList(page, name, buildingId, fireEnduranceRate,
				useNature, fireFacilitiesInfo, bizOrgCode,belongId));
	}

	/**
	 * 列表分页查询 重点部位权限控制，前端页面为studio配置无法控制传参，改为后端控制
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/pageNew")
	@ApiOperation(httpMethod = "GET", value = "重点部位分页查询", notes = "重点部位分页查询")
	public ResponseModel<IPage<KeySiteDto>> queryForPageNew(@RequestParam(value = "current") int current,
			@RequestParam(value = "size") int size, @RequestParam(required = false) String name,
			@RequestParam(required = false) Long buildingId, @RequestParam(required = false) String fireEnduranceRate,
			@RequestParam(required = false) String useNature, @RequestParam(required = false) String fireFacilitiesInfo,
			@RequestParam String bizOrgCode) {
		Page<KeySiteDto> page = new Page<KeySiteDto>();
		page.setCurrent(current);
		page.setSize(size);

		return ResponseHelper.buildResponse(keySiteServiceImpl.getPageList(page, name, buildingId, fireEnduranceRate,
				useNature, fireFacilitiesInfo, bizOrgCode,null));
	}

	@PersonIdentify
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/keySiteCountAndBuildingTree", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据登录人角色获取当前单位下的所在建筑的重点部位统计值", notes = "根据登录人角色获取当前单位下的所在建筑的重点部位统计值")
	public ResponseModel<List<Map<String, Object>>> keySiteCountAndBuildingTree(@RequestParam String bizOrgCode) {
		return ResponseHelper.buildResponse(keySiteService.keySiteCountAndBuildingTree(bizOrgCode));
	}
}
