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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.base.entity.ParkingChannel;
import com.jpsoft.shinestar.modules.base.service.ParkingChannelService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import io.swagger.annotations.Api;
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 javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 车道管理
 * sz
 */
@RestController
@RequestMapping("/base/parkingChannel")
@Api(description = "parkingChannel")
public class ParkingChannelController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ParkingChannelService parkingChannelService;

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

        ParkingChannel parkingChannel = new ParkingChannel();

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

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

        try {
            parkingChannel.setId(UUID.randomUUID().toString());
            parkingChannel.setDelFlag(false);
            parkingChannel.setCreateBy(subject);
            parkingChannel.setCreateTime(new Date());
            
            int affectCount = parkingChannelService.insert(parkingChannel);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(parkingChannel);
            } 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<ParkingChannel> edit(@PathVariable("id") String id){
        MessageResult<ParkingChannel> msgResult = new MessageResult<>();

        try {
            ParkingChannel parkingChannel = parkingChannelService.get(id);

            if (parkingChannel != null) {
                msgResult.setResult(true);
                msgResult.setData(parkingChannel);
            } 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<ParkingChannel> update(@RequestBody ParkingChannel parkingChannel,@RequestAttribute String subject){
        MessageResult<ParkingChannel> msgResult = new MessageResult<>();

        try {
            parkingChannel.setUpdateBy(subject);
            parkingChannel.setUpdateTime(new Date());
            
            int affectCount = parkingChannelService.update(parkingChannel);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(parkingChannel);
            } 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 {
            ParkingChannel parkingChannel = parkingChannelService.get(id);
            parkingChannel.setDelFlag(true);
            parkingChannel.setUpdateBy(subject);
            parkingChannel.setUpdateTime(new Date());

            int affectCount = parkingChannelService.update(parkingChannel);

            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) {
                ParkingChannel parkingChannel = parkingChannelService.get(id);
                parkingChannel.setDelFlag(true);
                parkingChannel.setUpdateBy(subject);
                parkingChannel.setUpdateTime(new Date());

                affectCount += parkingChannelService.update(parkingChannel);
            }

            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,
            @RequestParam(value="parkId",defaultValue="1") String parkId,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") 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("create_time","asc"));

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

        searchParams.put("parkId",parkId);

        Page<ParkingChannel> page = parkingChannelService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="重新同步车道信息")
    @RequestMapping(value = "sync",method = RequestMethod.POST)
    public MessageResult<Map> sync(
            @RequestParam(value="parkId",defaultValue="1") String parkId,
            @RequestAttribute String subject){

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

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

        Map<String,Object> searchParams = new HashMap<>();
        try {
            //查询本地数据库车道信息
            //List<ParkingChannel> pcList = parkingChannelService.findByParkId(Long.valueOf(parkId));

            //查设备上车道信息
            List<ParkingChannel> pcApiList = parkingChannelService.findApiByParkId(Long.valueOf(parkId));

            //先删除本地不存在的车道信息
            parkingChannelService.deleteNotExist(pcApiList);

            for(ParkingChannel pc : pcApiList){
                ParkingChannel newPc = parkingChannelService.findByChannelId(pc.getChannelId());
                if(newPc == null){
                    //新增
                    pc.setId(UUID.randomUUID().toString());
                    pc.setDelFlag(false);
                    pc.setCreateBy(subject);
                    pc.setCreateTime(new Date());
                    parkingChannelService.insert(pc);

                }else{
                    //修改
                    pc.setUpdateBy(subject);
                    pc.setUpdateTime(new Date());
                    parkingChannelService.update(pc);
                }
            }
            msgResult.setResult(true);
        }catch (Exception e){
            e.printStackTrace();
            msgResult.setResult(false);
            msgResult.setMessage("同步错误");
        }

        return msgResult;
    }
}
