package com.zzwtec.third.action.community;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zzwtec.third.common.*;
import com.zzwtec.third.config.redis.RedisService;
import com.zzwtec.third.model.basedata.dto.CommunityConfigDTO;
import com.zzwtec.third.common.DataObject;
import com.zzwtec.third.common.ResultJsonUtil;
import com.zzwtec.third.common.TokenServiceSupport;
import com.zzwtec.third.common.UrlContents;
import com.zzwtec.third.model.ObjType;
import com.zzwtec.third.model.SysuserCache;
import com.zzwtec.third.model.basedata.dto.CommunityDTO;
import com.zzwtec.third.model.basedata.dto.QueryCommunityDTO;
import com.zzwtec.third.model.permission.dto.ObjRelationDTO;
import com.zzwtec.third.services.CommunityConfigServiceImpl;
import com.zzwtec.third.services.CommunityServiceImpl;
import com.zzwtec.third.utils.BizException;
import com.zzwtec.third.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 小区管理控制器
 * @author luolanfeng
 * @date  2018-12-06
 *
 */
@Controller
public class AdmCommunityController {

	@Autowired
	private RedisService redisService;

	@Autowired
	private HttpServletResponse response;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	CommunityServiceImpl communityServiceImpl;
	@Autowired
	CommunityConfigServiceImpl communityConfigServiceImpl;

	private Logger logger = LoggerFactory.getLogger(AdmCommunityController.class);

	/**
	 * 获取小区列表用于切换小区
	 *
	 */
	@RequestMapping(UrlContents.URL_ADM_COMMUNITY_LIST)
	public String list(){
		//小区列表只有当前管理小区
		String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
		SysuserCache sysuserCache = redisService.getEntity(tokenId, new TypeReference<SysuserCache>(){});
		CommunityDTO communityDTO = sysuserCache.getCurrentManageCommunity();
		List<CommunityDTO> pageList=new ArrayList<>();
		pageList.add(communityDTO);
		Page<CommunityDTO> page = new Page<>();
		page.setData(pageList);
		page.setPage(1);
		page.setPageNum(1);
		page.setTotal(1);
		setAttr("pageList", pageList);
		PageIndexHelper.setPaging(this.request, page);
		return "/community/community/view/community_list.html";
	}
	/**
	 * 小区详情表单
	 *
	 */
	@RequestMapping(UrlContents.URL_ADM_COMMUNITY_DETAILS_FORM_UI)
	public String detailsFormUI(){
		//当前管理小区名称
		String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
		SysuserCache sysuserCache = redisService.getEntity(tokenId, new TypeReference<SysuserCache>(){});
		CommunityDTO currentManageCommunity=sysuserCache.getCurrentManageCommunity();
		if(currentManageCommunity!=null){
			CommunityConfigDTO communityConfigDTO=null;
			try {
				communityConfigDTO=communityConfigServiceImpl.queryCommunityConfigByCommunityId(currentManageCommunity.getId());
			}catch (Exception e){
				logger.info("查询小区配置信息失败");
			}
			if(communityConfigDTO==null){
				communityConfigDTO=new CommunityConfigDTO();
			}
			//小区设备配置信息
			setConfigureStr(1,communityConfigDTO.getDoorbellConfigure());
			setConfigureStr(2,communityConfigDTO.getEnclosureConfigure());
			JSONObject machineType_json=JSONObject.parseObject(communityConfigDTO.getMachineType());
			if(machineType_json!=null){
				setAttr("doorbellType", machineType_json.get("doorbell"));
				setAttr("enclosureType", machineType_json.get("enclosure"));
			}
			//小区便民电话：[{"type":"类别","list":[{"msg":"显示内容","phone":"电话号码"}]}]
			String communityTelephone=communityConfigDTO.getTelephone();
			setAttr("communityTelephone",communityTelephone );
			setAttr("community", currentManageCommunity);
			setAttr("servicesStr", communityConfigDTO.getServices());
			return "/community/community/view/community_details_form.html";
		}else {
			logger.info("获取当前管理小区信息失败");

			DataObject repJson = new DataObject(500,"获取小区信息失败");
			ResultJsonUtil.renderJson(response, repJson);
			return null;
		}



	}
	/**
	 * 切换小区表单
	 *
	 */
	@RequestMapping(UrlContents.URL_ADM_COMMUNITY_CHANGE_FORM_UI)
	public String changeFormUI(){
		//当前管理小区名称
		String currentManageCommunityName=getPara("currentManageCommunityName");
		if(StringUtil.isEmpty(currentManageCommunityName)){
			currentManageCommunityName="无";
		}
		List<CommunityDTO> communityList=queryManageCommunityList();
		setAttr("communityList",communityList);
		setAttr("currentManageCommunityName",currentManageCommunityName);

		return "/community/community/view/community_change_form.html";
	}
	/**
	 * 获取小区列表用于切换小区
	 *
	 */
	@RequestMapping(UrlContents.URL_ADM_COMMUNITY_CHANGE)
	public void change(){
		DataObject repJson = new DataObject("切换小区成功");
		String communityId=getPara("communityId");
		String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
		SysuserCache sysuserCache = redisService.getEntity(tokenId, new TypeReference<SysuserCache>(){});
		QueryCommunityDTO queryCommunityDTO=new QueryCommunityDTO();
		queryCommunityDTO.setToken(tokenId);
		queryCommunityDTO.setCommunityId(communityId);
		try {
			CommunityDTO communityDTO=communityServiceImpl.queryCommunityInfo(queryCommunityDTO);
			if(communityDTO!=null){
				sysuserCache.setCurrentManageCommunity(communityDTO);
				redisService.saveEntityToJson(tokenId, sysuserCache, 30, TimeUnit.MINUTES);
				request.setAttribute("currentManageCommunityId", communityDTO.getId());
				request.setAttribute("currentManageCommunityName", communityDTO.getName());
			}

		}catch (BizException e){
			repJson.setCode(e.getCode());
			repJson.setMsg(e.getMessage());
		}catch (Exception e){
			logger.info("查询小区信息失败");
			repJson.setCode(500);
			repJson.setMsg("查询小区信息失败");
		}
		ResultJsonUtil.renderJson(response, repJson);
	}




	private List<CommunityDTO> queryManageCommunityList(){
		List<CommunityDTO> manageCommunityList=new ArrayList<>();
		String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
		SysuserCache sysuserCache = redisService.getEntity(tokenId, new TypeReference<SysuserCache>(){});
		//此集合里存的是小区objrelation
		List<ObjRelationDTO> dataAuthList = sysuserCache.getDataAuthList();
		if(dataAuthList!=null && dataAuthList.size()>0){
			dataAuthList.stream().forEach(objRelation->{
				if(ObjType.COMMUNITY.equals(objRelation.getObjType())){
					QueryCommunityDTO queryCommunityDTO=new QueryCommunityDTO();
					queryCommunityDTO.setToken(tokenId);
					queryCommunityDTO.setCommunityId(objRelation.getObjId());
					try {
						manageCommunityList.add(communityServiceImpl.queryCommunityInfo(queryCommunityDTO));
					}catch (Exception e){
						logger.info("查询小区信息失败");
					}

				}
			});

		}

		return manageCommunityList;
	}



	/**
	 * 将设备配置json字符串 转换为页面需要的格式
	 * @param type
	 * @param jsonStr
	 */
	private void setConfigureStr(int type,String jsonStr){
		if(StringUtil.isEmpty(jsonStr)){
			return;
		}
		String prefix="enclosure_";
		if(type==1){
			prefix="doorbell_";
		}
		JSONObject json=JSONObject.parseObject(jsonStr);
		if(json==null){
			return;
		}
		JSONObject talkVideo_json=json.getJSONObject("talkVideo");
		JSONObject adVolume_json=json.getJSONObject("adVolume");
		JSONObject distance_json=json.getJSONObject("distance");

		setAttr(prefix+"lockAuto",json.get("lockAuto"));
		setAttr(prefix+"talkVolume",json.get("talkVolume"));
		setAttr(prefix+"tipsVolume",json.get("tipsVolume"));
		setAttr(prefix+"lockType",json.get("lockType"));
		setAttr(prefix+"lockDelayed",json.get("lockDelayed"));
		setAttr(prefix+"centerIP",json.get("centerIP"));
		setAttr(prefix+"cellIP",json.get("cellIP"));
		setAttr(prefix+"callWait",json.get("callWait"));
		setAttr(prefix+"qcScanningFrame",json.get("qcScanningFrame"));
		setAttr(prefix+"machineType",json.get("machineType"));
		setAttr(prefix+"keyboard",json.get("keyboard"));
		setAttr(prefix+"lightCritical",json.get("lightCritical"));
		setAttr(prefix+"upPic",json.get("upPic"));
		setAttr(prefix+"cardDataType",json.get("cardDataType"));

		if(json.containsKey("adSize") && StringUtil.notEmpty(json.get("adSize"))){
			this.request.setAttribute(prefix+"adSize", json.get("adSize"));
		}else{
//			String adSizeStr=AdScreenEnum.DeviceAdSize.getDeviceAdSizeByDeviceMode(AdScreenEnum.DeviceModel.getDeviceModel(json.get("machineType").toString())).getName();
//			if(!"未知".equals(adSizeStr)){
//				this.request.setAttribute(prefix+"adSize", adSizeStr);
//			}

		}




		if(talkVideo_json!=null){
			setAttr(prefix+"color",talkVideo_json.get("color"));
			setAttr(prefix+"blackAndWhite",talkVideo_json.get("blackAndWhite"));
		}
		if(adVolume_json!=null){
			setAttr(prefix+"low",adVolume_json.get("low"));
			setAttr(prefix+"lowTime",adVolume_json.get("lowTime"));
			setAttr(prefix+"high",adVolume_json.get("high"));
			setAttr(prefix+"highTime",adVolume_json.get("highTime"));
		}
		if(distance_json!=null){
			setAttr(prefix+"distanceswitch",distance_json.get("open"));
			setAttr(prefix+"distance",distance_json.get("distance"));
		}



	}


	private void setAttr(String key, Object value) {
		this.request.setAttribute(key, value);
	}

	private String getPara(String name) {
		return this.request.getParameter(name);
	}

}
