package com.yijia.station.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.yijia.common.annotation.Excel;
import com.yijia.common.config.YiJiaConfig;
import com.yijia.common.core.domain.model.LoginUser;
import com.yijia.common.exception.CustomException;
import com.yijia.common.utils.SecurityUtils;
import com.yijia.station.domain.*;
import com.yijia.station.mapper.PayOrderMapper;
import com.yijia.station.service.*;
import com.yijia.station.utils.FeiEPrinterUtil;
import com.yijia.system.service.ISysUserService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yijia.common.annotation.Log;
import com.yijia.common.core.controller.BaseController;
import com.yijia.common.core.domain.AjaxResult;
import com.yijia.common.enums.BusinessType;
import com.yijia.common.utils.poi.ExcelUtil;
import com.yijia.common.core.page.TableDataInfo;

/**
 * 班结管理Controller
 *
 * @author yijia
 * @date 2020-12-31
 */
@RestController
@RequestMapping("/station/structure")
public class StationClassStructureController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(StationClassStructureController.class);
    @Autowired
    private IStationClassStructureService stationClassStructureService;
    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private IStationClassesSummaryService stationClassesSummaryService;
    @Autowired
    private IStationDeviceManageService stationDeviceManageService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IStationPayService stationPayService;
    /**
     * 查询班结管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(StationClassStructure stationClassStructure)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        boolean flag= sysUserService.getUserRole(currentUser);
        if(!flag){
            stationClassStructure.setStationId(currentUser.getUser().getDeptId());
        }
        startPage();
        List<StationClassStructure> list = stationClassStructureService.selectStationClassStructureList(stationClassStructure);
        return getDataTable(list);
    }
    @GetMapping("/listPersonnelStructure")
    public TableDataInfo listPersonnelStructure(StationClassStructure stationClassStructure)
    {
        List<StationClassStructure> list = new ArrayList<>();
        if(stationClassStructure!=null &&stationClassStructure.getStationId()!=null ){
            list = stationClassStructureService.listPersonnelStructure(stationClassStructure);
        }
        return getTable(list);
    }

    @GetMapping("/listOilStructure")
    public TableDataInfo listOilStructure(StationClassStructure stationClassStructure)
    {
        List<StationClassStructure> list = new ArrayList<>();
        if(stationClassStructure!=null &&stationClassStructure.getStationId()!=null ){
            list = stationClassStructureService.listOilStructure(stationClassStructure);
        }
        return getTable(list);
    }
    @GetMapping("/listPersonnelPayStructure")
    public TableDataInfo listPersonnelPayStructure(StationClassStructure stationClassStructure)
    {
        List<StationClassStructure> list = new ArrayList<>();
        if(stationClassStructure!=null &&stationClassStructure.getStationId()!=null ){
            list = stationClassStructureService.listPersonnelPayStructure(stationClassStructure);
        }
        return getTable(list);
    }

    @GetMapping("/listClass")
    public AjaxResult listClass(StationClassStructure stationClassStructure)
    {
        return AjaxResult.success(stationClassStructureService.listClass(stationClassStructure));
    }
    /**
     * 导出班结管理列表
     */

    @Log(title = "班结管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(StationClassStructure stationClassStructure)
    {
        StationClassesSummary stationClassesSummary =new StationClassesSummary();
        stationClassesSummary.setStationId(stationClassStructure.getStationId());
        stationClassesSummary.setClassesNo(stationClassStructure.getClassStructureNo());
        StationClassesSummary summary= stationClassesSummaryService.selectStationClassesSummary(stationClassesSummary);
        List<StationClassStructure> listPersonnelPay = stationClassStructureService.listPersonnelPayStructure(stationClassStructure);
        List<StationClassStructure> oillist = stationClassStructureService.listOilStructure(stationClassStructure);
        List<StationClassStructure> listPersonnel = stationClassStructureService.listPersonnelStructure(stationClassStructure);
        StationClassStructure listPersonnelPaySum =stationClassStructureService.listPersonnelPayStructureSum(stationClassStructure);
        StationClassStructure oillistSum =stationClassStructureService.listOilStructureSum(stationClassStructure);
        StationClassStructure listPersonnelSum =stationClassStructureService.listPersonnelStructureSum(stationClassStructure);
        AjaxResult ss = exportExcel( summary,listPersonnel,oillist,listPersonnelPay,listPersonnelPaySum,oillistSum,listPersonnelSum, "structure");
        return ss;
    }
    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param list 导出数据集合
     * @param sheetName 工作表的名称
     * @return 结果
     */
    public AjaxResult exportExcel( StationClassesSummary summary,List<StationClassStructure> listP,List<StationClassStructure> listOil,List<StationClassStructure> list,StationClassStructure listPersonnelPaySum,StationClassStructure oillistSum,StationClassStructure listPersonnelSum, String sheetName)
    {
        OutputStream out = null;
        Workbook wb= new SXSSFWorkbook(500);
        try
        {
            Sheet sheet = wb.createSheet("班结数据");
            sheet.setDefaultColumnWidth(20);//默认列宽20
            CellStyle style = wb.createCellStyle();
            CreationHelper createHelper = wb.getCreationHelper();
            style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
            int rows =listP.size()+listOil.size()+list.size()+10;
            int personlist =listP.size()+3;
            int oillist =personlist+3+listOil.size();
            Cell cell =null;
            Row row =null;
            for (int i = 0; i < rows; i++) {
                if(i == 0) {
                    row = sheet.createRow(i);
                    cell = row.createCell(0);
                    cell.setCellStyle(style);
                    cell.setCellValue("班结开始时间：");
                    cell = row.createCell(1);
                    cell.setCellStyle(style);
                    cell.setCellValue(summary.getStartDate());
                    cell = row.createCell(2);
                    cell.setCellStyle(style);
                    cell.setCellValue("班结人：");
                    cell = row.createCell(3);
                    cell.setCellStyle(style);
                    cell.setCellValue(summary.getClassesMan());
                }else if(i == 1){// 生成第一行(表头)
                    row = sheet.createRow(i);
                    // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
                    sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 5));
                    cell = row.createCell(0);
                    cell.setCellStyle(style);
                    cell.setCellValue("按员工汇总");
                }else {
                    if (i == 2) {
                        row = sheet.createRow(i);
                        cell = row.createCell(0);
                        cell.setCellValue("员工姓名");
                        cell.setCellStyle(style);
                        cell = row.createCell(1);
                        cell.setCellValue("负责枪号");
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue("销量");
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue("销额");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue("销售笔数");
                        cell.setCellStyle(style);
                    } else if (i > 2 && i < personlist) {
                        row = sheet.createRow(i);
                        int j = i - 3;
                        cell = row.createCell(0);
                        cell.setCellValue(listP.get(j).getOilPersonnel());
                        cell.setCellStyle(style);
                        cell = row.createCell(1);
                        cell.setCellValue(listP.get(j).getOilGun());
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue(listP.get(j).getOrderLiters() + "");
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue(listP.get(j).getAmt() + "");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue(listP.get(j).getOrderNo());
                        cell.setCellStyle(style);
                    }else if (i == personlist) {
                        row = sheet.createRow(i);
                        cell = row.createCell(0);
                        cell.setCellValue("合计");
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue(listPersonnelSum.getOrderLiters()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue(listPersonnelSum.getAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue(listPersonnelSum.getOrderNo());
                        cell.setCellStyle(style);
                    }else if (i == personlist+1) {
                        row = sheet.createRow(i);
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 5));
                        cell = row.createCell(0);
                        cell.setCellStyle(style);
                        cell.setCellValue("按油品汇总");
                    } else if (i == personlist + 2) {
                        row = sheet.createRow(i);
                        cell = row.createCell(0);
                        cell.setCellValue("油品");
                        cell.setCellStyle(style);
                        cell = row.createCell(1);
                        cell.setCellValue("负责枪号");
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue("销量");
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue("销额");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue("销售笔数");
                        cell.setCellStyle(style);
                    } else if (i > personlist+2 && i < oillist) {
                        row = sheet.createRow(i);
                        int j = i - personlist-3;
                        cell = row.createCell(0);
                        cell.setCellValue(listOil.get(j).getOilName());
                        cell.setCellStyle(style);
                        cell = row.createCell(1);
                        cell.setCellValue(listOil.get(j).getOilGun());
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue(listOil.get(j).getOrderLiters().toString());
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue(listOil.get(j).getAmt() + "");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue(listOil.get(j).getOrderNo());
                        cell.setCellStyle(style);
                    } else if(i==oillist){
                        row = sheet.createRow(i);
                        cell = row.createCell(0);
                        cell.setCellValue("合计");
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue(oillistSum.getOrderLiters() + "");
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue(oillistSum.getAmt() + "");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue(oillistSum.getOrderNo());
                        cell.setCellStyle(style);
                    }else if(i==oillist+1){
                        row = sheet.createRow(i);
                        sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 11));
                        cell = row.createCell(0);
                        cell.setCellStyle(style);
                        cell.setCellValue("按员工/支付方式汇总");
                    }else if(i==oillist+2){
                        row = sheet.createRow(i);
                        cell = row.createCell(0);
                        cell.setCellValue("员工姓名");
                        cell.setCellStyle(style);
                        cell = row.createCell(1);
                        cell.setCellValue("负责枪号");
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue("微信笔数");
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue("支付宝笔数");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue("现金笔数");
                        cell.setCellStyle(style);
                        cell = row.createCell(5);
                        cell.setCellValue("优惠");
                        cell.setCellStyle(style);
                        cell = row.createCell(6);
                        cell.setCellValue("优惠劵");
                        cell.setCellStyle(style);
                        cell = row.createCell(7);
                        cell.setCellValue("微信金额");
                        cell.setCellStyle(style);
                        cell = row.createCell(8);
                        cell.setCellValue("支付宝金额");
                        cell.setCellStyle(style);
                        cell = row.createCell(9);
                        cell.setCellValue("现金金额");
                        cell.setCellStyle(style);
                        cell = row.createCell(10);
                        cell.setCellValue("会员卡支付");
                        cell.setCellStyle(style);
                    }else if(i<rows-1){
                        int j =i-oillist-3;
                        row = sheet.createRow(i);
                        cell = row.createCell(0);
                        cell.setCellValue(list.get(j).getOilPersonnel());
                        cell.setCellStyle(style);
                        cell = row.createCell(1);
                        cell.setCellValue(list.get(j).getOilGun());
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue(list.get(j).getWxNum()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue(list.get(j).getZfbNum()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue(list.get(j).getXjNum()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(5);
                        cell.setCellValue(list.get(j).getDiscountAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(6);
                        cell.setCellValue(list.get(j).getDiscountCouponAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(7);
                        cell.setCellValue(list.get(j).getWxAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(8);
                        cell.setCellValue(list.get(j).getZfbAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(9);
                        cell.setCellValue(list.get(j).getXjAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(10);
                        cell.setCellValue(list.get(j).getMemberAmt()+"");
                        cell.setCellStyle(style);
                    }else{
                        row = sheet.createRow(i);
                        cell = row.createCell(0);
                        cell.setCellValue("合计");
                        cell.setCellStyle(style);
                        cell = row.createCell(2);
                        cell.setCellValue(listPersonnelPaySum.getWxNum()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(3);
                        cell.setCellValue(listPersonnelPaySum.getZfbNum()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(4);
                        cell.setCellValue(listPersonnelPaySum.getXjNum()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(5);
                        cell.setCellValue(listPersonnelPaySum.getDiscountAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(6);
                        cell.setCellValue(listPersonnelPaySum.getDiscountCouponAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(7);
                        cell.setCellValue(listPersonnelPaySum.getWxAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(8);
                        cell.setCellValue(listPersonnelPaySum.getZfbAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(9);
                        cell.setCellValue(listPersonnelPaySum.getXjAmt()+"");
                        cell.setCellStyle(style);
                        cell = row.createCell(10);
                        cell.setCellValue(listPersonnelPaySum.getMemberAmt()+"");
                        cell.setCellStyle(style);
                    }
                }
            }
            String filename = encodingFilename(sheetName);
            out = new FileOutputStream(getAbsoluteFile(filename));
            wb.write(out);
            out.close();// 关闭输出流
            return AjaxResult.success(filename);
        }
        catch (Exception e)
        {
            log.error("导出Excel异常{}", e.getMessage());
            throw new CustomException("导出Excel失败，请联系网站管理员！");
        }
        finally
        {
            if (wb != null)
            {
                try
                {
                    wb.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (out != null)
            {
                try
                {
                    out.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

    private String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }

    public String getAbsoluteFile(String filename)
    {
        String downloadPath = YiJiaConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * 获取班结管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('station:structure:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(stationClassStructureService.selectStationClassStructureById(id));
    }

    /**
     * 新增班结管理
     */
    @Log(title = "班结管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StationClassStructure stationClassStructure) throws ParseException {
        //获取当前班结油站
        LoginUser currentUser = SecurityUtils.getLoginUser();
        Long stationId=currentUser.getUser().getDeptId();
        String stationName=stationClassStructure.getStationName();
        String username = stationClassStructure.getClassStructureMan();
        //根据油站查询出油站是否班结过，班结过就需要查询上次班结的时间
        StationClassStructure classes =new StationClassStructure();
        classes.setStationId(stationId);
        //查询出上次班结，最后一条数据
        StationClassStructure sss =stationClassStructureService.selectStationClassStructureMax(classes);
        String beginTime="";
        //当前时间
        Date date= new Date();
        StationClassStructure classesStructure =new StationClassStructure();
        classesStructure.setStationId(stationId);
        DateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
        String no=dFormat.format(date);
        classesStructure.setLikeClassStructureNo(no);
        //查询班结信息中本日班结次数
        StationClassStructure structure =stationClassStructureService.selectDistnctClassStructure(classesStructure);
        if(structure!=null){
            if(structure.getNum()==0){
                no = no + "0"+1;
            }else{
                int num  = structure.getNum()+1;
                if(num>0 && num<10){
                    no = no + "0"+num;
                }else{
                    no = no +""+ num;
                }
            }
        }
        int i=0;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dfe = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(sss!=null){
            //获取上次班结时间
            PayOrder order=new PayOrder();
            order.setStationId(stationId);
            order.setStatus("1");
            beginTime= dateFormat.format(sss.getClassStructureDate());
            order.setBeginTime(beginTime);
            order.setEndTime( dateFormat.format(date));
            List<PayOrder> list = payOrderService.selectPayOrderList(order);
            for(PayOrder payOrder:list){
                StationClassStructure stationclass =new StationClassStructure();
                stationclass.setStationId(payOrder.getStationId());
                stationclass.setStationName(payOrder.getStationName());
                stationclass.setClassStartDate(dfe.parse(beginTime));
                stationclass.setClassStructureMan(username);
                stationclass.setClassStructureNo(no);
                stationclass.setClassStructureDate(date);
                stationclass.setOrderNo(payOrder.getOrderNo());
                stationclass.setOilGun(payOrder.getOilGun());
                stationclass.setOilName(payOrder.getOilName());
                if(payOrder.getOilPirce()!=null){
                    stationclass.setOilPirce(payOrder.getOilPirce());
                }
                if(payOrder.getOilType()!=null){
                    stationclass.setOilType(payOrder.getOilType());
                }
                stationclass.setConsumerId(payOrder.getConsumerId());
                stationclass.setConsumer(payOrder.getConsumer());
                stationclass.setAmt(payOrder.getAmt());
                if(payOrder.getReceivableAmt()!=null){
                    stationclass.setReceivableAmt(payOrder.getReceivableAmt());
                }else{
                    stationclass.setReceivableAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getReceivedAmt()!=null){
                    stationclass.setReceivedAmt(payOrder.getReceivedAmt());
                }else{
                    stationclass.setReceivedAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getDiscountAmt()!=null){
                    stationclass.setDiscountAmt(payOrder.getDiscountAmt());
                }else{
                    stationclass.setDiscountAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getDiscountCouponAmt()!=null){
                    stationclass.setDiscountCouponAmt(payOrder.getDiscountCouponAmt());
                }else{
                    stationclass.setDiscountCouponAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getWxAmt()!=null){
                    stationclass.setWxAmt(payOrder.getWxAmt());
                }else{
                    stationclass.setWxAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getZfbAmt()!=null){
                    stationclass.setZfbAmt(payOrder.getZfbAmt());
                }else{
                    stationclass.setZfbAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getPosAmt()!=null){
                    stationclass.setPosAmt(payOrder.getPosAmt());
                }else{
                    stationclass.setPosAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getXjAmt()!=null){
                    stationclass.setXjAmt(payOrder.getXjAmt());
                }else{
                    stationclass.setXjAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getDidiAppAmt()!=null){
                    stationclass.setDidiAppAmt(payOrder.getDidiAppAmt());
                }else{
                    stationclass.setDidiAppAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getTyAppAmt()!=null){
                    stationclass.setDidiAppAmt(payOrder.getTyAppAmt());
                }else{
                    stationclass.setDidiAppAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getOtherAmt()!=null){
                    stationclass.setOtherAmt(payOrder.getOtherAmt());
                }else{
                    stationclass.setOtherAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getDzkAmt()!=null){
                    stationclass.setDzkAmt(payOrder.getDzkAmt());
                }else{
                    stationclass.setDzkAmt(BigDecimal.valueOf(0));
                }
                if(payOrder.getMemberAmt()!=null){
                    stationclass.setMemberAmt(payOrder.getMemberAmt());
                }else{
                    stationclass.setMemberAmt(BigDecimal.valueOf(0));
                }
                stationclass.setOrderLiters(payOrder.getOrderLiters());
                stationclass.setPayWay(payOrder.getPayWay());
                stationclass.setPayType(payOrder.getPayType());
                stationclass.setPayDate(payOrder.getPayDate());
                stationclass.setOilPersonnel(payOrder.getOilPersonnel());
                stationclass.setOrderType(payOrder.getOrderType());
                if(payOrder.getPrintCount()!=null){
                    stationclass.setPrintNum(payOrder.getPrintCount());
                }else{
                    stationclass.setPrintNum(Long.valueOf("0"));
                }

                i= stationClassStructureService.insertStationClassStructure(stationclass);
            }
        }else{
            //初次班结 班结时间默认为当前时间，班结人username
            PayOrder p =new  PayOrder();
            p.setStationId(stationId);
            p.setStatus("1");
            PayOrder orders= payOrderService.getPayOrderInfoMin(p);
            if(orders!=null){
                //根据班结时间查询订单
                PayOrder order=new PayOrder();
                beginTime= dateFormat.format(orders.getCreatedDate());
                order.setStationId(stationId);
                order.setStatus("1");
                order.setEndTime(dateFormat.format(date));
                List<PayOrder> list = payOrderService.selectPayOrderList(order);
                if(list !=null && list.size()>0){
                    for(PayOrder payOrder:list){
                        StationClassStructure stationclass =new StationClassStructure();
                        stationclass.setStationId(payOrder.getStationId());
                        stationclass.setClassStartDate(dfe.parse(beginTime));
                        stationclass.setStationName(payOrder.getStationName());
                        stationclass.setClassStructureMan(username);
                        stationclass.setClassStructureDate(date);
                        stationclass.setClassStructureNo(no);
                        stationclass.setOrderNo(payOrder.getOrderNo());
                        stationclass.setOilGun(payOrder.getOilGun());
                        stationclass.setOilName(payOrder.getOilName());
                        if(payOrder.getOilPirce()!=null){
                            stationclass.setOilPirce(payOrder.getOilPirce());
                        }
                        if(payOrder.getOilType()!=null){
                            stationclass.setOilType(payOrder.getOilType());
                        }
                        stationclass.setConsumerId(payOrder.getConsumerId());
                        stationclass.setConsumer(payOrder.getConsumer());
                        stationclass.setAmt(payOrder.getAmt());
                        if(payOrder.getReceivableAmt()!=null){
                            stationclass.setReceivableAmt(payOrder.getReceivableAmt());
                        }else{
                            stationclass.setReceivableAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getReceivedAmt()!=null){
                            stationclass.setReceivedAmt(payOrder.getReceivedAmt());
                        }else{
                            stationclass.setReceivedAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getDiscountAmt()!=null){
                            stationclass.setDiscountAmt(payOrder.getDiscountAmt());
                        }else{
                            stationclass.setDiscountAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getDiscountCouponAmt()!=null){
                            stationclass.setDiscountCouponAmt(payOrder.getDiscountCouponAmt());
                        }else{
                            stationclass.setDiscountCouponAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getWxAmt()!=null){
                            stationclass.setWxAmt(payOrder.getWxAmt());
                        }else{
                            stationclass.setWxAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getZfbAmt()!=null){
                            stationclass.setZfbAmt(payOrder.getZfbAmt());
                        }else{
                            stationclass.setZfbAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getPosAmt()!=null){
                            stationclass.setPosAmt(payOrder.getPosAmt());
                        }else{
                            stationclass.setPosAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getXjAmt()!=null){
                            stationclass.setXjAmt(payOrder.getXjAmt());
                        }else{
                            stationclass.setXjAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getDidiAppAmt()!=null){
                            stationclass.setDidiAppAmt(payOrder.getDidiAppAmt());
                        }else{
                            stationclass.setDidiAppAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getTyAppAmt()!=null){
                            stationclass.setDidiAppAmt(payOrder.getTyAppAmt());
                        }else{
                            stationclass.setDidiAppAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getOtherAmt()!=null){
                            stationclass.setOtherAmt(payOrder.getOtherAmt());
                        }else{
                            stationclass.setOtherAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getDzkAmt()!=null){
                            stationclass.setDzkAmt(payOrder.getDzkAmt());
                        }else{
                            stationclass.setDzkAmt(BigDecimal.valueOf(0));
                        }
                        if(payOrder.getMemberAmt()!=null){
                            stationclass.setMemberAmt(payOrder.getMemberAmt());
                        }else{
                            stationclass.setMemberAmt(BigDecimal.valueOf(0));
                        }
                        stationclass.setOrderLiters(payOrder.getOrderLiters());
                        stationclass.setPayWay(payOrder.getPayWay());
                        stationclass.setPayType(payOrder.getPayType());
                        stationclass.setPayDate(payOrder.getPayDate());
                        stationclass.setOilPersonnel(payOrder.getOilPersonnel());
                        stationclass.setOrderType(payOrder.getOrderType());
                        if(payOrder.getPrintCount()!=null){
                            stationclass.setPrintNum(payOrder.getPrintCount());
                        }else{
                            stationclass.setPrintNum(Long.valueOf("0"));
                        }
                        i= stationClassStructureService.insertStationClassStructure(stationclass);
                    }
                }

            }
        }
        StationClassStructure scs =new StationClassStructure();
        scs.setClassStructureNo(no);
        scs.setStationId(stationId);
        scs.setOrderType("1"); //油品
        //汇总班结数据将汇总的数据插入到汇总数据中
        StationClassStructure stationclass = stationClassStructureService.selectSummyClassStructure(scs);
        if(stationclass!=null){
            StationClassesSummary stationClassesSummary =new StationClassesSummary();
            stationClassesSummary.setClassesNo(stationclass.getClassStructureNo());
            if(stationclass.getClassStartDate()!=null){
                stationClassesSummary.setStartDate(stationclass.getClassStartDate());
            }
            if(stationclass.getClassStructureDate()!=null){
                stationClassesSummary.setEndDate(stationclass.getClassStructureDate());
            }
            stationClassesSummary.setStationName(stationclass.getStationName());
            if(stationclass.getStationId()!=null){
                stationClassesSummary.setStationId(stationclass.getStationId());
            }
            if(stationclass.getNum()!=null){
                stationClassesSummary.setOrderNum(Long.valueOf(stationclass.getNum()));
            }
            if(stationclass.getPrintNum()!=null){
                stationClassesSummary.setPrintNum(stationclass.getPrintNum());
            }
            if(stationclass.getOrderLiters()!=null){
                stationClassesSummary.setSaleLiters(stationclass.getOrderLiters());
            }
            if(stationclass.getAmt()!=null){
                stationClassesSummary.setAmt(stationclass.getAmt());
            }
            if(stationclass.getReceivableAmt()!=null){
                stationClassesSummary.setSaleAmt(stationclass.getReceivableAmt());
            }
            if(stationclass.getDiscountAmt()!=null){
                stationClassesSummary.setDiscountAmt(stationclass.getDiscountAmt());
            }
            if(stationclass.getDzkAmt()!=null){
                stationClassesSummary.setDzkAmt(stationclass.getDzkAmt());
            }else{
                stationClassesSummary.setDzkAmt(BigDecimal.valueOf(0));
            }
            if(stationclass.getZfbAmt()!=null){
                stationClassesSummary.setZfbAmt(stationclass.getZfbAmt());
            }else{
                stationClassesSummary.setZfbAmt(BigDecimal.valueOf(0));
            }
            if(stationclass.getWxAmt()!=null){
                stationClassesSummary.setWxAmt(stationclass.getWxAmt());
            }else{
                stationClassesSummary.setWxAmt(BigDecimal.valueOf(0));
            }
            if(stationclass.getPrintNum()!=null){
                stationClassesSummary.setPrintNum(stationclass.getPrintNum());
            }else{
                stationClassesSummary.setPrintNum(Long.valueOf("0"));
            }
            stationClassesSummary.setClassesMan(stationclass.getClassStructureMan());
            i=stationClassesSummaryService.insertStationClassesSummary(stationClassesSummary);
            //班结成功，打印小票
            //根据油站查询是否打印班结小票
            StationPay  stationPay =new StationPay();
            stationPay.setStationId(stationId);
            StationPay pay = stationPayService.selectStationPayOne(stationPay);
            if(pay!=null &&pay.getWsPrintFlag() !=null &&pay.getWsPrintFlag()!="" &&pay.getWsPrintFlag().equals("1")){
                //查询班结小票数据
                StationClassStructure classStructure= new StationClassStructure();
                classStructure.setClassStructureNo(no);
                classStructure.setStationId(stationId);
                classStructure.setOrderType("1");// 油品
                List<StationClassStructure>  list= stationClassStructureService.listOilStructure(classStructure);
                //支付方式汇总数据
                List<StationClassStructure>  paylist= stationClassStructureService.listPayStructure(classStructure);
                //汇总非油品
                StationClassStructure selectNoOil =new StationClassStructure();
                selectNoOil.setClassStructureNo(no);
                selectNoOil.setStationId(stationId);
                selectNoOil.setOrderType("2");// 非油品
                StationClassStructure search = stationClassStructureService.selectSummyClassStructure(selectNoOil);
                //查询出小票数据
                String content;
                content = "<CB>班结小票</CB><BR>";
                content += "--------------------------------<BR>";
                if(list!=null && list.size()>0 && paylist !=null && paylist.size()>0 ){
                    if(list.get(0).getClassStartDate()!=null){
                        content += "开始时间："+dateFormat.format(list.get(0).getClassStartDate())+"  <BR>";
                    }else{
                        content += "开始时间： <BR>";
                    }
                    content += "班结时间："+dateFormat.format(list.get(0).getClassStructureDate())+" <BR>";
                    content += "油品  笔    升数      金额<BR>";
                    content += "--------------------------------<BR>";

                    BigDecimal sumAmt = new BigDecimal(0);
                    BigDecimal liters = new BigDecimal(0);
                    BigDecimal coupon = new BigDecimal(0);
                    BigDecimal ysAmt =  new BigDecimal(0);
                    BigDecimal dzAmt =  new BigDecimal(0);
                    int num = 0;
                    int pageNum=0;
                    for(StationClassStructure str : list){
                        String orderLiter="";
                        String amt="";
                        String receivableAmt="";
                        String orderno="";
                        //打印小票数量
                        if(str.getPrintNum()!=null){
                            pageNum += str.getPrintNum();
                        }
                        if( str.getOrderLiters()==null){
                            str.setOrderLiters(BigDecimal.valueOf(0));
                            orderLiter="0";
                        }else{
                            liters=liters.add(str.getOrderLiters());
                            orderLiter= str.getOrderLiters().toString();
                        }
                        //实收金额
                        if( str.getAmt()==null){
                            str.setAmt(BigDecimal.valueOf(0));
                            amt="0";
                        }else{
                            sumAmt=sumAmt.add(str.getAmt());
                            amt=str.getAmt().toString();
                        }
                        //应付金额
                        if( str.getReceivableAmt()==null){
                            str.setReceivableAmt(BigDecimal.valueOf(0));
                            receivableAmt="0";
                        }else{
                            ysAmt=ysAmt.add(str.getReceivableAmt());
                            receivableAmt=str.getReceivableAmt().toString();
                        }
                        //到款金额
                        if( str.getReceivedAmt()==null){
                            str.setReceivedAmt(BigDecimal.valueOf(0));
                        }else{
                            dzAmt = dzAmt.add(str.getReceivedAmt());
                        }
                        //优惠金额
                        if( str.getDiscountAmt()==null){
                            str.setDiscountAmt(BigDecimal.valueOf(0));
                        }else{
                            coupon=coupon.add(str.getDiscountAmt());
                        }
                        //订单数量
                        if( str.getOrderNo()==null){
                            str.setOrderNo(String.valueOf(0));
                        }else{
                            num= num+Integer.parseInt(str.getOrderNo());
                            orderno=str.getOrderNo().toString();
                        }
                        String oilname=addSpace(str.getOilName(),4);
                        orderno=addSpace(orderno,3);
                        orderLiter=addSpace(orderLiter,8);
                        receivableAmt=addSpace(receivableAmt,8);
                        content += oilname+"  "+orderno+"  "+orderLiter+"  "+receivableAmt+"<BR>";
                    }
                    content += "--------------------------------<BR>";
                    String sumorder=addSpace(String.valueOf(num),3);
                    String oilliters=addSpace(String.valueOf(liters),9);
                    String oilYsAmt=addSpace(String.valueOf(ysAmt),9);
                    content += "合计  "+sumorder +"  "+liters +"  "+oilYsAmt+"<BR>";
                    content += " <BR>";
                    //按支付方式
                    content += "支付方式  笔    升数      金额<BR>";
                    for(StationClassStructure sc : paylist){
                        String orderno= sc.getOrderNo();
                        orderno =addSpace(orderno,3);
                        String orderLiter="";
                        if(sc.getOrderLiters()!=null){
                            orderLiter = sc.getOrderLiters().toString();
                        }else{
                            sc.setOrderLiters(BigDecimal.valueOf(0));
                            orderLiter= sc.getOrderLiters().toString();
                        }
                        orderLiter =addSpace(orderLiter,8);
                        String receivableAmt="";
                        if(sc.getReceivableAmt()!=null){
                            receivableAmt = sc.getReceivableAmt().toString();
                        }else{
                            sc.setReceivableAmt(BigDecimal.valueOf(0));
                            receivableAmt= sc.getReceivableAmt().toString();
                        }
                        content += sc.getPayType()+"  "+orderno+"  "+orderLiter+"  "+receivableAmt+"<BR>";
                    }
                    content += "小票张数： "+pageNum+" 张<BR>";
                    content += "班结金额： "+ysAmt+" 元<BR>";
                    content += "优惠总额： "+coupon+" 元<BR>";
                    content += "实际支付： "+sumAmt+" 元<BR>";
                    content += "到款金额： "+dzAmt+"元<BR>";
                    content += "--------------------------------<BR>";
                    if(search!=null){
                        if( search.getAmt()==null){
                            search.setAmt(BigDecimal.valueOf(0));
                        }
                        content +="非油总额： "+search.getAmt()+"元<BR>";
                    }else{
                        content +="非油总额： 0  元<BR>";
                    }
                    content += "班结人： "+list.get(0).getClassStructureMan()+"<BR>";
                    content += "<BR>";
                    content += "--------------------------------<BR>";
                    content += "<BR>";
                    //查询打印机信息
                    Map params  =new HashMap();
                    params.put("stationId", list.get(0).getStationId());
                    params.put("deviceType", "3");
                    Map mp  = stationDeviceManageService.getPrinterSnByStationId(params);
                    if(mp!=null&&mp.containsKey("device_no") && mp.get("device_no")!= null && mp.get("device_no")!=""){
                        String sn = mp.get("device_no").toString();
                        FeiEPrinterUtil.printReceipt(sn, content);
                    }else {
                        logger.info("请正确配置打印机");
                        i=2;
                    }
                }
            }

        }
        return toAjaxee(i);
    }
    private  String addSpace(String str, int size) {
        int len = str.length();
        if (len < size) {
            for (int i = 0; i < size - len; i++) {
                str += " ";
            }
        }
        return str;
    }


    /**
     * 修改班结管理
     */

    @Log(title = "班结管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StationClassStructure stationClassStructure)
    {
        return toAjax(stationClassStructureService.updateStationClassStructure(stationClassStructure));
    }

    /**
     * 删除班结管理
     */
    @PreAuthorize("@ss.hasPermi('station:structure:remove')")
    @Log(title = "班结管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(stationClassStructureService.deleteStationClassStructureByIds(ids));
    }

    /**
     * 查询上次班结数据
     */
    @GetMapping("/getAgeClassStructure")
    public AjaxResult getAgeClassStructure(StationClassStructure stationClassStructure)
    {
        //根据当前登陆人获取当前油站id
        LoginUser currentUser = SecurityUtils.getLoginUser();
        stationClassStructure.setStationId(currentUser.getUser().getDeptId());
        return AjaxResult.success(stationClassStructureService.selectStationClassStructureMax(stationClassStructure));
    }
    //初始化数据 根据员工汇总
    @GetMapping("/selectPersonnelStructure")
    public TableDataInfo selectPersonnelStructure(StationClassStructure stationClassStructure)
{
    LoginUser currentUser = SecurityUtils.getLoginUser();
    List<StationClassStructure> list = new ArrayList<>();
    //根据油站查询出上次班结时间，
    stationClassStructure.setStationId(currentUser.getUser().getDeptId());
    StationClassStructure  structure=  stationClassStructureService.selectStationClassStructureMax(stationClassStructure);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    if(structure!=null){
        PayOrder payOrder =new PayOrder();
        payOrder.setStationId(structure.getStationId());
        payOrder.setStatus("1");
        payOrder.setBeginTime(sdf.format(structure.getClassStructureDate()));
        List<PayOrder> payOrderList =  payOrderService.selectPersonnelStructure(payOrder);
        for(PayOrder order:payOrderList){
            StationClassStructure classStructure =new StationClassStructure();
            classStructure.setOilPersonnel(order.getOilPersonnel());
            classStructure.setOilGun(order.getOilGun());
            classStructure.setAmt(order.getAmt());
            classStructure.setOrderLiters(order.getOrderLiters());
            classStructure.setOrderNo(order.getOrderNo());
            list.add(classStructure);
        }
    }else{
        //根据上次班结时间，和油站去订单表中查询数据，并按照人员汇总数据
        PayOrder payOrder =new PayOrder();
        payOrder.setStatus("1");
        payOrder.setStationId(stationClassStructure.getStationId());
        List<PayOrder> payOrderList=  payOrderService.selectPersonnelStructure(payOrder);
        for(PayOrder order:payOrderList){
            StationClassStructure classStructure =new StationClassStructure();
            classStructure.setOilPersonnel(order.getOilPersonnel());
            classStructure.setOilGun(order.getOilGun());
            classStructure.setAmt(order.getAmt());
            classStructure.setOrderLiters(order.getOrderLiters());
            classStructure.setOrderNo(order.getOrderNo());
            list.add(classStructure);
        }
    }

    return getTable(list);
}

    /**
     * 初始化数据班结数据，根据油品汇总
     * @param stationClassStructure
     * @return
     */
    @GetMapping("/selectOilStructure")
    public TableDataInfo selectOilStructure(StationClassStructure stationClassStructure)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //根据油站查询出上次班结时间，
        stationClassStructure.setStationId(currentUser.getUser().getDeptId());
        StationClassStructure  structure=  stationClassStructureService.selectStationClassStructureMax(stationClassStructure);
        List<StationClassStructure> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //根据上次班结时间，和油站去订单表中查询数据，并按照人员汇总数据
        if(structure!=null){
            PayOrder payOrder =new PayOrder();
            payOrder.setStatus("1");
            payOrder.setStationId(structure.getStationId());
            System.out.println("日期："+structure.getClassStructureDate());
            payOrder.setBeginTime(sdf.format(structure.getClassStructureDate()));
            List<PayOrder> payOrderList =  payOrderService.selectOilStructure(payOrder);
            for(PayOrder order:payOrderList){
                StationClassStructure classStructure =new StationClassStructure();
                classStructure.setOilName(order.getOilName());
                classStructure.setOilGun(order.getOilGun());
                classStructure.setAmt(order.getAmt());
                classStructure.setOrderLiters(order.getOrderLiters());
                classStructure.setOrderNo(order.getOrderNo());
                list.add(classStructure);
            }
        }else{
            PayOrder payOrder =new PayOrder();
            payOrder.setStatus("1");
            payOrder.setStationId(stationClassStructure.getStationId());
            List<PayOrder> payOrderList =  payOrderService.selectOilStructure(payOrder);
            for(PayOrder order:payOrderList){
                StationClassStructure classStructure =new StationClassStructure();
                classStructure.setOilName(order.getOilName());
                classStructure.setOilGun(order.getOilGun());
                classStructure.setAmt(order.getAmt());
                classStructure.setOrderLiters(order.getOrderLiters());
                classStructure.setOrderNo(order.getOrderNo());
                list.add(classStructure);
            }
        }

        return getTable(list);
    }
    /**
     * 初始化数据班结数据，根据员工/支付方式汇总
     * @param stationClassStructure
     * @return
     */
    @GetMapping("/selectPersonnelPayStructure")
    public TableDataInfo selectPersonnelPayStructure(StationClassStructure stationClassStructure)
    {
        //根据油站查询出上次班结时间，
        LoginUser currentUser = SecurityUtils.getLoginUser();
        stationClassStructure.setStationId(currentUser.getUser().getDeptId());
        StationClassStructure  structure=  stationClassStructureService.selectStationClassStructureMax(stationClassStructure);
        List<StationClassStructure> list = new ArrayList<>();
        //根据上次班结时间，和油站去订单表中查询数据，并按照人员汇总数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(structure !=null){
            PayOrder payOrder =new PayOrder();
            payOrder.setStationId(structure.getStationId());
            payOrder.setStatus("1");
            System.out.println("日期："+structure.getClassStructureDate());
            payOrder.setBeginTime(sdf.format(structure.getClassStructureDate()));
            List<PayOrder> payOrderList =  payOrderService.selectPersonnelPayStructure(payOrder);
            for(PayOrder order:payOrderList){
                StationClassStructure classStructure =new StationClassStructure();
                classStructure.setOilPersonnel(order.getOilPersonnel());
                classStructure.setOilGun(order.getOilGun());
                classStructure.setWxNum(order.getWxNum());
                classStructure.setZfbNum(order.getZfbNum());
                classStructure.setXjNum(order.getXjNum());
                classStructure.setDiscountAmt(order.getDiscountAmt());
                classStructure.setDiscountCouponAmt(order.getDiscountCouponAmt());
                classStructure.setWxAmt(order.getWxAmt());
                classStructure.setZfbAmt(order.getZfbAmt());
                classStructure.setXjAmt(order.getXjAmt());
                classStructure.setMemberAmt(order.getMemberAmt());
                classStructure.setOrderLiters(order.getOrderLiters());
                classStructure.setOrderNo(order.getOrderNo());
                list.add(classStructure);
            }
        }else{
            PayOrder payOrder =new PayOrder();
            payOrder.setStatus("1");
            payOrder.setStationId(stationClassStructure.getStationId());
            List<PayOrder> payOrderList =  payOrderService.selectPersonnelPayStructure(payOrder);
            for(PayOrder order:payOrderList){
                StationClassStructure classStructure =new StationClassStructure();
                classStructure.setOilPersonnel(order.getOilPersonnel());
                classStructure.setOilGun(order.getOilGun());
                classStructure.setWxNum(order.getWxNum());
                classStructure.setZfbNum(order.getZfbNum());
                classStructure.setXjNum(order.getXjNum());
                classStructure.setDiscountAmt(order.getDiscountAmt());
                classStructure.setDiscountCouponAmt(order.getDiscountCouponAmt());
                classStructure.setWxAmt(order.getWxAmt());
                classStructure.setZfbAmt(order.getZfbAmt());
                classStructure.setXjAmt(order.getXjAmt());
                classStructure.setMemberAmt(order.getMemberAmt());
                classStructure.setOrderLiters(order.getOrderLiters());
                classStructure.setOrderNo(order.getOrderNo());
                list.add(classStructure);
            }
        }
        return getTable(list);
    }


}
