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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.dto.CanteenOutsourcerBalanceDTO;
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.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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/canteenOutsourcerBalance")
@Api(description = "canteenOutsourcerBalance")
public class CanteenOutsourcerBalanceController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private CanteenOutsourcerBalanceService canteenOutsourcerBalanceService;

    @Autowired
    private CanteenDiningRecordService canteenDiningRecordService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private DeviceInfoService deviceInfoService;

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

        CanteenOutsourcerBalance canteenOutsourcerBalance = new CanteenOutsourcerBalance();

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

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

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

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

        try {
            CanteenOutsourcerBalance canteenOutsourcerBalance = canteenOutsourcerBalanceService.get(id);

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

        try {
            canteenOutsourcerBalance.setUpdateBy(subject);
            canteenOutsourcerBalance.setUpdateTime(new Date());
            
            int affectCount = canteenOutsourcerBalanceService.update(canteenOutsourcerBalance);

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

            int affectCount = canteenOutsourcerBalanceService.update(canteenOutsourcerBalance);

            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) {
                CanteenOutsourcerBalance canteenOutsourcerBalance = canteenOutsourcerBalanceService.get(id);
                canteenOutsourcerBalance.setDelFlag(true);
                canteenOutsourcerBalance.setUpdateBy(subject);
                canteenOutsourcerBalance.setUpdateTime(new Date());

                affectCount += canteenOutsourcerBalanceService.update(canteenOutsourcerBalance);
            }

            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 name,String jobNumber,String companyId,String recordTimeRange,
//            @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("b.create_time","desc"));
//
//        if (StringUtils.isNotEmpty(name)) {
//            searchParams.put("name","%" + name + "%");
//        }
//
//        if (StringUtils.isNotEmpty(jobNumber)) {
//            searchParams.put("jobNumber","%" + jobNumber + "%");
//        }
//
//        if (StringUtils.isNotEmpty(companyId)) {
//            searchParams.put("companyId","%" + companyId + "%");
//        }
//
//        searchParams.put("isOutsourcer",true);
//
//        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<PersonInfo> page = personInfoService.searchCanteenOutsourcerBalance(searchParams,pageIndex,pageSize,true,sortList);
//
//        Page<CanteenOutsourcerBalanceDTO> pageDto = new Page<>();
//
//        for (PersonInfo personInfo:page) {
//            CanteenOutsourcerBalanceDTO dto = new CanteenOutsourcerBalanceDTO();
//
////            CanteenOutsourcerBalance canteenOutsourcerBalance = canteenOutsourcerBalanceService.findByPersonId(personInfo.getId());
////            if(canteenOutsourcerBalance!=null) {
////                dto.setId(canteenOutsourcerBalance.getId());
////                dto.setBalanceFee(canteenOutsourcerBalance.getAmount());
////                dto.setCardNumber(canteenOutsourcerBalance.getCardNumber());
////                dto.setLastRechargeTime(canteenOutsourcerBalance.getLastRechargeTime());
////
////            }
//
//            CanteenDiningRecord canteenDiningRecord = canteenDiningRecordService.lastEatTime(personInfo.getId());
//            if(canteenDiningRecord!=null){
//                dto.setLastMealTime(canteenDiningRecord.getRecordTime());
//            }
//
//            dto.setPersonId(personInfo.getId());
//            dto.setPersonName(personInfo.getName());
//            dto.setJobNumber(personInfo.getJobNumber());
//            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
//            if(companyInfo!=null){
//                dto.setCompanyName(companyInfo.getName());
//            }
//
//            int eatIndex = canteenDiningRecordService.findCountByPersonId(personInfo.getId());
//
//            dto.setEatIndex(eatIndex);
//
//            pageDto.add(dto);
//        }
//
//        pageDto.setPageSize(page.getPageSize());
//        pageDto.setTotal(page.getTotal());
//        pageDto.setPageNum(page.getPageNum());
//
//
//        msgResult.setResult(true);
//        msgResult.setData(PojoUtils.pageWrapper(pageDto));
//
//        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.create_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 + "%");
            }


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

            searchParams.put("isOutsourcer", true);


            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();
                    }
                }

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

                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("recordTime"),""));
            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;
    }


    @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"));

            searchParams.put("isOutsourcer", true);


            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 = page.getResult();

//            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;

    }


    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 = "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);

            searchParams.put("isOutsourcer", true);

            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", "asc"));

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


            searchParams.put("isOutsourcer", true);


            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 = page.getResult();

            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);
            }

            searchParams.put("isOutsourcer", true);

            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(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;
    }
}
