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

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

    @Autowired
    private ElectricMeterInfoService electricMeterInfoService;

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

        ElectricMeterInfo electricMeterInfo = new ElectricMeterInfo();

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

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

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

            int haveCount = electricMeterInfoService.getCountByMNoAndUNo(electricMeterInfo.getMeterNo(),electricMeterInfo.getUnitNo(),electricMeterInfo.getId());
            if(haveCount > 0){
                throw new Exception("表号加单位不能重复!");
            }
            
            int affectCount = electricMeterInfoService.insert(electricMeterInfo);

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

        try {
            ElectricMeterInfo electricMeterInfo = electricMeterInfoService.get(id);

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

        try {
            electricMeterInfo.setUpdateBy(subject);
            electricMeterInfo.setUpdateTime(new Date());

            int haveCount = electricMeterInfoService.getCountByMNoAndUNo(electricMeterInfo.getMeterNo(),electricMeterInfo.getUnitNo(),electricMeterInfo.getId());
            if(haveCount > 0){
                throw new Exception("表号加单位不能重复!");
            }

            int affectCount = electricMeterInfoService.update(electricMeterInfo);

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

            int affectCount = electricMeterInfoService.update(electricMeterInfo);

            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) {
                ElectricMeterInfo electricMeterInfo = electricMeterInfoService.get(id);
                electricMeterInfo.setDelFlag(true);
                electricMeterInfo.setUpdateBy(subject);
                electricMeterInfo.setUpdateTime(new Date());

                affectCount += electricMeterInfoService.update(electricMeterInfo);
            }

            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(name="meterNo",defaultValue = "") String meterNo,
            @RequestParam(name="terminalId",defaultValue = "") String terminalId,
            @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("a.create_time","desc"));

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

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

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

        Page<ElectricMeterInfo> page = electricMeterInfoService.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 = "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.create_time", "desc"));

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

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

        Page<ElectricMeterInfo> page = electricMeterInfoService.pageSearch(searchParams,0, limit,sortList);
        List<ElectricMeterInfo> meterInfoList = page.getResult();
        msgResult.setResult(true);
        msgResult.setData(meterInfoList);

        return msgResult;
    }

}
