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

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.dto.ParkingRecordDTO;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.ParkingInfo;
import com.jpsoft.shinestar.modules.base.entity.ParkingRecord;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.ParkingInfoService;
import com.jpsoft.shinestar.modules.base.service.ParkingRecordService;
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.DataDictionary;
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.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.*;

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

    @Autowired
    private ParkingRecordService parkingRecordService;

    @Autowired
    private ParkingInfoService parkingInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private UserService userService;


    @ApiOperation(value="停车收费明细列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Object> pageList(
            String carNum,String companyId,String carType,String payType,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date paymentStartTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date paymentEndTime,
            @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(carNum)) {
                searchParams.put("carNum", "%" + carNum + "%");
            }
            if (StringUtils.isNotEmpty(companyId)) {
                searchParams.put("companyId", companyId);
            }
            if (StringUtils.isNotEmpty(carType)) {
                searchParams.put("carType", carType);
            }
            if (StringUtils.isNotEmpty(payType)) {
                searchParams.put("payType", payType);
            }

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

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

            //当前用户ID
            User user = userService.get(subject);
            if (!userService.hasRole(subject,"SYSADMIN")) {
                CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

                searchParams.put("parentCompanyCode", companyInfo.getCode() + "%");
            }

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

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

            for (ParkingRecord parkingRecord : page) {
                Map<String, Object> map = new HashMap<>();

                map.put("id", parkingRecord.getId());
                map.put("carNum",parkingRecord.getCarNum());

                ParkingInfo parkingInfo = parkingInfoService.findByParkId(parkingRecord.getParkId());

                if (parkingInfo != null) {
                    CompanyInfo companyInfo = companyInfoService.get(parkingInfo.getCompanyId());
                    if (companyInfo != null) {
                        map.put("companyName",companyInfo.getName());
                    }
                }

                if (StringUtils.isNotEmpty(parkingRecord.getCarType())) {
                    String carTypeN = dataDictionaryService.findNameByCatalogNameAndValue("车辆类型", "36");
                    map.put("carType",carTypeN);
                }

                map.put("parkingTime",parkingRecord.getParkingTime());
                map.put("totalAmount",parkingRecord.getTotalAmount());
                map.put("reduceAmount",parkingRecord.getReduceAmount());
                map.put("payAmount",parkingRecord.getPayAmount());

                if(parkingRecord.getPaymentTime()!=null){
                    map.put("paymentTime",DateUtil.format(parkingRecord.getPaymentTime(),"yyyy-MM-dd HH:mm"));
                }
                map.put("payType",parkingRecord.getPayTypeN());

                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) {
        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("carNum"),""));
            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("carType"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("parkingTime"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("totalAmount"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("reduceAmount"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("payAmount"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("paymentTime"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("payType"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

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

            downloadUrl = OSSUtil.upload(ossConfig,"parkingRecord","停车收费记录.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }


    @ApiOperation(value="车辆类型列表")
    @RequestMapping(value = "carTypeList",method = RequestMethod.POST)
    public MessageResult<List<DataDictionary>> carTypeList(){
        MessageResult<List<DataDictionary>> msgResult = new MessageResult<>();

        List<DataDictionary> list = dataDictionaryService.findByCatalogName("车辆类型");

        msgResult.setResult(true);
        msgResult.setData(list);
        return msgResult;
    }




    @ApiOperation(value="停车收费明细列表")
    @RequestMapping(value = "inOutPageList",method = RequestMethod.POST)
    public MessageResult<Object> inOutPageList(
            String carNum,String carType,String carStatus,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date inParkingStartTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date inParkingEndTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date outParkingStartTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date outParkingEndTime,
            @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(carNum)) {
                searchParams.put("carNum", "%" + carNum + "%");
            }
            if (StringUtils.isNotEmpty(carType)) {
                searchParams.put("carType", carType);
            }

            if (StringUtils.isNotEmpty(carStatus)) {
                if(carStatus.equals("1")){
                    searchParams.put("outParkingTime", "1");
                }
                else{
                    searchParams.put("outParkingTime", "0");
                }

            }

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

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

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

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

            //当前用户ID
            User user = userService.get(subject);
            if (!userService.hasRole(subject,"SYSADMIN")) {
                CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

                searchParams.put("parentCompanyCode", companyInfo.getCode() + "%");
            }

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

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

            for (ParkingRecord parkingRecord : page) {
                Map<String, Object> map = new HashMap<>();

                map.put("id", parkingRecord.getId());
                map.put("carNum",parkingRecord.getCarNum());

                if (StringUtils.isNotEmpty(parkingRecord.getCarType())) {
                    String carTypeN = dataDictionaryService.findNameByCatalogNameAndValue("车辆类型", "36");
                    map.put("carType",carTypeN);
                }

                if(parkingRecord.getOutParkingTime()!=null) {
                    map.put("carStatusN", "已离场");
                    map.put("carStatus", "1");
                }
                else{
                    map.put("carStatusN", "停车中");
                    map.put("carStatus", "0");
                }


                if(parkingRecord.getInParkingTime()!=null){
                    map.put("inParkingTime",DateUtil.format(parkingRecord.getInParkingTime(),"yyyy-MM-dd HH:mm"));
                }

                if(parkingRecord.getOutParkingTime()!=null){
                    map.put("outParkingTime",DateUtil.format(parkingRecord.getOutParkingTime(),"yyyy-MM-dd HH:mm"));
                }

                map.put("parkingTime",parkingRecord.getParkingTime());

                mapList.add(map);

            }


            if (exportFlag) {
                String filePath = inOutExportXls(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 inOutExportXls(List<Map> mapList) {
        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("carNum"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("carType"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("carStatusN"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("inParkingTime"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("outParkingTime"),""));
            if(map.get("parkingTime")!=null) {
                row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("parkingTime") + "分钟", ""));
            }
            else{
                row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("parkingTime"), ""));
            }
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

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

            downloadUrl = OSSUtil.upload(ossConfig,"parkingRecordInOut","车辆出入记录.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }
}
