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.*;
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 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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private CanteenDiningRecordService canteenDiningRecordService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @ApiOperation(value="食堂后勤人员就餐明细表")
    @RequestMapping(value = "canteenRearServiceList",method = RequestMethod.POST)
    public MessageResult<Object> canteenDiningRecordDetailList(
            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.hq_sort_no", "asc"));

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


            if (StringUtil.isNotEmpty(companyId)) {
                if("hq1".equals(companyId)){
                    //外勤1
                    searchParams.put("hqStatus", "1");
                }else if("hq2".equals(companyId)){
                    //外勤2
                    searchParams.put("hqStatus", "2");
                }
                else {
                    CompanyInfo parentCompanyInfo = companyInfoService.get(companyId);

                    searchParams.put("companyCode", parentCompanyInfo.getCode() + "%");

                    searchParams.put("hqStatus", parentCompanyInfo.getClassify());
                }
            }
            else{
                searchParams.put("querHq", "yes");
            }

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

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

            for (Map map : page) {
                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("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("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"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("totalFee"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

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

            downloadUrl = OSSUtil.upload(ossConfig,"canteenRearService","后勤人员就餐统计表.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }




    @ApiOperation(value="食堂后勤人员就餐详情")
    @RequestMapping(value = "canteenRearServiceDetail",method = RequestMethod.POST)
    public MessageResult<Object> canteenRearServiceDetail(
            String recordTimeRange,String personId,String categoryStr,
            @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("record_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);
            }


            searchParams.put("personId", personId);

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


            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 map = new HashMap();
                String personName="";
                String jobNumber="";
                String companyName="";
                String recordTime="";
                String categoryN="";

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

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

                map.put("companyName",companyName);
                map.put("personName",personName);
                map.put("jobNumber",jobNumber);
                if(StringUtils.isNotEmpty(canteenDiningRecord.getCategory())){
                    if(canteenDiningRecord.getCategory().equals("2")){
                        categoryN="中餐";
                    }
                    else if(canteenDiningRecord.getCategory().equals("3")){
                        categoryN="晚餐";
                    }
                    else if(canteenDiningRecord.getCategory().equals("4")){
                        categoryN="宵夜";
                    }
                }
                map.put("category",categoryN);
                map.put("categoryAmount",canteenDiningRecord.getCategoryAmount());
                if(canteenDiningRecord.getRecordTime()!=null){
                    recordTime = sdf.format(canteenDiningRecord.getRecordTime());
                }
                map.put("recordTime",recordTime);
                map.put("address",canteenDiningRecord.getAddress());

                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;

    }



    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("address"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("category"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("categoryAmount"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

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

            downloadUrl = OSSUtil.upload(ossConfig,"canteenRearServiceDetail","后勤人员就餐详情表.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }
}
