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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.DeviceInfo;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.base.entity.WatchMeasure;
import com.jpsoft.shinestar.modules.base.service.WatchMeasureService;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
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.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/base/watchMeasure")
@Api(description = "老人手表消息接口")
public class WatchMeasureController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WatchMeasureService watchMeasureService;
    @Autowired
    private DataDictionaryService dataDictionaryService;

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

        WatchMeasure watchMeasure = new WatchMeasure();

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

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

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

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

        try {
            WatchMeasure watchMeasure = watchMeasureService.get(id);

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

        try {
            watchMeasure.setUpdateBy(subject);
            watchMeasure.setUpdateTime(new Date());
            
            int affectCount = watchMeasureService.update(watchMeasure);

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

            int affectCount = watchMeasureService.update(watchMeasure);

            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) {
                WatchMeasure watchMeasure = watchMeasureService.get(id);
                watchMeasure.setDelFlag(true);
                watchMeasure.setUpdateBy(subject);
                watchMeasure.setUpdateTime(new Date());

                affectCount += watchMeasureService.update(watchMeasure);
            }

            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 deviceNo, String name,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date endTime,
            @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("record_time","desc"));

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

        if(startTime != null){
            searchParams.put("startTime", startTime);
        }

        if(endTime != null){
            searchParams.put("endTime", endTime);
        }

        Page<WatchMeasure> page = watchMeasureService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        Map<String, DataDictionary> nameListMap = dataDictionaryService.findMapByCatalogName("老人手表测量项目");
        for (WatchMeasure watchMeasure:page) {
            if (nameListMap.containsKey(watchMeasure.getName())) {
                watchMeasure.setNameN(nameListMap.get(watchMeasure.getName()).getName());
            }
            else{
                watchMeasure.setNameN("["+watchMeasure.getName()+"]");
            }
        }

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

        return msgResult;
    }
}
