package com.zzwtec.third.action.community;

import com.alibaba.fastjson.TypeReference;
import com.zzwtec.third.common.DataObject;
import com.zzwtec.third.common.Page;
import com.zzwtec.third.common.PageIndexHelper;
import com.zzwtec.third.common.Pageing;
import com.zzwtec.third.common.TokenServiceSupport;
import com.zzwtec.third.common.UrlContents;
import com.zzwtec.third.config.redis.RedisService;
import com.zzwtec.third.model.SysuserCache;
import com.zzwtec.third.model.basedata.dto.BuildDTO;
import com.zzwtec.third.model.basedata.dto.BuildODTO;
import com.zzwtec.third.model.basedata.dto.CommunityDTO;
import com.zzwtec.third.model.basedata.dto.DeleteBuildODTO;
import com.zzwtec.third.model.basedata.dto.QueryBuildDTO;
import com.zzwtec.third.model.basedata.dto.QueryDoorODTO;
import com.zzwtec.third.model.basedata.model.Door;
import com.zzwtec.third.services.BuildServiceImpl;
import com.zzwtec.third.services.DoorServiceImpl;
import com.zzwtec.third.utils.BizException;
import com.zzwtec.third.utils.ErrorCode;
import com.zzwtec.third.utils.ResultJsonUtil;
import com.zzwtec.third.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.Collections;
import java.util.List;

/**
 * 楼栋信息管理
 *
 * @author 温欣悦
 * @date 2018/12/6
 */
@Controller
public class AdmBuildController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BuildServiceImpl buildServiceImpl;
    @Autowired
    private DoorServiceImpl doorService;

    private final Logger LOGGER = LoggerFactory.getLogger(AdmBuildController.class);

    /**
     * 获取楼栋分页信息列表
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_BUILD)
    public String getBuildPage() {
        // 获取当前管理的小区Id
        String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
        SysuserCache sysuserCache = redisService.getEntity(token, new TypeReference<SysuserCache>() {
        });
        CommunityDTO currentManageCommunity = sysuserCache.getCurrentManageCommunity();
        // 获取当前页
        String page = request.getParameter("page");
        Integer currentPage = 1;
        if (StringUtil.notEmpty(page)) {
            try {
                currentPage = Integer.parseInt(page);
            } catch (Exception e) {
            }
        }
        // 封装参数
        QueryBuildDTO queryBuildDTO = new QueryBuildDTO();
        queryBuildDTO.setCommunityId(currentManageCommunity.getId());
        queryBuildDTO.setPage(currentPage);
        queryBuildDTO.setToken(token);
        queryBuildDTO.setPageNum(Pageing.PAGE_SIZE);
        // 处理响应页面
        Page<BuildDTO> buildPage = new Page<BuildDTO>();
        try {
            buildPage = buildServiceImpl.queryBuildByCommunityId(queryBuildDTO);
            if (buildPage == null) {
                LOGGER.warn("获取楼栋分页信息为null");
            } else {
                request.setAttribute("pageList", buildPage.getData());
            }
        } catch (BizException e) {
            LOGGER.warn("获取楼栋分页信息失败,", e.getMessage());
        } catch (Exception e) {
            LOGGER.warn("获取楼栋分页信息失败,", e);
        }
        buildPage.setPage(currentPage);
        buildPage.setPageNum(Pageing.PAGE_SIZE);
        PageIndexHelper.setPaging(request, buildPage);
        return "/community/build/view/build_list.html";
    }

    /**
     * 获取添加楼栋的页面
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_BUILD_ADD_FORM_UI)
    public String addBuildFormUI() {
        return "/community/build/view/build_add_form.html";
    }

    /**
     * 获取修改楼栋的页面
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_BUILD_EDIT_FORM_UI)
    public String updateBuildFormUI() {
        try {
            // 获取并存储楼栋信息
            String buildId = request.getParameter("id");
            BuildDTO buildDTO = buildServiceImpl.queryBuildById(buildId);
            request.setAttribute("build", buildDTO);
        } catch (BizException e) {
            LOGGER.warn("根据楼栋id获取楼栋信息失败,", e.getMessage());
        } catch (Exception e) {
            LOGGER.warn("根据楼栋id获取楼栋信息失败", e);
        }

        return "/community/build/view/build_edit_form.html";
    }

    /**
     * 添加楼栋
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_BUILD_ADD)
    public void addBuild(BuildDTO build) {
        DataObject responseJson = new DataObject();
        try {
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            // 封装请求参数
            BuildODTO buildODTO = new BuildODTO();
            buildODTO.setToken(token);
            buildODTO.setCommunityId(build.getCommunityId());
            buildODTO.setName(build.getName());
            buildODTO.setNum(build.getNum());
            buildODTO.setAddress(build.getAddress());
            buildODTO.setLatitude(build.getLatitude());
            buildODTO.setLongitude(build.getLongitude());
            String buildId = buildServiceImpl.addBuild(buildODTO);
            if (StringUtil.isEmpty(buildId)) {
                responseJson = new DataObject(ErrorCode.ERROR_1.getCode(), ErrorCode.ERROR_1.getMessage());
            }
        } catch (BizException e) {
            responseJson = new DataObject(e.getCode(), e.getMessage());
            LOGGER.warn("添加楼栋失败,", e.getMessage());
        } catch (Exception e) {
            LOGGER.warn("添加楼栋失败", e);
            responseJson = new DataObject(ErrorCode.ERROR_1.getCode(), ErrorCode.ERROR_1.getMessage());
        } finally {
            ResultJsonUtil.renderJson(response, responseJson);
        }
    }

    /**
     * 修改楼栋
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_BUILD_UPD)
    public void updateBuild(BuildDTO build) {
        DataObject responseJson = new DataObject();
        try {
            // 获取当前管理的小区Id
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            SysuserCache sysuserCache = redisService.getEntity(token, new TypeReference<SysuserCache>() {
            });
            String communityId = sysuserCache.getCurrentManageCommunity().getId();
            // 封装参数
            BuildODTO buildODTO = new BuildODTO();
            buildODTO.setToken(token);
            buildODTO.setCommunityId(communityId);
            buildODTO.setBuildId(build.getId());
            buildODTO.setName(build.getName());
            buildODTO.setNum(build.getNum());
            buildODTO.setAddress(build.getAddress());
            buildODTO.setLatitude(build.getLatitude());
            buildODTO.setLongitude(build.getLongitude());
            // 远程调用
            buildServiceImpl.updateBuild(buildODTO);
        } catch (BizException e) {
            LOGGER.warn("修改楼栋失败,", e.getMessage());
            responseJson = new DataObject(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.warn("修改楼栋失败", e);
            responseJson = new DataObject(ErrorCode.ERROR_1.getCode(), ErrorCode.ERROR_1.getMessage());
        } finally {
            ResultJsonUtil.renderJson(response, responseJson);
        }
    }

    /**
     * 删除楼栋
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_BUILD_DEL)
    public void deleteBuild() {
        DataObject responseJson = new DataObject();
        try {
            // 获取当前管理的小区Id
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            SysuserCache sysuserCache = redisService.getEntity(token, new TypeReference<SysuserCache>() {
            });
            String communityId = sysuserCache.getCurrentManageCommunity().getId();
            // 获取删除的楼栋id
            String ids = request.getParameter("ids");
            String[] idArray = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList, idArray);
            // 封装查询参数
            DeleteBuildODTO deleteBuildODTO = new DeleteBuildODTO();
            deleteBuildODTO.setToken(token);
            deleteBuildODTO.setCommunityId(communityId);
            deleteBuildODTO.setBuildIds(idList);
            // 远程调用
            buildServiceImpl.deleteBuildByIds(deleteBuildODTO);
        } catch (BizException e) {
            LOGGER.warn("删除楼栋失败,", e.getMessage());
            responseJson = new DataObject(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.warn("删除楼栋失败", e);
            responseJson = new DataObject(ErrorCode.ERROR_1.getCode(), ErrorCode.ERROR_1.getMessage());
        } finally {
            ResultJsonUtil.renderJson(response, responseJson);
        }
    }

    /**
     * 获取房间信息
     * @return
     *
     */
    @RequestMapping(UrlContents.URL_ADM_BUILD_MODEL_DATA)
    public void getBuildData() {
        //输出到浏览器
        DataObject repJson = new DataObject();
        try {
            //获取参数
            String buildId = this.request.getParameter("buildId");
            BuildDTO buildDTO = buildServiceImpl.queryBuildById(buildId);
            repJson.setData(buildDTO);
        } catch (BizException e) {
            LOGGER.warn(e.getMessage(), e);
            repJson = new DataObject(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e.getCause());
            repJson = new DataObject(ErrorCode.ERROR_A_NEGATIVE.getCode(), ErrorCode.ERROR_A_NEGATIVE.getMessage());
        } finally {
            ResultJsonUtil.renderJson(response, repJson);
        }
    }
}
