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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.TerminalInfo;
import com.jpsoft.shinestar.modules.base.service.TerminalInfoService;
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/terminalInfo")
public class TerminalInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TerminalInfoService terminalInfoService;

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

        TerminalInfo terminalInfo = new TerminalInfo();

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

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

        try {
            terminalInfo.setId(UUID.randomUUID().toString());
            terminalInfo.setDelFlag(false);
            terminalInfo.setCreateBy(subject);
            terminalInfo.setCreateTime(new Date());
            int haveCount = terminalInfoService.getCountByName(terminalInfo.getName(),terminalInfo.getId());
            if(haveCount > 0){
                throw new Exception("该终端名称已存在!");
            }
            int affectCount = terminalInfoService.insert(terminalInfo);

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

        try {
            TerminalInfo terminalInfo = terminalInfoService.get(id);

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

        try {
            terminalInfo.setUpdateBy(subject);
            terminalInfo.setUpdateTime(new Date());
            int haveCount = terminalInfoService.getCountByName(terminalInfo.getName(),terminalInfo.getId());
            if(haveCount > 0){
                throw new Exception("该终端名称已存在!");
            }
            int affectCount = terminalInfoService.update(terminalInfo);

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

            int affectCount = terminalInfoService.update(terminalInfo);

            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) {
                TerminalInfo terminalInfo = terminalInfoService.get(id);
                terminalInfo.setDelFlag(true);
                terminalInfo.setUpdateBy(subject);
                terminalInfo.setUpdateTime(new Date());

                affectCount += terminalInfoService.update(terminalInfo);
            }

            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 name,
            @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(name)) {
            searchParams.put("name","%" + name + "%");
        }

        Page<TerminalInfo> page = terminalInfoService.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 = "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("sort_no", "asc"));

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

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

        Page<TerminalInfo> page = terminalInfoService.pageSearch(searchParams,0, limit,sortList);
        List<TerminalInfo> terminalInfoList = page.getResult();
        msgResult.setResult(true);
        msgResult.setData(terminalInfoList);

        return msgResult;
    }
}
