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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
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.StringUtils;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
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.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.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 javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/base/canteenDiningRecord")
@Api(description = "canteenDiningRecord")
public class CanteenDiningRecordController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private CanteenDiningRecordService canteenDiningRecordService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private CanteenDeviceService canteenDeviceService;

    @Autowired
    private CanteenInfoService canteenInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserCompanyService userCompanyService;


    @Autowired
    private PersonDeviceLogService personDeviceLogService;

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

        CanteenDiningRecord canteenDiningRecord = new CanteenDiningRecord();

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

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

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

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

        try {
            CanteenDiningRecord canteenDiningRecord = canteenDiningRecordService.get(id);

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

        try {
            canteenDiningRecord.setUpdateBy(subject);
            canteenDiningRecord.setUpdateTime(new Date());
            
            int affectCount = canteenDiningRecordService.update(canteenDiningRecord);

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

            int affectCount = canteenDiningRecordService.update(canteenDiningRecord);

            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) {
                CanteenDiningRecord canteenDiningRecord = canteenDiningRecordService.get(id);
                canteenDiningRecord.setDelFlag(true);
                canteenDiningRecord.setUpdateBy(subject);
                canteenDiningRecord.setUpdateTime(new Date());

                affectCount += canteenDiningRecordService.update(canteenDiningRecord);
            }

            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<Object> pageList(
            Long personId,String name,String jobNumber,String companyId,String deviceId,String timeRanges,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

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


        try {

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

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

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

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

            if (StringUtils.isNotEmpty(deviceId)) {
                String[] deviceIdArray = deviceId.split(",");
                List<String> deviceNoList = new ArrayList<>();
                for (String itemId:deviceIdArray) {
                    DeviceInfo deviceInfo = deviceInfoService.get(itemId);
                    if(deviceInfo!=null){
                        //searchParams.put("deviceNo", deviceInfo.getDeviceNo());
                        deviceNoList.add(deviceInfo.getDeviceNo());

                    }
                }

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

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


            User user = userService.get(subject);

            if (userService.hasRole(subject, "SYSADMIN")||userService.hasRole(subject, "食堂")) {

            } else {
                if (StringUtils.isNotEmpty(companyId)) {
                    searchParams.put("companyId", "%"+companyId+"%");
                }
                else {
                    CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
                    searchParams.put("companyId", "%" + companyInfo.getId() + "%");
                }
            }


            if (StringUtils.isNotEmpty(timeRanges)) {
                String[] timeRangeArray = timeRanges.split(",");
                String beginTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                    beginTime+=" 00:00:00";
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime+=" 00:00:00";
                    endTime+=" 23:59:59";
                }

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

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

            List<Map> mapList = new ArrayList<>();

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

            for (CanteenDiningRecord canteenDiningRecord : page) {
                Map<String,Object> map = new HashMap<>();
                String personName="";
                String jobNumberTemp="";
                String companyName="";

                PersonInfo personInfo = personInfoService.get(canteenDiningRecord.getPersonId());
                if (personInfo != null) {
                    personName = personInfo.getName();
                    jobNumberTemp = personInfo.getJobNumber();

                    CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
                    if (companyInfo != null) {
                        companyName = companyInfo.getName();
                    }
                }

                map.put("createTime",sdf.format(canteenDiningRecord.getCreateTime()));

                if(canteenDiningRecord.getRecordTime()!=null) {
                    map.put("recordTime", sdf.format(canteenDiningRecord.getRecordTime()));
                }

                map.put("categoryAmount",canteenDiningRecord.getCategoryAmount());
                map.put("address",canteenDiningRecord.getAddress());
                map.put("personName",personName);
                map.put("jobNumber",jobNumberTemp);
                map.put("companyName",companyName);

                String category = canteenDiningRecord.getCategory();

                String categoryName = dataDictionaryService.findNameByCatalogNameAndValue("餐别", category);

                map.put("categoryName",categoryName);

                String deviceName="";

                if(StringUtils.isNotEmpty(canteenDiningRecord.getDeviceNo())){

                    DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(canteenDiningRecord.getDeviceNo());

                    if(deviceInfo!=null){
                        deviceName = deviceInfo.getAliasName();
                    }
                }
                map.put("deviceName",deviceName);

                mapList.add(map);
            }

            if(exportFlag) {
                String filePath = exportXls(mapList);
                msgResult.setData(filePath);
            }
            else{
                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                msgResult.setData(dataMap);
            }

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

        return msgResult;
    }


    private String exportXls(List<Map> mapList) throws IOException {
        String downloadUrl = "";

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

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","部门","工号","姓名","时间","餐别",
                "就餐金额（元）","地点"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        for (int i=0;i<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("companyName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("jobNumber"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("personName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("createTime"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("categoryName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("categoryAmount"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("address"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"canteenDiningRecord","员工就餐记录统计.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }


    private String canteenExportXls(List<Map> mapList) throws IOException {
        String downloadUrl = "";

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

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","食堂名称","食堂地址","总计总数","中餐就餐总数","晚餐就餐总数",
                "宵夜就餐总数"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        for (int i=0;i<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("canteenName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("address"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("personNum"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("lunch"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("supper"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("nightSnack"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"canteenDiningRecordDetail","食堂就餐统计表.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }


    private String canteenDetailExportXls(List<Map> mapList) throws IOException {
        String downloadUrl = "";

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

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","部门","工号","姓名","时间","餐别","地点"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        for (int i=0;i<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("companyName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("jobNumber"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("personName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("recordTime"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("categoryN"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("address_"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"canteenDetailExport","食堂就餐详情统计表.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }



    @ApiOperation(value="食堂就餐明细表")
    @RequestMapping(value = "canteenDiningRecordDetailList",method = RequestMethod.POST)
    public MessageResult<Object> canteenDiningRecordDetailList(
            String recordTimeRange,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String subject) {

        //当前用户ID
        System.out.println(subject);

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


        try {

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

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


            if (StringUtils.isNotEmpty(recordTimeRange)) {
                String[] timeRangeArray = recordTimeRange.split(",");
                String beginTime = "";
                String endTime = "";
                beginTime+=" 00:00:00";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime+=" 00:00:00";
                    endTime+=" 23:59:59";
                }

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

            Page<Map> page = canteenDiningRecordService.canteenDiningRecordDetailList(searchParams, pageIndex, pageSize, true, sortList);

            List<Map> mapList = new ArrayList<>();

            for (Map map : page) {
//                String canteenName ="";
//                if(map.get("deviceNo")!=null){
//                    String deviceNo = map.get("deviceNo").toString();
//                    DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(deviceNo);
//                    if(deviceInfo!=null){
//                        CanteenDevice canteenDevice = canteenDeviceService.findByDeviceId(deviceInfo.getId());
//                        if(canteenDevice!=null){
//                            CanteenInfo canteenInfo = canteenInfoService.get(canteenDevice.getCanteenId());
//                            if(canteenInfo!=null){
//                                canteenName = canteenInfo.getName();
//                            }
//                        }
//                    }
//                }
//                map.put("canteenName",canteenName);
                mapList.add(map);
            }

            if(exportFlag) {
                String filePath = canteenExportXls(mapList);
                msgResult.setData(filePath);
            }
            else{
                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                msgResult.setData(dataMap);
            }

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

        return msgResult;

    }



    @ApiOperation(value="食堂就餐明细表详情")
    @RequestMapping(value = "canteenDiningRecordDetail",method = RequestMethod.POST)
    public MessageResult<Object> canteenDiningRecordDetail(
            String id,String recordTimeRange,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String subject) {

        //当前用户ID
        System.out.println(subject);

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


        try {

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

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

            searchParams.put("id",id);

            if (StringUtils.isNotEmpty(recordTimeRange)) {
                String[] timeRangeArray = recordTimeRange.split(",");
                String beginTime = "";
                String endTime = "";
                beginTime+=" 00:00:00";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime+=" 00:00:00";
                    endTime+=" 23:59:59";
                }

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

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


            Page<Map> page = canteenDiningRecordService.canteenDiningRecordDetail(searchParams, pageIndex, pageSize, true, sortList);

            List<Map> mapList = new ArrayList<>();


            for (Map map : page) {
                String personName="";
                String companyName="";
                String jobNumber="";
                String categoryN="";
                String recordTime="";

                if(map.get("person_id")!=null){
                    Long personId =Long.parseLong(map.get("person_id").toString());
                    PersonInfo personInfo = personInfoService.get(personId);
                    if(personInfo!=null){
                        personName = personInfo.getName();
                        jobNumber = personInfo.getJobNumber();
                        CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
                        if(companyInfo!=null){
                            companyName = companyInfo.getName();
                        }
                    }
                }
                map.put("personName",personName);
                map.put("companyName",companyName);
                map.put("jobNumber",jobNumber);

                if(map.get("record_time")!=null){
                    Date record_time = sdf.parse(map.get("record_time").toString());
                    recordTime = sdf.format(record_time);
                }

                map.put("recordTime",recordTime);

                if(map.get("category_")!=null){
                    String category = map.get("category_").toString();
                    categoryN = dataDictionaryService.findNameByCatalogNameAndValue("就餐类型",category);
                }

                map.put("categoryN",categoryN);

                mapList.add(map);
            }

            if(exportFlag) {
                String filePath = canteenDetailExportXls(mapList);
                msgResult.setData(filePath);
            }
            else{
                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                msgResult.setData(dataMap);
            }

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

        return msgResult;

    }


    @ApiOperation(value="部门就餐明细表")
    @RequestMapping(value = "canteenDiningRecordCompanyList",method = RequestMethod.POST)
    public MessageResult<Object> canteenDiningRecordCompanyList(
            String recordTimeRange,String companyId,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String subject) {

        //当前用户ID
        System.out.println(subject);

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


        try {

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

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

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


            if (StringUtils.isNotEmpty(recordTimeRange)) {
                String[] timeRangeArray = recordTimeRange.split(",");
                String beginTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                    beginTime+=" 00:00:00";
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime+=" 00:00:00";
                    endTime+=" 23:59:59";
                }

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

            Page<Map> page = canteenDiningRecordService.canteenDiningRecordCompanyList(searchParams, pageIndex, pageSize, true, sortList);

            List<Map> mapList = new ArrayList<>();

            for (Map map : page) {
                mapList.add(map);
            }

            if(exportFlag) {
                String filePath = companyExportXls(mapList);
                msgResult.setData(filePath);
            }
            else{
                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                msgResult.setData(dataMap);
            }

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

        return msgResult;

    }



    private String companyExportXls(List<Map> mapList) throws IOException {
        String downloadUrl = "";

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

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","部门名称","总计总数","中餐就餐总数","晚餐就餐总数","宵夜就餐总数",};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        for (int i=0;i<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("companyName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("personNum"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("lunch"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("supper"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("nightSnack"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"canteenDiningRecord","部门就餐记录统计.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }






    @ApiOperation(value="部门就餐详情表")
    @RequestMapping(value = "canteenDiningRecordCompanyDetail",method = RequestMethod.POST)
    public MessageResult<Object> canteenDiningRecordCompanyDetail(
            String recordTimeRange,String companyId,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String subject) {

        //当前用户ID
        System.out.println(subject);

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


        try {

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

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

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


            if (StringUtils.isNotEmpty(recordTimeRange)) {
                String[] timeRangeArray = recordTimeRange.split(",");
                String beginTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                    beginTime+=" 00:00:00";
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime+=" 00:00:00";
                    endTime+=" 23:59:59";
                }

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

            Page<Map> page = canteenDiningRecordService.canteenDiningRecordCompanyDetail(searchParams, pageIndex, pageSize, true, sortList);

            List<Map> mapList = new ArrayList<>();

            for (Map map : page) {
                mapList.add(map);
            }

            if(exportFlag) {
                String filePath = companyDetailExportXls(mapList);
                msgResult.setData(filePath);
            }
            else{
                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                msgResult.setData(dataMap);
            }

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

        return msgResult;

    }




    private String companyDetailExportXls(List<Map> mapList) throws IOException {
        String downloadUrl = "";

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

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","部门名称","工号","姓名","中餐就餐总数","晚餐就餐总数","宵夜就餐总数","就餐总次数"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        for (int i=0;i<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("companyName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("name_"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("job_number"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("lunch"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("supper"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("nightSnack"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("personNum"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"canteenDiningRecordCompanyDetail","部门就餐记录详情统计.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }

    @PostMapping("punchIn")
    @ApiOperation(value="食堂就餐打卡测试")
    @ApiImplicitParams({
        @ApiImplicitParam(name="deviceNo",value = "设备编号",required = true,paramType = "form"),
        @ApiImplicitParam(name="personId",value = "人员编号",required = true,paramType = "form"),
        @ApiImplicitParam(name = "recordTime",value = "考勤时间", required = true,paramType="form")
    })
    public MessageResult<String> punchIn(String deviceNo, Long personId,
                                          @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date recordTime){
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            Boolean result = canteenDiningRecordService.punchIn(deviceNo,personId,recordTime);

            //todo 填写具体代码
            messageResult.setResult(result);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return messageResult;
    }

    @GetMapping("batchUpdate")
    @ApiOperation(value="更新食堂就餐记录")
    public MessageResult<Integer> batchUpdate(Long personId,String deviceNo,
                                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date startTime,
                                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date endTime){
        MessageResult<Integer> messageResult = new MessageResult<>();
        int affectCount = 0;

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

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

            searchParams.put("deviceNo",deviceNo);
            searchParams.put("beginTime", startTime);
            searchParams.put("endTime", endTime);

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

            Page<PersonDeviceLog> page = personDeviceLogService.pageSearch(searchParams,1,100,true,sortList);
            int pages = page.getPages();

            for (int i=1;i<=pages;i++){
                List<PersonDeviceLog> list;

                if(i==1) {
                    list = page.getResult();
                }
                else{
                    page = personDeviceLogService.pageSearch(searchParams,i,100,true,sortList);
                    list = page.getResult();
                }

                for (PersonDeviceLog personDeviceLog : list) {
                    boolean result = canteenDiningRecordService.punchIn(personDeviceLog.getDeviceNo(),personDeviceLog.getPersonId(),personDeviceLog.getRecordTime());

                    if (result){
                        affectCount++;
                    }
                }
            }

            //todo 填写具体代码
            messageResult.setData(affectCount);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return messageResult;

    }
}
