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


import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.CompanyPositionService;
import com.jpsoft.shinestar.modules.base.service.DeviceInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonDeviceLogService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.utils.TimeZonesUtil;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserCompanyService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/personDeviceLog")
@Api(description = "日志台账")
public class PersonDeviceLogController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CompanyPositionService companyPositionService;

    @Autowired
    private ValueOperations<String,Object> valueOperations;

    @Autowired
    private UserCompanyService userCompanyService;

    private final String exportPrefix = "exportDeviceLog_";

    @ApiOperation(value = "列表")
    @RequestMapping(value = "pageList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "所属单位编号", paramType = "query"),
            @ApiImplicitParam(name = "subordinate", value = "是否查询下级单位", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "deviceNo", value = "设备编号", paramType = "query"),
            @ApiImplicitParam(name = "aliasName", value = "设备别名", paramType = "query"),
            @ApiImplicitParam(name = "personId", value = "人员编号", paramType = "query"),
            @ApiImplicitParam(name = "personName", value = "人员姓名", paramType = "query"),
            @ApiImplicitParam(name = "jobNumbers", value = "工号", paramType = "query"),
            @ApiImplicitParam(name = "timeRanges", value = "时间范围", paramType = "query"),
            @ApiImplicitParam(name = "temperatureRanges", value = "温度范围", paramType = "query"),
            @ApiImplicitParam(name = "matchMsg", value = "匹配状态", paramType = "query"),
            @ApiImplicitParam(name = "distinct", value = "是否去重", paramType = "query")
    })
    public MessageResult<Map> pageList(
            String companyId,
            @RequestParam(value = "subordinate", defaultValue = "false") Boolean subordinate,
            String deviceNo, String aliasName, String personId,String personName,String jobNumbers,
            String timeRanges, String temperatureRanges, String matchMsg,
            @RequestParam(value = "distinct", defaultValue = "false") Boolean distinct,
            @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<>();

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.record_time", "desc"));

        //为公司管理员
        boolean isSysAdmin = userService.hasRole(subject, "SYSADMIN");

        if (!isSysAdmin) {
            User user = userService.get(subject);
            String userCompanyId = user.getCompanyId();

            //去掉了删除判断
            //需要查出已删除的设备
            List<DeviceInfo> deviceInfoList = deviceInfoService.findByCompanyId(userCompanyId);

            List<String> deviceNoList = new ArrayList<>();

            for (DeviceInfo deviceInfo : deviceInfoList) {
                deviceNoList.add(deviceInfo.getDeviceNo());
            }

            //查询关联单位表
            List<CompanyInfo> relateCompanyList = userCompanyService.findByUserId(user.getId());

            for (CompanyInfo companyInfo : relateCompanyList) {
                List<DeviceInfo> relateDevices = deviceInfoService.findByCompanyId(companyInfo.getId());

                for (DeviceInfo deviceInfo : relateDevices) {
                    if (!deviceNoList.contains(deviceInfo.getDeviceNo())){
                        deviceNoList.add(deviceInfo.getDeviceNo());
                    }
                }
            }

            if (deviceNoList.size() == 0) {
                deviceNoList.add("-1");
            }

            searchParams.put("deviceNoList", deviceNoList);
            searchParams.put("relateCompanyList", relateCompanyList);

            CompanyInfo companyInfo = companyInfoService.get(userCompanyId);
            searchParams.put("companyCode", companyInfo.getCode() + "%");
        }

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

            //指定单位则把关联单位查询条件去掉
            searchParams.put("relateCompanyList", null);

            CompanyInfo companyInfo = companyInfoService.get(companyId);

            if (subordinate) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            } else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
        }

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

        if (StringUtil.isNotEmpty(aliasName)) {
            searchParams.put("aliasName", "%" + aliasName + "%");
        }

        if (StringUtil.isNotEmpty(personId)) {
            searchParams.put("personId", personId);
        }

        if (StringUtil.isNotEmpty(personName)) {
            searchParams.put("personName", "%" + personName + "%");
        }

        if (StringUtil.isNotEmpty(jobNumbers)) {
            String[] jobNumbersArray = jobNumbers.split(",");
            searchParams.put("jobNumbers", Arrays.asList(jobNumbersArray));
        }

        if (StringUtil.isNotEmpty(matchMsg)) {
            searchParams.put("matchMsg", matchMsg);
        }

        if (StringUtil.isNotEmpty(timeRanges)) {
            String[] timeRangeArray = timeRanges.split(",");
            String beginTime = "";
            String endTime = "";
            if (timeRangeArray.length == 1) {
                beginTime = timeRangeArray[0];
            } else if (timeRangeArray.length == 2) {
                beginTime = timeRangeArray[0];
                endTime = timeRangeArray[1];
            }

            searchParams.put("beginTime", beginTime);
            searchParams.put("endTime", endTime);
        }

        if (StringUtil.isNotEmpty(temperatureRanges)) {
            String[] temperatureRangeArray = temperatureRanges.split(",");

            String minTemperature = "";
            String maxTemperature = "";

            if (temperatureRangeArray.length == 1) {
                minTemperature = temperatureRangeArray[0];
            }
            if (temperatureRangeArray.length == 2) {
                minTemperature = temperatureRangeArray[0];
                maxTemperature = temperatureRangeArray[1];
            }

            if (StringUtil.isNotEmpty(minTemperature)) {
                searchParams.put("minTemperature", minTemperature);
            }
            if (StringUtil.isNotEmpty(maxTemperature)) {
                searchParams.put("maxTemperature", maxTemperature);
            }
        }

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

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

        return msgResult;
    }

    @GetMapping("exportProgress")
    public MessageResult<String> exportProgress(String timestamp){
        MessageResult<String> msgResult = new MessageResult<>();

        String exportProgress = (String)valueOperations.get(exportPrefix + timestamp);

        if(StringUtils.isNotEmpty(exportProgress)){
            msgResult.setMessage(exportProgress);
            msgResult.setResult(true);
        }

        return msgResult;
    }

    public void   setExportProgress(String timestamp,String msg){
        valueOperations.set(exportPrefix + timestamp , msg,5, TimeUnit.MINUTES);
    }

    @ApiOperation(value = "导出日志台账")
    @PostMapping("exportXls")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "timestamp", value = "时间戳", paramType = "query"),
            @ApiImplicitParam(name = "companyId", value = "所属单位编号", paramType = "query"),
            @ApiImplicitParam(name = "subordinate", value = "是否查询下级单位", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "deviceNo", value = "设备编号", paramType = "query"),
            @ApiImplicitParam(name = "aliasName", value = "设备别名", paramType = "query"),
            @ApiImplicitParam(name = "personName", value = "人员姓名", paramType = "query"),
            @ApiImplicitParam(name = "jobNumbers", value = "工号", paramType = "query"),
            @ApiImplicitParam(name = "timeRanges", value = "时间范围", paramType = "query"),
            @ApiImplicitParam(name = "temperatureRanges", value = "温度范围", paramType = "query"),
            @ApiImplicitParam(name = "matchMsg", value = "匹配状态", paramType = "query"),
            @ApiImplicitParam(name = "distinct", value = "是否去重", paramType = "query")
    })
    public MessageResult<String> exportXls(
            String timestamp,
            String companyId,
            @RequestParam(value = "subordinate", defaultValue = "false") Boolean subordinate,
            String deviceNo, String aliasName, String personName,String personId,
            String jobNumbers,
            String timeRanges, String temperatureRanges, String matchMsg,
            @RequestParam(value = "distinct", defaultValue = "false") Boolean distinct,
            @RequestAttribute String subject,
            @RequestParam(defaultValue = "1000") int pageSize
        ) {
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            long start = System.currentTimeMillis();

            User user = userService.get(subject);
            String userCompanyId = user.getCompanyId();

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet();

            //表头
            Row rowTitle = sheet.createRow(0);
            Cell cellTitle1 = rowTitle.createCell(0);
            cellTitle1.setCellValue("序号");
            Cell cellTitle2 = rowTitle.createCell(1);
            cellTitle2.setCellValue("检测时间");
            Cell cellTitle3 = rowTitle.createCell(2);
            cellTitle3.setCellValue("人员姓名");
            Cell cellTitle4 = rowTitle.createCell(3);
            cellTitle4.setCellValue("工号");
            Cell cellTitle5 = rowTitle.createCell(4);
            cellTitle5.setCellValue("测温度数");
            Cell cellTitle6 = rowTitle.createCell(5);
            cellTitle6.setCellValue("设备编号");
            Cell cellTitle7 = rowTitle.createCell(6);
            cellTitle7.setCellValue("设备别称");
            Cell cellTitle8 = rowTitle.createCell(7);
            cellTitle8.setCellValue("拍照图片");
            Cell cellTitle9 = rowTitle.createCell(8);
            cellTitle9.setCellValue("备注");

            //获取公司
            //五级位置
            //CompanyInfo companyInfo = companyInfoService.get(companyId);
//            List<CompanyPosition> companyPositionList = companyPositionService.findByCompanyId(userCompanyId);
//            CompanyPosition companyPosition = null;
//            if (companyPositionList.size() > 0) {
//                companyPosition = companyPositionList.get(0);
//                Cell cellTitle8 = rowTitle.createCell(7);
//                cellTitle8.setCellValue(companyPosition.getPosition1Name());
//                Cell cellTitle9 = rowTitle.createCell(8);
//                cellTitle9.setCellValue(companyPosition.getPosition2Name());
//                Cell cellTitle10 = rowTitle.createCell(9);
//                cellTitle10.setCellValue(companyPosition.getPosition3Name());
//                Cell cellTitle11 = rowTitle.createCell(10);
//                cellTitle11.setCellValue(companyPosition.getPosition4Name());
//                Cell cellTitle12 = rowTitle.createCell(11);
//                cellTitle12.setCellValue(companyPosition.getPosition5Name());
//            }

            //表内容
            Map<String, Object> searchParams = new HashMap<>();

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

            //为公司管理员
            boolean isSysAdmin = userService.hasRole(subject, "SYSADMIN");
            if (!isSysAdmin) {
                //去掉了删除判断
                //需要查出已删除的设备
                List<DeviceInfo> deviceInfoList = deviceInfoService.findByCompanyId(userCompanyId);
                List<String> deviceNoList = new ArrayList<String>();

                for (DeviceInfo deviceInfo : deviceInfoList) {
                    deviceNoList.add(deviceInfo.getDeviceNo());
                }

                if (deviceNoList.size() == 0) {
                    deviceNoList.add("-1");
                }

                searchParams.put("deviceNoList", deviceNoList);
            }

            if (StringUtil.isNotEmpty(deviceNo)) {
                searchParams.put("deviceNo", "%" + deviceNo + "%");
            }
            if (StringUtil.isNotEmpty(aliasName)) {
                searchParams.put("aliasName", "%" + aliasName + "%");
            }
            if (StringUtil.isNotEmpty(personName)) {
                searchParams.put("personName", "%" + personName + "%");
            }
            if (StringUtil.isNotEmpty(personId)) {
                searchParams.put("personId", personId);
            }

            if (StringUtil.isNotEmpty(jobNumbers)) {
                String[] jobNumbersArray = jobNumbers.split(",");
                searchParams.put("jobNumbers", Arrays.asList(jobNumbersArray));
            }


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

                CompanyInfo companyInfo = companyInfoService.get(companyId);

                if (subordinate) {
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                } else {
                    searchParams.put("companyCode", companyInfo.getCode());
                }
            }

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

            if (StringUtil.isNotEmpty(matchMsg)) {
                searchParams.put("matchMsg", matchMsg);
            }

            if (StringUtil.isNotEmpty(timeRanges)) {
                String[] timeRangeArray = timeRanges.split(",");
                String beginTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                }

                searchParams.put("beginTime", beginTime);
                searchParams.put("endTime", endTime);
            }

            if (StringUtil.isNotEmpty(temperatureRanges)) {
                String[] temperatureRangeArray = temperatureRanges.split(",");

                String minTemperature = "";
                String maxTemperature = "";
                if (temperatureRangeArray.length == 1) {
                    minTemperature = temperatureRangeArray[0];
                } else if (temperatureRangeArray.length == 2) {
                    minTemperature = temperatureRangeArray[0];
                    maxTemperature = temperatureRangeArray[1];
                }

                searchParams.put("minTemperature", minTemperature);
                searchParams.put("maxTemperature", maxTemperature);
            }

            int pageNum = 1;
            boolean needCount = true;
            int totalPages = 1;
            long total = 0;
            long exportNum = 0;

            if(pageSize>10000){
                pageSize = 10000;
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            //起始时间和截止时间不能超过1一个月
            if(searchParams.get("beginTime")==null || searchParams.get("endTime")==null){
                throw new Exception("导出时间段不能为空!");
            }
            else{
                DateTime beginTime = new DateTime(sdf.parse(searchParams.get("beginTime").toString()));
                DateTime endTime = new DateTime(sdf.parse(searchParams.get("endTime").toString()));

                int days = Days.daysBetween(beginTime,endTime).getDays();

                if(days>31){
                    throw new Exception("导出时间段不能超过1个月!");
                }
            }

            boolean loop = true;

            while(pageNum<=totalPages && loop){
                Page<PersonDeviceLog> page = personDeviceLogService.pageSearch(searchParams, pageNum, pageSize, needCount, sortList);

                if(needCount){
                    totalPages = page.getPages();
                    total = page.getTotal();
                    setExportProgress(timestamp , "导出进度：0/" +  page.getTotal() + "...");
                }

                for (int i = 0; i < page.size(); i++) {
                    int rowNum = (pageNum-1)*pageSize + i + 1;

                    if(rowNum>100000){
                        loop = false;
                        break;
                    }

                    PersonDeviceLog personDeviceLog = page.get(i);

                    Row rowContent = sheet.createRow( rowNum);

                    Cell cellContent1 = rowContent.createCell(0);
                    cellContent1.setCellValue(i + 1);

                    String recordTime = "";
                    if (personDeviceLog.getRecordTime() != null) {
                        recordTime = sdf.format(personDeviceLog.getRecordTime());
                    }

                    Cell cellContent2 = rowContent.createCell(1);
                    cellContent2.setCellValue(recordTime);

                    String name = "";
                    String jobNumber = "";
                    if (personDeviceLog.getPerson() != null) {
                        name = personDeviceLog.getPerson().getName();
                        if(personDeviceLog.getPerson().getJobNumber() != null) {
                            jobNumber = personDeviceLog.getPerson().getJobNumber();
                        }
                    } else {
                        name = "匿名用户";
                    }
                    Cell cellContent3 = rowContent.createCell(2);
                    cellContent3.setCellValue(name);
                    Cell cellContent4 = rowContent.createCell(3);
                    cellContent4.setCellValue(jobNumber);
                    Cell cellContent5 = rowContent.createCell(4);
                    cellContent5.setCellValue(personDeviceLog.getTemperature().toString());
                    Cell cellContent6 = rowContent.createCell(5);
                    cellContent6.setCellValue(personDeviceLog.getDeviceNo());
                    Cell cellContent7 = rowContent.createCell(6);
                    if(personDeviceLog.getDevice() != null) {
                        cellContent7.setCellValue(personDeviceLog.getDevice().getAliasName());
                    }
                    Cell cellContent8 = rowContent.createCell(7);
                    cellContent8.setCellValue(personDeviceLog.getFaceImage());
                    Cell cellContent9 = rowContent.createCell(8);
                    cellContent9.setCellValue(personDeviceLog.getRemark());
//                    //五级位置
//                    //判断 如果公司没有五级位置 就不做展示
//                    if (companyPositionList.size() > 0) {
//                        PersonInfo person = personDeviceLog.getPerson();
//                        if (person != null) {
//                            Cell cellContent8 = rowContent.createCell(7);
//                            if (person.getPosition1() != null) {
//                                cellContent8.setCellValue(person.getPosition1());
//                            }
//                            Cell cellContent9 = rowContent.createCell(8);
//                            if (person.getPosition1() != null) {
//                                cellContent9.setCellValue(person.getPosition2());
//                            }
//                            Cell cellContent10 = rowContent.createCell(9);
//                            if (person.getPosition1() != null) {
//                                cellContent10.setCellValue(person.getPosition3());
//                            }
//                            Cell cellContent11 = rowContent.createCell(10);
//                            if (person.getPosition1() != null) {
//                                cellContent11.setCellValue(person.getPosition4());
//                            }
//                            Cell cellContent12 = rowContent.createCell(11);
//                            if (person.getPosition1() != null) {
//                                cellContent12.setCellValue(person.getPosition5());
//                            }
//                        }
//                    }

                    sheet.autoSizeColumn(i);
                }

                pageNum++;
                needCount = false; //第二页就不用查总数
                exportNum += page.size();

                setExportProgress(timestamp ,String.format("导出进度：%s/%s...", exportNum, total));
            }

            //todo 将wb保存到oss
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            workbook.write(output);
            byte[] buffer = output.toByteArray();
            output.close();

            logger.warn("原文件大小：" + buffer.length);

            String fileName = DateTime.now().toString("yyyyMMddHHmmss") + ".xlsx";

            InputStream input = new ByteArrayInputStream(buffer);

            //todo 如果超过2M则压缩
            if(buffer.length>2*1024*1024){
                setExportProgress(timestamp ,"导出数据完毕，正在压缩...");

                ByteArrayOutputStream zipOut = new ByteArrayOutputStream();

                ZipOutputStream zos = new ZipOutputStream(zipOut);
                ZipEntry zipEntry = new ZipEntry(fileName);
                zos.putNextEntry(zipEntry);
                zos.write(buffer, 0, buffer.length);
                zos.close();

                byte[] zipBuffer = zipOut.toByteArray();
                logger.warn("压缩后文件大小：" + zipBuffer.length);

                input = new ByteArrayInputStream(zipBuffer);

                //文件被压缩
                fileName = DateTime.now().toString("yyyyMMddHHmmss") + ".zip";
            }

            long end = System.currentTimeMillis();

            setExportProgress(timestamp ,"导出数据完毕，正在保存...");
            String downloadUrl = OSSUtil.upload(ossConfig, "export", fileName, input);

            msgResult.setData(downloadUrl);

            long elapse = end - start;

            msgResult.setMessage(String.format(
                    "导出完毕，请点击下载链接保存！耗时: %s",
                    TimeZonesUtil.friendlyTimeFormat(elapse)));

            msgResult.setResult(true);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value = "导入数据(一次性导入食堂记录用)")
    @RequestMapping(value = "importData", method = RequestMethod.POST)
    public void importData() {
        int count = 0;
        try {
            count = personDeviceLogService.importData();
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

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

        PersonDeviceLog personDeviceLog = new PersonDeviceLog();

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

        return msgResult;
    }

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

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

            int affectCount = personDeviceLogService.insert(personDeviceLog);

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

        try {
            PersonDeviceLog personDeviceLog = personDeviceLogService.get(id);

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

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

            int affectCount = personDeviceLogService.update(personDeviceLog);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(personDeviceLog);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }
}
