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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.ParkingInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.ParkingInfoService;
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 com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
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/parkingInfo")
public class ParkingInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ParkingInfoService parkingInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private CompanyInfoService companyInfoService;

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

        ParkingInfo parkingInfo = new ParkingInfo();

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

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<ParkingInfo> add(@RequestBody ParkingInfo parkingInfo,@RequestAttribute String subject){
        MessageResult<ParkingInfo> msgResult = new MessageResult<>();
        User user = userService.get(subject);

        try {
            parkingInfo.setId(UUID.randomUUID().toString());
            //parkingInfo.setCompanyId(user.getCompanyId());
            parkingInfo.setDelFlag(false);
            parkingInfo.setCreateBy(subject);
            parkingInfo.setCreateTime(new Date());
            
            int affectCount = parkingInfoService.insert(parkingInfo);

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

        try {
            ParkingInfo parkingInfo = parkingInfoService.get(id);

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

        try {
            parkingInfo.setUpdateBy(subject);
            parkingInfo.setUpdateTime(new Date());
            
            int affectCount = parkingInfoService.update(parkingInfo);

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

            int affectCount = parkingInfoService.update(parkingInfo);

            if (affectCount > 0) {
                List<ParkingInfo> piList = parkingInfoService.findByParentId(parkingInfo.getId());
                for(ParkingInfo pi : piList){
                    pi.setDelFlag(true);
                    pi.setUpdateBy(subject);
                    pi.setUpdateTime(new Date());
                    parkingInfoService.update(pi);
                }

                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) {
                ParkingInfo parkingInfo = parkingInfoService.get(id);
                parkingInfo.setDelFlag(true);
                parkingInfo.setUpdateBy(subject);
                parkingInfo.setUpdateTime(new Date());
                affectCount += parkingInfoService.update(parkingInfo);

                List<ParkingInfo> piList = parkingInfoService.findByParentId(parkingInfo.getId());
                for(ParkingInfo pi : piList){
                    pi.setDelFlag(true);
                    pi.setUpdateBy(subject);
                    pi.setUpdateTime(new Date());
                    parkingInfoService.update(pi);
                }
            }

            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 parkingName, String parentId,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);
        User user = userService.get(subject);

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

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

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

        if (StringUtils.isNotEmpty(parkingName)) {
            searchParams.put("parkingName","%" + parkingName + "%");
        }
        if (!parentId.equals("null") && StringUtils.isNotEmpty(parentId)) {
            searchParams.put("parentId",parentId);
        }

        if (!userService.hasRole(subject,"SYSADMIN")) {
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            List<CompanyInfo> list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%",null);
            searchParams.put("companyIds",list);
        }

        Page<ParkingInfo> page = parkingInfoService.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(@RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);
        User user = userService.get(subject);

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

        List<ParkingInfo> list = parkingInfoService.list();

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

        return msgResult;
    }
}
