package com.jpsoft.shinestar.modules.base.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.RoomInfo;
import com.jpsoft.shinestar.modules.base.service.ElectricClientInfoService;
import com.jpsoft.shinestar.modules.base.service.RoomInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/base/roomInfo")
public class RoomInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RoomInfoService roomInfoService;
    @Autowired
    private ElectricClientInfoService electricClientInfoService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<RoomInfo> create(String parentId){
        MessageResult<RoomInfo> msgResult = new MessageResult<>();

        RoomInfo roomInfo = new RoomInfo();

        if(StringUtils.isNotEmpty(parentId)){
            RoomInfo parent = roomInfoService.get(parentId);

            roomInfo.setParentId(parent.getId());
            roomInfo.setParentName(parent.getName());

            if (parent.getType().equals("1")){
                roomInfo.setType("2");
            }
            else if (parent.getType().equals("2")){
                roomInfo.setType("3");
            }
        }
        else{
            roomInfo.setType("1");
        }

        msgResult.setData(roomInfo);
        msgResult.setResult(true);

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<RoomInfo> add(@RequestBody RoomInfo roomInfo,@RequestAttribute String subject){
        MessageResult<RoomInfo> msgResult = new MessageResult<>();

        try {
            roomInfo.setId(UUID.randomUUID().toString());
            roomInfo.setDelFlag(false);
            roomInfo.setCreateBy(subject);
            roomInfo.setCreateTime(new Date());

            int affectCount = roomInfoService.insert(roomInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(roomInfoService.get(roomInfo.getId()));
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<RoomInfo> edit(@PathVariable("id") String id){
        MessageResult<RoomInfo> msgResult = new MessageResult<>();

        try {
            RoomInfo roomInfo = roomInfoService.get(id);

            if (roomInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(roomInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<RoomInfo> update(@RequestBody RoomInfo roomInfo,@RequestAttribute String subject){
        MessageResult<RoomInfo> msgResult = new MessageResult<>();

        try {
            roomInfo.setUpdateBy(subject);
            roomInfo.setUpdateTime(new Date());
            
            int affectCount = roomInfoService.update(roomInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(roomInfoService.get(roomInfo.getId()));
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            RoomInfo roomInfo = roomInfoService.get(id);
            roomInfo.setDelFlag(true);
            roomInfo.setUpdateBy(subject);
            roomInfo.setUpdateTime(new Date());

            int affectCount = roomInfoService.deleteAll(roomInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                RoomInfo roomInfo = roomInfoService.get(id);
                roomInfo.setDelFlag(true);
                roomInfo.setUpdateBy(subject);
                roomInfo.setUpdateTime(new Date());

                affectCount += roomInfoService.update(roomInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String id,
            String infoName,
            String parentId,
            String type,
            @RequestParam(name="pageIndex",defaultValue = "1") int pageIndex,
            @RequestParam(name="pageSize",defaultValue = "10") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("sort_no","asc"));

        if (StringUtils.isNotEmpty(id)) {
            searchParams.put("id","%" + id + "%");
        }

        if (StringUtils.isNotEmpty(infoName)) {
            searchParams.put("name", "%" + infoName + "%");
        }

        if (StringUtils.isNotEmpty(parentId)) {
            searchParams.put("parentId", parentId);
        }

        if (StringUtils.isNotEmpty(type)) {
            searchParams.put("type", type);
        }

        Page<RoomInfo> page = roomInfoService.pageSearch(searchParams,pageIndex,pageSize,sortList);
        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value = "查询")
    @RequestMapping(value = "query", method = RequestMethod.POST)
    public MessageResult<List> query(
            String keywords,
            @RequestParam(value = "excludeId", defaultValue = "") String excludeId,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "parentId", defaultValue = "") String parentId,
            @RequestParam(value = "parentType", defaultValue = "") String parentType,
            @RequestParam(value = "length", defaultValue = "20") int limit,
            @RequestAttribute String subject) {
        MessageResult<List> msgResult = new MessageResult<>();

        Map<String, Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.sort_no", "asc"));

        if (StringUtils.isNotEmpty(keywords)) {
            searchParams.put("name", "%" + keywords + "%");
        }

        if (StringUtils.isNotEmpty(excludeId)) {
            searchParams.put("excludeId", excludeId);
        }

        if (StringUtils.isNotEmpty(parentId)) {
            searchParams.put("parentId", parentId);
        }
        if (StringUtils.isNotEmpty(parentType)) {
            if("1".equals(parentType)){
                //选择为园区 则不查
                type = "";
            }else if("2".equals(parentType)){
                //选择为楼栋
                //则查询园区信息
                type = "1";
            } else if("3".equals(parentType)){
                //选择为房间
                //则查询楼栋信息
                type = "2";
            }
            searchParams.put("type", type);
        }

        if (StringUtils.isNotEmpty(type)) {
            searchParams.put("type", type);
        }

        Page<RoomInfo> page = roomInfoService.pageSearch(searchParams,0, limit,sortList);
        List<RoomInfo> roomInfoList = page.getResult();

        msgResult.setResult(true);
        msgResult.setData(roomInfoList);

        return msgResult;
    }


    @ApiOperation(value = "查询")
    @RequestMapping(value = "queryTree", method = RequestMethod.POST)
    public MessageResult<List> queryTree(
            String keywords,
            @RequestParam(value = "excludeId", defaultValue = "") String excludeId,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "parentId", defaultValue = "") String parentId,
            @RequestParam(value = "parentType", defaultValue = "") String parentType,
            @RequestParam(value = "length", defaultValue = "20") int limit,
            @RequestAttribute String subject) {
        MessageResult<List> msgResult = new MessageResult<>();

        Map<String, Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.sort_no", "asc"));

        if (StringUtils.isNotEmpty(parentId)) {
            searchParams.put("parentId", parentId);
        }else{
            searchParams.put("type", 1);
        }

        Page<RoomInfo> page = roomInfoService.pageSearch(searchParams,0, limit,sortList);
        List<RoomInfo> roomInfoList = page.getResult();

        msgResult.setResult(true);
        msgResult.setData(roomInfoList);

        return msgResult;
    }
}
