package com.zzwtec.third.action.community;

import com.alibaba.fastjson.JSONArray;
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.SysuserCache;
import com.zzwtec.third.model.UserCellType;
import com.zzwtec.third.model.basedata.dto.*;
import com.zzwtec.third.services.BuildServiceImpl;
import com.zzwtec.third.services.CellServiceImpl;
import com.zzwtec.third.services.UserCellServiceImpl;
import com.zzwtec.third.utils.*;
import com.zzwtec.third.utils.ResultJsonUtil;
import org.apache.commons.lang3.StringUtils;
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.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ShangJia
 * @date 2018/12/6
 */
@Controller
public class AdmCellController {
    private static final Logger logger = LoggerFactory.getLogger(AdmCellController.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @Autowired
    private CellServiceImpl cellService;
    @Autowired
    private BuildServiceImpl buildService;
    @Autowired
    private UserCellServiceImpl userCellService;

    /**
     * 获取房间列表
     */
//    @PowerType(adminType=AdminType.Admin,value=AccountPowerType.ORGSEE)
    @RequestMapping(UrlContents.URL_ADM_CELL)
    public String index() {
        //输出到浏览器的提示
        DataObject repJson = new DataObject();
        String buildId = getParam("search_buildId");
        String buildName = getParam("search_buildName");
        //第一次进入页面
        if(StringUtil.isEmpty(buildId)){
            //第一次进入页面的标志
            setAttr("cellFirstIn", 1);
            Page page = new Page();
            PageIndexHelper.setPaging(this.request, page);
            return "/community/cell/view/cell_list.html";
        }else {
            try {
                String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
                String pageString = getParam("page");
                int currentPage = StringUtil.isEmpty(pageString)?1:Integer.parseInt(pageString);
                //封装数据
                QueryCellODTO queryCellODTO = new QueryCellODTO();
                queryCellODTO.setToken(tokenId);
                queryCellODTO.setPage(currentPage);//第一次进入列表默认是第一页
                queryCellODTO.setBuildId(buildId);
                //根据楼栋分页查询房间
                Page<CellDTO> page = cellService.queryCellByBuildId(queryCellODTO);
                setAttr("pageList", page.getData());
                //设置分页条
                page.setPage(currentPage);
                PageIndexHelper.setPaging(this.request, page);
                setAttr("search_buildName", buildName);
                setAttr("search_buildId", buildId);
                return "/community/cell/view/cell_list.html";
            } catch (BizException e) {
                logger.warn(e.getMessage(), e);
                repJson = new DataObject(e.getCode(), e.getMessage());
                ResultJsonUtil.renderJson(response, repJson);
                return null;
            } catch (Exception e) {
                logger.error(e.getMessage(), e.getCause());
                repJson = new DataObject(ErrorCode.ERROR_A_NEGATIVE.getCode(), ErrorCode.ERROR_A_NEGATIVE.getMessage());
                ResultJsonUtil.renderJson(response, repJson);
                return null;
            }
        }
    }

    /**
     * 获取添加表单添加界面
     */
//    @PowerType(adminType=AdminType.Admin,value=AccountPowerType.ORGADD)
    @RequestMapping(UrlContents.URL_ADM_CELL_ADD_FORM_UI)
    public String addFormUI(){
        //从SysuserCache中取到当前的小区id
        String tokenId = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
        SysuserCache sysuserCache = redisService.getEntity(tokenId, new TypeReference<SysuserCache>(){});
        CommunityDTO dto = sysuserCache.getCurrentManageCommunity();
        setAttr("communityId", dto.getId());
        setAttr("communityName", dto.getName());
        return "/community/cell/view/cell_add_form.html";
    }

    /**
     * 添加房间
     * @param cellDTO
     */
    @RequestMapping(UrlContents.URL_ADM_CELL_ADD)
    public void add(@ModelAttribute("cellDTO") CellDTO cellDTO){
        //输出到浏览器的提示
        DataObject repJson;
        try {
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            //封装数据
            CellODTO cellODTO = BeanUtil.copyProperties(CellODTO.class, cellDTO);
            cellODTO.setToken(token);
            cellODTO.setCellId(cellDTO.getId());
            cellService.addCell(cellODTO);
            repJson = new DataObject("添加房间成功");
            ResultJsonUtil.renderJson(response, repJson);
            return;
        } catch (BizException e) {
            logger.warn(e.getMessage(), e);
            repJson = new DataObject(e.getCode(), e.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(), e.getCause());
            repJson = new DataObject(ErrorCode.ERROR_A_NEGATIVE.getCode(), ErrorCode.ERROR_A_NEGATIVE.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        }

    }

    /**
     * 根据ID获取一条记录,并且返回编辑界面UI
     */
    @RequestMapping(UrlContents.URL_ADM_CELL_EDIT_FORM_UI)
    public String editFormUI(){
        //向浏览器的输出
        DataObject repJson;
        try {
            //获取参数
            String id = getParam("id");
            CellDTO cellDTO=new CellDTO();
            String buildId="";
            String buildName="";
            String communityName="";
            String communityId="";
            if(StringUtil.notEmpty(id)){
                //查询房间
                cellDTO = cellService.queryCellByCellId(id);
                buildId = cellDTO.getBuildId();
                //查询楼栋
                BuildDTO buildDTO = buildService.queryBuildById(buildId);
                buildName = buildDTO.getName();
                communityId = buildDTO.getCommunityId();
                communityName = buildDTO.getCommunityName();
                //查询住户
                UserCellDTO userCellDTO = new UserCellDTO();
                userCellDTO.setCellId(id);
                UserCellDTO[] userCellList = userCellService.queryUserCell(userCellDTO);
                List<Map<String,Object>> cellList =new ArrayList<>();
                if (null != userCellList) {
                    for(UserCellDTO m :userCellList){
                        if (null == m) { continue; }
                        Map<String,Object> data = new HashMap<>();
                        data.put("cellId", id);
                        data.put("userName", m.getUserName());
                        data.put("userId", m.getUserId());
                        data.put("communityName", m.getCommunityName());
                        data.put("buildName", m.getBuildName());
                        data.put("cellName", m.getCellName());
                        if(StringUtil.notEmpty(m.getUserPhone()) && m.getUserPhone().length()>=11){
                            data.put("userPhone", new StringBuffer(m.getUserPhone())
                                    .replace(3, 7, "****")
                                    .toString()
                            );
                        }else{
                            data.put("userPhone", m.getUserPhone());
                        }
                        data.put("isCheckIdCard", m.getIsCheckIdCard());
                        data.put("isMsgCheck", m.getMsgCheck());
                        data.put("userCellType",UserCellType.getUserCellType(m.getType()));
                        if (null == m.getType()) {
                            data.put("typeName", "未知住户");
                        } else if (UserCellType.MASTER.equals(m.getType())) {
                            data.put("typeName", "户主");
                        }else if(UserCellType.MEMBER.equals(m.getType())){
                            data.put("typeName", "成员");
                        }else if(UserCellType.TENANT.equals(m.getType())){
                            data.put("typeName", "租客");
                        }
                        cellList.add(data);
                    }
                }
                setAttr("cellList", cellList);
            }
            setAttr("cell", cellDTO);
            setAttr("buildId", buildId);
            setAttr("buildName", buildName);
            setAttr("communityId", communityId);
            setAttr("communityName", communityName);
            return "/community/cell/view/cell_edit_form.html";
        } catch (BizException e) {
            logger.warn(e.getMessage(), e);
            repJson = new DataObject(e.getCode(), e.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage(), e.getCause());
            repJson = new DataObject(ErrorCode.ERROR_A_NEGATIVE.getCode(), ErrorCode.ERROR_A_NEGATIVE.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return null;
        }
    }



    /**
     * 修改房间
     */
    @RequestMapping(UrlContents.URL_ADM_CELL_UPD)
    public void upd(@ModelAttribute("cellDTO") CellDTO cellDTO) {
        //输出到浏览器的提示
        DataObject repJson;
        try {
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            cellDTO.setCancall(StringUtil.notEmpty(cellDTO.getCallphone().trim()));
            CellODTO cellODTO = BeanUtil.copyProperties(CellODTO.class, cellDTO);
            cellODTO.setToken(token);
            cellODTO.setCellId(cellDTO.getId());
            cellService.updateCell(cellODTO);
            repJson = new DataObject("更新房间成功");
            ResultJsonUtil.renderJson(response, repJson);
            return;
        } catch (BizException e) {
            logger.warn(e.getMessage(), e);
            repJson = new DataObject(e.getCode(), e.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(), e.getCause());
            repJson = new DataObject(ErrorCode.ERROR_A_NEGATIVE.getCode(), ErrorCode.ERROR_A_NEGATIVE.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        }
    }
        /**
         * 删除房间
         */
    @RequestMapping(UrlContents.URL_ADM_CELL_DEL)
    public void del(){
        //输出到浏览器的提示
        DataObject repJson;
        try {
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            //封装数据
            DeleteCellODTO deleteCellODTO = new DeleteCellODTO();
            String ids = getParam("ids");
            String buildId = getParam("buildId");
            if(StringUtil.isEmpty(buildId)){
                repJson = new DataObject("未获取到楼栋,请重新选择楼栋后再操作");
                ResultJsonUtil.renderJson(response, repJson);
                return;
            }
            String[] idArr = ids.split(",");
            List<String> idList = Arrays.stream(idArr).collect(Collectors.toList());
            deleteCellODTO.setToken(token);
            deleteCellODTO.setBuildId(buildId);
            deleteCellODTO.setCellIds(idList);
            cellService.deleteCellByIds(deleteCellODTO);
            repJson = new DataObject("删除房间成功");
            ResultJsonUtil.renderJson(response, repJson);
            return;
        } catch (BizException e) {
            logger.warn(e.getMessage(), e);
            repJson = new DataObject(e.getCode(), e.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(), e.getCause());
            repJson = new DataObject(ErrorCode.ERROR_A_NEGATIVE.getCode(), ErrorCode.ERROR_A_NEGATIVE.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        }
    }

    /**
     * 添加或修改用户
     */
    @RequestMapping(UrlContents.URL_ADM_USER_ADD_UPD)
    public void addOrModifyUser(@ModelAttribute("userDTO")UserDTO userDTO) {
        DataObject repJson = null;
        try {
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            if (StringUtils.isEmpty(userDTO.getCellId())) {
                repJson =  new DataObject("500", "没有传入房间id");
                ResultJsonUtil.renderJson(response, repJson);
                return;
            }
            if (StringUtils.isEmpty(userDTO.getName())) {
                repJson = new DataObject("500", "没有传入住户姓名");
                ResultJsonUtil.renderJson(response, repJson);
                return;
            }
            if(userDTO.getName()!=null && userDTO.getName().length()>50){
                repJson = new DataObject("500", "姓名长度不能超过50个字符");
                ResultJsonUtil.renderJson(response, repJson);
                return;
            }
            if (StringUtils.isEmpty(userDTO.getLoginphone())) {
                repJson = new DataObject("500", "没有传入住户电话");
                ResultJsonUtil.renderJson(response, repJson);
                return;
            }
            if (null == userDTO.getUserCellType()) {
                repJson = new DataObject("500", "没有确认住户房产关系");
                ResultJsonUtil.renderJson(response, repJson);
                return;
            }
            if (!userDTO.getLoginphone().contains("*") && !userDTO.getLoginphone().matches("(^(0\\d{2,3})?-?[1-9]\\d{6,7}$)|(^(\\d{2})?1[3-9]\\d{9}$)|(^([5|6|8|9])\\d{7}$)")) {
                repJson = new DataObject("500", "电话号码不合法");
                ResultJsonUtil.renderJson(response, repJson);
                return;
            }
            //封装数据
            UserODTO userODTO = new UserODTO();
            userODTO.setToken(token);
            userODTO.setCellId(userDTO.getCellId());
            userODTO.setUserName(userDTO.getName());
            userODTO.setUserLoginphone(userDTO.getLoginphone());
            userODTO.setType(UserCellType.getUserCellType(userDTO.getUserCellType()));
            //新增
            if(StringUtil.isEmpty(userDTO.getId())){
                userCellService.addUserByUserCellInfo(userODTO);
            } else{//修改
                UserDTO existUser = userCellService.queryUserByUserId(userDTO.getId());
                if(userDTO.getLoginphone().contains("*")) {
                    String oldLoginphone = new StringBuffer(existUser.getLoginphone()).replace(3, 7, "****").toString();
                    String newLoginphone = userDTO.getLoginphone();
                    if (!oldLoginphone.equals(newLoginphone)) {
                        repJson = new DataObject("500", "电话号码不合法");
                        ResultJsonUtil.renderJson(response, repJson);
                        return;
                    } else {
                        userODTO.setUserLoginphone(existUser.getLoginphone());
                    }
                }
                userODTO.setUserId(userDTO.getId());
                userCellService.updateUserByUserCellInfo(userODTO);
            }
            repJson = new DataObject(0,"更新住户成功");
            ResultJsonUtil.renderJson(response, repJson);
        } catch (BizException e) {
            logger.warn(e.getMessage(), e);
            repJson = new DataObject(e.getCode(), e.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(), e.getCause());
            repJson = new DataObject(ErrorCode.ERROR_A_NEGATIVE.getCode(), ErrorCode.ERROR_A_NEGATIVE.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        }
    }
    /**
     * 根据用户的房产详情删除房产
     */
    @RequestMapping(UrlContents.URL_ADM_USER_CELL_DEL)
    public void delUserCellHouseProperty() {
        DataObject repJson;
        try {
            String token = TokenServiceSupport.getWebTokenIdFromCookie(this.request);
            String houseProperty = getParam("houseProperty");
            JSONArray jsonArray = JSONArray.parseArray(houseProperty);
            if (null == jsonArray || jsonArray.isEmpty()) {
                repJson = new DataObject("500", "没有传入房产信息");
                ResultJsonUtil.renderJson(response, repJson);
                return;
            }
            for (int i = 0; i < jsonArray.size(); i ++) {
                JSONObject userCellJson = jsonArray.getJSONObject(i);
                String userId = userCellJson.getString("userId");
                String cellId = userCellJson.getString("cellId");
                if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(cellId)) {
                    repJson = new DataObject("500", "传入信息不全");
                    ResultJsonUtil.renderJson(response, repJson);
                    return;
                }
                DeleteUserODTO deleteUserODTO = new DeleteUserODTO();
                deleteUserODTO.setUserId(userId);
                deleteUserODTO.setCellId(cellId);
                deleteUserODTO.setToken(token);
                userCellService.deleteUserCellByUserIdCellId(deleteUserODTO);
            }
            repJson = new DataObject("0", "删除住户房产成功");
            ResultJsonUtil.renderJson(response, repJson);
        } catch (BizException e) {
            logger.warn(e.getMessage(), e);
            repJson = new DataObject(e.getCode(), e.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(), e.getCause());
            repJson = new DataObject(ErrorCode.ERROR_A_NEGATIVE.getCode(), ErrorCode.ERROR_A_NEGATIVE.getMessage());
            ResultJsonUtil.renderJson(response, repJson);
            return;
        }

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