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.ResultJsonUtil;
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.CommunityDTO;
import com.zzwtec.third.model.basedata.dto.DoorDTO;
import com.zzwtec.third.model.basedata.dto.DoorRemoteDTO;
import com.zzwtec.third.model.basedata.dto.QueryDoor2DTO;
import com.zzwtec.third.services.DoorServiceImpl;
import com.zzwtec.third.utils.BizException;
import com.zzwtec.third.utils.ErrorCode;
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.List;

/**
 * 门信息的管理
 *
 * @author 温欣悦
 * @date 2018/12/10
 */
@Controller
public class AdmDoorController {
    @Autowired
    private DoorServiceImpl doorServiceImpl;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private RedisService redisService;

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

    /**
     * 获取门分页信息列表
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_DOOR_LIST)
    public String getDoorPage() {
        // 获取小区Id和楼栋id
        String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
        SysuserCache sysuserCache = redisService.getEntity(token, new TypeReference<SysuserCache>() {
        });
        CommunityDTO currentManageCommunity = sysuserCache.getCurrentManageCommunity();
        String communityId = currentManageCommunity.getId();
        String buildId = request.getParameter("buildId_s");
        String buildName = request.getParameter("buildName_s");
        // 如果去掉了名字就代表没选择楼栋
        if (StringUtil.isEmpty(buildName)) {
            buildId = null;
        }
        // 封装分页查询参数
        Page<DoorDTO> requestPage = new Page<>();
        // 封装小区和楼栋id
        DoorDTO doorDTO = new DoorDTO();
        doorDTO.setCommunityId(communityId);
        doorDTO.setBuildId(buildId);
        List<DoorDTO> data = new ArrayList<>();
        data.add(doorDTO);
        requestPage.setData(data);
        // 封装当前页
        String page = request.getParameter("page");
        Integer currentPage = 1;
        if (StringUtil.notEmpty(page)) {
            currentPage = Integer.parseInt(page);
        }
        requestPage.setPage(currentPage);
        requestPage.setPageNum(12);
        // 处理响应数据
        try {
            requestPage = doorServiceImpl.queryPageDoorByCommunityIdOrBuildId(requestPage);
            if (requestPage == null) {
                LOGGER.warn("获取门分页信息为null");
            } else {
                request.setAttribute("pageList", requestPage.getData());
            }
        } catch (BizException e) {
            LOGGER.warn("获取门分页信息失败,", e.getMessage());
        } catch (Exception e) {
            LOGGER.warn("获取门分页信息失败,", e);
        }
        request.setAttribute("buildId_s", buildId);
        request.setAttribute("buildName_s", buildName);
        requestPage.setPage(currentPage);
        requestPage.setPageNum(Pageing.PAGE_SIZE);
        PageIndexHelper.setPaging(request, requestPage);
        return "/community/door/view/door_list.html";
    }

    /**
     * 获取修改门的表单页面
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_DOOR_EDIT_FORM_UI)
    public String editDoorFormUI() {
        try {
            // 获取id和token，并封装到请求参数中
            String doorId = request.getParameter("id");
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            QueryDoor2DTO queryDoor2DTO = new QueryDoor2DTO();
            queryDoor2DTO.setToken(token);
            queryDoor2DTO.setDoorId(doorId);
            // 获取门信息
            DoorDTO doorDTO = doorServiceImpl.queryDoorById(queryDoor2DTO);
            request.setAttribute("door", doorDTO);
            if (doorDTO != null) {
                if (doorDTO.getRemote()) {
                    request.setAttribute("doorRemote", 1);
                } else {
                    request.setAttribute("doorRemote", 0);
                }
            }
        } catch (BizException e) {
            LOGGER.warn("根据门id获取门信息失败,", e.getMessage());
        } catch (Exception e) {
            LOGGER.warn("根据门id获取门信息失败", e);
        }

        return "/community/door/view/door_edit_form.html";
    }

    /**
     * 修改门信息（只能修改门是否能远程开门的功能）
     *
     * @author wxy
     */
    @RequestMapping(UrlContents.URL_ADM_DOOR_UPD)
    public void updateDoor() {
        DataObject responseJson = new DataObject();
        try {
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            String id = request.getParameter("id");
            String doorRemote = request.getParameter("doorRemote");
            int remote = Integer.parseInt(doorRemote);
            DoorRemoteDTO doorRemoteDTO = new DoorRemoteDTO();
            doorRemoteDTO.setToken(token);
            doorRemoteDTO.setDoorId(id);
            doorRemoteDTO.setRemote(remote);
            doorServiceImpl.updateDoorRemote(doorRemoteDTO);
        } 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);
        }
    }
}

