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

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.dto.OrderPayTimeDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.dto.*;
import com.jpsoft.shinestar.modules.business.entity.BillPushGoods;
import com.jpsoft.shinestar.modules.business.service.BillPushGoodsService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.business.entity.BillPush;
import com.jpsoft.shinestar.modules.business.service.BillPushService;
import com.jpsoft.shinestar.modules.common.utils.*;
import com.jpsoft.shinestar.modules.pay.properties.WxPayProperties;
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.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
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.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/business/billPush")
public class BillPushController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private BillPushService billPushService;

    @Autowired
    private BillPushGoodsService billPushGoodsService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CompanyPaymentInfoService companyPaymentInfoService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private GoodsInfoService goodsInfoService;

    @Autowired
    private CompanyGoodInfoService companyGoodInfoService;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private CheckinInfoService checkinInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

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

        BillPushDetailDTO dto = new BillPushDetailDTO();

        User user = userService.get(subject);

        CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.findByCompanyId(user.getCompanyId());

        if(companyPaymentInfo!=null){
            dto.setCollectionAccountId(companyPaymentInfo.getId());
            dto.setCollectionAccountName(companyPaymentInfo.getName());
        }

        dto.setIsOpenWechat(false);
        dto.setIsOpenAlipay(false);
        dto.setBillPushGoodsList(new ArrayList<>());
        dto.setRemoveBillPushGoodsList(new ArrayList<>());

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

        return msgResult;
    }

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<Integer> add(@RequestBody BillPushDetailDTO dto, @RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {

            int affectCount = billPushService.insert(dto,subject);

            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="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<BillPushDetailDTO> edit(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<BillPushDetailDTO> msgResult = new MessageResult<>();

        try {
            BillPush billPush = billPushService.get(id);

            if (billPush != null) {
                User user = userService.get(subject);

                CompanyInfo tempCompany = companyInfoService.get(user.getCompanyId());

                BillPushDetailDTO billPushDetailDTO = new BillPushDetailDTO();
                billPushDetailDTO.setId(billPush.getId());
                billPushDetailDTO.setName(billPush.getName());
                billPushDetailDTO.setPayee(billPush.getPayee());
                billPushDetailDTO.setCollectionAccountId(Long.parseLong(billPush.getCollectionAccountId()));
                billPushDetailDTO.setCompanyId(billPush.getCompanyId());
                billPushDetailDTO.setCheckinInfoId(billPush.getCheckinInfoId());
                billPushDetailDTO.setIsMobilePayment(tempCompany.getIsMobilePayment());
                CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.parseLong(billPush.getCollectionAccountId()));
                billPushDetailDTO.setCollectionAccountName(companyPaymentInfo.getName());
                billPushDetailDTO.setPersonId(billPush.getPersonId());
                PersonInfo personInfo = personInfoService.get(billPush.getPersonId());
                billPushDetailDTO.setPersonName(personInfo.getName());
                billPushDetailDTO.setBak(billPush.getBak());
                billPushDetailDTO.setIsOpenWechat(billPush.getIsOpenWechat());
                billPushDetailDTO.setIsOpenAlipay(billPush.getIsOpenAlipay());
                billPushDetailDTO.setInvoiceType(billPush.getInvoiceType());
                billPushDetailDTO.setInvoiced(billPush.getInvoiced());

                List<BillPushGoods> list = billPushGoodsService.findByBillPushId(billPush.getId());

                CheckinInfo checkinInfo = checkinInfoService.get(billPush.getCheckinInfoId());

                List<BillPushGoodsDTO> billPushGoodsDTOList = new ArrayList<>();

                for (BillPushGoods billPushGoods:list) {
                    BillPushGoodsDTO billPushGoodsDTO = new BillPushGoodsDTO();
                    billPushGoodsDTO.setId(billPushGoods.getId());

                    if(checkinInfo!=null){
                        CompanyGoodInfo companyGoodInfo = companyGoodInfoService.findByCompanyIdAndGoodsId(checkinInfo.getId(),billPushGoods.getGoodsId());
                        if(companyGoodInfo!=null){
                            GoodsInfo goodsInfo = goodsInfoService.get(billPushGoods.getGoodsId());

                            if(companyGoodInfo.getUnitPrice()!=null) {
                                //租户对商户商品有自定义价格
                                billPushGoodsDTO.setUnitPrice(companyGoodInfo.getUnitPrice());
                            }
                            else{
                                //每个商户设置一组商品
                                billPushGoodsDTO.setUnitPrice(goodsInfo.getUnitPrice());
                            }

                            billPushGoodsDTO.setUnit(goodsInfo.getUnit());
                            billPushGoodsDTO.setGoodsId(companyGoodInfo.getId());
                            billPushGoodsDTO.setGoodTypeId(goodsInfo.getType());
                        }
                    }


                    String beginEndTime = billPushGoods.getBeginEndTime();

                    if(StringUtils.isNotEmpty(beginEndTime)){
                        String[] beginEndTimeArray = beginEndTime.split(",");

                        billPushGoodsDTO.setBeginDate(beginEndTimeArray[0]);
                        billPushGoodsDTO.setEndDate(beginEndTimeArray[1]);
                    }

                    if(StringUtils.isNotEmpty(billPushGoods.getNumStr())){
                        JSONObject jsonObject = JSONObject.fromObject(billPushGoods.getNumStr());
                        if (jsonObject!=null) {
                            if (jsonObject.get("start") != null) {
                                String start = jsonObject.getString("start");
                                billPushGoodsDTO.setNumStr(start);
                            }
                            if (jsonObject.get("end") != null) {
                                String end = jsonObject.getString("end");
                                billPushGoodsDTO.setNumStr2(end);

                            }
                            if (jsonObject.get("total") != null) {
                                String total = jsonObject.getString("total");
                                billPushGoodsDTO.setNumStr3(total);
                            }
                        }
                    }

                    //billPushGoodsDTO.setNumStr(billPushGoods.getNumStr());

                    if(StringUtils.isNotEmpty(billPushGoods.getDetails())){
                        JSONObject jsonObject = JSONObject.fromObject(billPushGoods.getDetails());
                        if (jsonObject!=null) {
                            if (jsonObject.get("standard") != null) {
                                String standard = jsonObject.getString("standard");
                                billPushGoodsDTO.setStandard(standard);
                            }

                            if (jsonObject.get("totalFee") != null) {
                                String totalFeeStr = jsonObject.getString("totalFee");
                                if (StringUtils.isNotEmpty(totalFeeStr)) {
                                    BigDecimal totalFee = new BigDecimal(totalFeeStr);
                                    billPushGoodsDTO.setTotalFee(totalFee);
                                }
                            }

                            if (jsonObject.get("unitPrice") != null) {
                                String unitPriceStr = jsonObject.getString("unitPrice");
                                BigDecimal unitPrice = new BigDecimal(unitPriceStr);
                                billPushGoodsDTO.setUnitPrice(unitPrice);
                            }
                        }
                    }

                    billPushGoodsDTOList.add(billPushGoodsDTO);
                }


                billPushDetailDTO.setBillPushGoodsList(billPushGoodsDTOList);
                billPushDetailDTO.setRemoveBillPushGoodsList(new ArrayList<>());

                msgResult.setResult(true);
                msgResult.setData(billPushDetailDTO);
            } 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("detail/{id}")
    public MessageResult<BillPushDetailListDTO> detail(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<BillPushDetailListDTO> msgResult = new MessageResult<>();

        try {

            BillPush billPush = billPushService.get(id);

            if (billPush != null) {
                User user = userService.get(subject);

                CompanyInfo tempCompany = companyInfoService.get(user.getCompanyId());

                BillPushDetailListDTO billPushDetailListDTO = new BillPushDetailListDTO();
                billPushDetailListDTO.setName(billPush.getName());
                billPushDetailListDTO.setPayee(billPush.getPayee());
                billPushDetailListDTO.setIsMobilePayment(tempCompany.getIsMobilePayment());
                if(StringUtils.isNotEmpty(billPush.getCollectionAccountId())) {
                    CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.parseLong(billPush.getCollectionAccountId()));
                    billPushDetailListDTO.setCollectionAccount(companyPaymentInfo.getName());
                }
                if(StringUtils.isNotEmpty(billPush.getCompanyId())) {
                    CompanyInfo companyInfo = companyInfoService.get(billPush.getCompanyId());
                    billPushDetailListDTO.setCompanyName(companyInfo.getName());

                }
                if(billPush.getPersonId()!=null){
                    PersonInfo personInfo = personInfoService.get(billPush.getPersonId());
                    billPushDetailListDTO.setPersonName(personInfo.getName());
                }
                billPushDetailListDTO.setStatus(billPush.getStatus());
                billPushDetailListDTO.setPushTime(billPush.getPushTime());
                if(StringUtils.isNotEmpty(billPush.getOrderId())){
                    OrderInfo order = orderInfoService.get(billPush.getOrderId());

                    if (StringUtils.isNotEmpty(order.getPayName())) {
                        if ("wechat".equals(order.getPayName())) {
                            billPushDetailListDTO.setPayName("微信");
                        } else if ("alipay".equals(order.getPayName())) {
                            billPushDetailListDTO.setPayName("支付宝");
                        }
                        else if ("cash".equals(order.getPayName())) {
                            billPushDetailListDTO.setPayName("现金支付");
                        }
                        else if ("transfer".equals(order.getPayName())) {
                            billPushDetailListDTO.setPayName("对公转账");
                        }
                        else if ("individual".equals(order.getPayName())) {
                            billPushDetailListDTO.setPayName("个人账户");
                        }
                    }
                    else {
                        billPushDetailListDTO.setPayName("线下支付");
                    }

                    billPushDetailListDTO.setPayTime(order.getPayTime());
                    billPushDetailListDTO.setPayStatus(order.getPayStatus());
                }
                billPushDetailListDTO.setBak(billPush.getBak());
                billPushDetailListDTO.setIsOpenWechat(billPush.getIsOpenWechat());
                billPushDetailListDTO.setIsOpenAlipay(billPush.getIsOpenAlipay());
                billPushDetailListDTO.setInvoiceType(billPush.getInvoiceType());
                billPushDetailListDTO.setInvoiced(billPush.getInvoiced());

                if(StringUtils.isNotEmpty(billPush.getInvoiceType())){
                    List<DataDictionary> dictionaryList = dataDictionaryService.findByCatalogName("开票类型");

                    for (DataDictionary item:dictionaryList) {
                        if(item.getValue().equals(billPush.getInvoiceType())){
                            billPushDetailListDTO.setInvoiceTypeN(item.getName());
                        }
                    }
                }
                billPushDetailListDTO.setOrderId(billPush.getOrderId());

                msgResult.setResult(true);
                msgResult.setData(billPushDetailListDTO);
            } 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<BillPush> update(@RequestBody BillPushDetailDTO dto,@RequestAttribute String subject){
        MessageResult<BillPush> msgResult = new MessageResult<>();

        try {
            BillPush billPush = billPushService.get(dto.getId());

            billPush.setName(dto.getName());

            String checkinInfoId = dto.getCheckinInfoId();
            CheckinInfo checkinInfo = checkinInfoService.get(checkinInfoId);

            if(checkinInfo!=null){
                billPush.setCompanyId(checkinInfo.getCompanyId());
            }

            billPush.setPersonId(dto.getPersonId());
            billPush.setCollectionAccountId(dto.getCollectionAccountId().toString());
            billPush.setPayee(dto.getPayee());
            billPush.setBak(dto.getBak());
            billPush.setUpdateBy(subject);
            billPush.setUpdateTime(new Date());
            billPush.setIsOpenWechat(dto.getIsOpenWechat());
            billPush.setIsOpenAlipay(dto.getIsOpenAlipay());
            billPush.setInvoiceType(dto.getInvoiceType());

            int affectCount = billPushService.update(billPush);

            int orderCount = 0;

            if (affectCount > 0) {
                //需要更新的数据列表
                List<BillPushGoodsDTO> billPushGoodsDTOList = dto.getBillPushGoodsList();

                int bodyNum = 0;

                if(billPushGoodsDTOList!=null) {

                    String goodsId = "";
                    String body = "";
                    BigDecimal totalFee = BigDecimal.ZERO;

                    for (BillPushGoodsDTO billPushGoodsDTO : billPushGoodsDTOList) {
                        BillPushGoods billPushGoods = new BillPushGoods();
                        CompanyGoodInfo companyGoodInfo = null;

                        if(StringUtils.isNotEmpty(billPushGoodsDTO.getId())) {
                            billPushGoods = billPushGoodsService.get(billPushGoodsDTO.getId());
                            billPushGoods.setSortNo(billPushGoodsDTO.getSortNo());

                            String companyGoodsId = billPushGoodsDTO.getGoodsId();

                            companyGoodInfo = companyGoodInfoService.get(companyGoodsId);

                            billPushGoods.setGoodsId(companyGoodInfo.getGoodsId());

                            billPushGoods.setBeginEndTime(billPushGoodsDTO.getBeginDate()+","+billPushGoodsDTO.getEndDate());

                            billPushGoods.setNumStr(billPushGoodsDTO.getNumStr());

                            GoodsInfo goodsInfo = goodsInfoService.get(companyGoodInfo.getGoodsId());
                            if(goodsInfo!=null){
                                JSONObject jsonObject = new JSONObject();

                                String start = "";
                                String end = "";
                                String total = "";
                                if(goodsInfo.getType().equals("7")){
                                    start = billPushGoodsDTO.getNumStr();
                                    end = billPushGoodsDTO.getNumStr2();
                                    total = billPushGoodsDTO.getNumStr3();
                                }
                                else{
                                    total = billPushGoodsDTO.getNumStr3();
                                }
                                jsonObject.put("start",start);
                                jsonObject.put("end",end);
                                jsonObject.put("total",total);
                                billPushGoods.setNumStr(jsonObject.toString());
                            }

                            BigDecimal feeDecimal = billPushGoodsDTO.getTotalFee();
                            String standard = billPushGoodsDTO.getStandard();

                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("standard",standard);
                            jsonObject.put("unitPrice", billPushGoodsDTO.getUnitPrice());
                            jsonObject.put("totalFee",feeDecimal);

                            billPushGoods.setDetails(jsonObject.toString());

                            billPushGoods.setUpdateBy(subject);
                            billPushGoods.setUpdateTime(new Date());

                            billPushGoodsService.update(billPushGoods);
                        }
                        else{
                            billPushGoods.setBillPushId(billPush.getId());
                            billPushGoods.setId(UUID.randomUUID().toString());
                            billPushGoods.setBeginEndTime(billPushGoodsDTO.getBeginDate()+","+billPushGoodsDTO.getEndDate());
                            billPushGoods.setSortNo(billPushGoodsDTO.getSortNo());

                            String companyGoodsId = billPushGoodsDTO.getGoodsId();

                            companyGoodInfo = companyGoodInfoService.get(companyGoodsId);

                            billPushGoods.setGoodsId(companyGoodInfo.getGoodsId());

                            GoodsInfo goodsInfo = goodsInfoService.get(companyGoodInfo.getGoodsId());
                            if(goodsInfo!=null){
                                JSONObject jsonObject = new JSONObject();

                                String start = "";
                                String end = "";
                                String total = "";
                                if(goodsInfo.getType().equals("7")){
                                    start = billPushGoodsDTO.getNumStr();
                                    end = billPushGoodsDTO.getNumStr2();
                                    total = billPushGoodsDTO.getNumStr3();
                                }
                                else{
                                    total = billPushGoodsDTO.getNumStr3();
                                }
                                jsonObject.put("start",start);
                                jsonObject.put("end",end);
                                jsonObject.put("total",total);
                                billPushGoods.setNumStr(jsonObject.toString());
                            }

                            BigDecimal feeDecimal = billPushGoodsDTO.getTotalFee();
                            String standard = billPushGoodsDTO.getStandard();
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("standard",standard);
                            jsonObject.put("unitPrice", billPushGoodsDTO.getUnitPrice());
                            jsonObject.put("totalFee",feeDecimal);

                            billPushGoods.setDetails(jsonObject.toString());

                            billPushGoods.setDelFlag(false);
                            billPushGoods.setCreateBy(subject);
                            billPushGoods.setCreateTime(new Date());

                            billPushGoodsService.insert(billPushGoods);
                        }

                        //将本次收款单单价保存到租户对应收费项中
                        companyGoodInfo.setUnitPrice(billPushGoodsDTO.getUnitPrice());
                        companyGoodInfo.setUpdateTime(new Date());
                        companyGoodInfo.setUpdateBy(subject);
                        companyGoodInfoService.update(companyGoodInfo);
                    }
                }

                //已被删除的数据列表,更新删除状态
                List<BillPushGoodsDTO> removeBillPushGoodsList = dto.getRemoveBillPushGoodsList();

                if(removeBillPushGoodsList!=null) {
                    for (BillPushGoodsDTO billPushGoodsDTO : removeBillPushGoodsList) {
                        if(StringUtils.isNotEmpty(billPushGoodsDTO.getId())) {
                            BillPushGoods billPushGoods = billPushGoodsService.get(billPushGoodsDTO.getId());

                            billPushGoods.setUpdateBy(subject);
                            billPushGoods.setUpdateTime(new Date());
                            billPushGoods.setDelFlag(true);

                            billPushGoodsService.update(billPushGoods);
                        }
                    }
                }

                String goodsId = "";
                String body = "";
                BigDecimal totalFee = BigDecimal.ZERO;

                List<BillPushGoods> billPushGoodsList = billPushGoodsService.findByBillPushId(dto.getId());

                for (BillPushGoods billPushGoods:billPushGoodsList) {
                    GoodsInfo goodsInfo = goodsInfoService.get(billPushGoods.getGoodsId());
                    if(goodsInfo!=null){
                        goodsId += goodsInfo.getId()+",";
                        body += goodsInfo.getName()+",";
                        bodyNum++;
                    }

                    if(StringUtils.isNotEmpty(billPushGoods.getDetails())) {
                        JSONObject jsonObject = JSONObject.fromObject(billPushGoods.getDetails());
                        if (jsonObject!=null) {
                            if (jsonObject.get("totalFee") != null) {
                                String totalFeeStr = jsonObject.getString("totalFee");
                                if (StringUtils.isNotEmpty(totalFeeStr)) {
                                    BigDecimal fee = BigDecimal.valueOf(Double.parseDouble(totalFeeStr));
                                    totalFee = totalFee.add(fee);
                                }
                            }
                        }
                    }
                }

                OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());
                if(StringUtils.isNotEmpty(body)){
                    body = body.substring(0,body.lastIndexOf(","));
                    orderInfo.setBody(body);
                }

                if(StringUtils.isNotEmpty(goodsId)){
                    goodsId = goodsId.substring(0,goodsId.lastIndexOf(","));
                    orderInfo.setGoodsId(goodsId);
                }

                orderInfo.setTotalFee(totalFee);

                if(bodyNum>1){
                    //多于一个为综合
                    orderInfo.setType("10");
                }
                else{
                    GoodsInfo temp = goodsInfoService.get(goodsId);
                    if(temp!=null){
                        orderInfo.setType(temp.getType());
                    }
                }
                orderCount = orderInfoService.update(orderInfo);

                if(orderCount>0) {
                    msgResult.setResult(true);
                    msgResult.setData(billPushService.get(billPush.getId()));
                }
                else {
                    msgResult.setResult(false);
                    msgResult.setMessage("数据库更新失败");
                }
            } 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<BillPush> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<BillPush> msgResult = new MessageResult<>();

        try {
            BillPush billPush = billPushService.get(id);

            OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());

            int affectCount = 0;

            if(orderInfo == null){
                throw new Exception("订单不存在！");
            }

            if(orderInfo.getPayStatus()==10){
                orderInfo.setDelFlag(true);
                orderInfo.setUpdateBy(subject);
                orderInfo.setUpdateTime(new Date());
                int count = orderInfoService.update(orderInfo);

                if(count>0) {
                    billPush.setDelFlag(true);
                    billPush.setUpdateBy(subject);
                    billPush.setUpdateTime(new Date());

                    affectCount = billPushService.update(billPush);
                }
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
            } 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("closeBill/{id}")
    public MessageResult<BillPush> closeBill(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<BillPush> msgResult = new MessageResult<>();

        try {
            BillPush billPush = billPushService.get(id);
            billPush.setStatus("3");
            billPush.setUpdateBy(subject);

            OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());

            int affectCount = 0;

            if(orderInfo == null){
                throw new Exception("订单不存在！");
            }

            if(orderInfo.getPayStatus()==10){
                orderInfo.setPayStatus(30);
                int count = orderInfoService.update(orderInfo);

                if(count>0) {
                    billPush.setUpdateTime(new Date());
                    affectCount = billPushService.update(billPush);
                }
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
            } 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/{id}")
    public MessageResult<BillPush> batchDelete(@PathVariable("id") String id){
        MessageResult<BillPush> msgResult = new MessageResult<>();

        msgResult.setResult(false);
        msgResult.setMessage("未实现");

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String name,
            String companyId,String status,String payStatus,String payName,String invoiced,
            String collectionAccount,String pushTimeRange,String payTimeRange,
            @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("a.create_time","desc"));

        User user = userService.get(subject);

        CompanyInfo tempCompany = companyInfoService.get(user.getCompanyId());


        if(StringUtils.isNotEmpty(companyId)){
            searchParams.put("companyId",companyId);
        }
        else{
            List<CompanyPaymentInfo> companyPaymentInfoList = companyPaymentInfoService.findListByCompanyId(user.getCompanyId());
            searchParams.put("companyPaymentInfoList",companyPaymentInfoList);
        }

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

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

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

        if(invoiced!=null){
            searchParams.put("invoiced", Boolean.valueOf(invoiced));
        }

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



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

            searchParams.put("beginPushTime", beginPushTime);
            searchParams.put("endPushTime", endPushTime);
        }

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

            searchParams.put("beginPayTime", beginPayTime);
            searchParams.put("endPayTime", endPayTime);
        }

        Page<BillPush> page = billPushService.pageSearch(searchParams,pageIndex,pageSize,sortList);

        Page<BillPushDTO> pageDto = new Page<>();

        for (BillPush billPush:page) {
            BillPushDTO billPushDTO = new BillPushDTO();
            billPushDTO.setId(billPush.getId());
            billPushDTO.setName(billPush.getName());
            billPushDTO.setIsMobilePayment(tempCompany.getIsMobilePayment());
            CompanyInfo companyInfo = companyInfoService.get(billPush.getCompanyId());
            if(companyInfo!=null) {
                billPushDTO.setCompanyName(companyInfo.getName());
            }
            PersonInfo personInfo = personInfoService.get(billPush.getPersonId());
            if(personInfo!=null){
                billPushDTO.setPersonName(personInfo.getName());
                billPushDTO.setPhone(personInfo.getPhone());
            }

            if(StringUtils.isNotEmpty(billPush.getCollectionAccountId())){
                CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.parseLong(billPush.getCollectionAccountId()));
                if(companyPaymentInfo!=null) {
                    billPushDTO.setCollectionAccount(companyPaymentInfo.getName());
                }
            }

            OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());

            if(orderInfo!=null) {
                billPushDTO.setTotalFee(orderInfo.getTotalFee());
                billPushDTO.setPayStatus(orderInfo.getPayStatus());
                billPushDTO.setPayTime(orderInfo.getPayTime());

                if (StringUtils.isNotEmpty(orderInfo.getPayName())) {
                    if ("wechat".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("微信");
                    } else if ("alipay".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("支付宝");
                    }
                    else if ("cash".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("现金支付");
                    }
                    else if ("transfer".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("对公转账");
                    }
                    else if ("individual".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("个人账户");
                    }
                    else {
                        billPushDTO.setPayName("线下支付");
                    }
                }
            }

            billPushDTO.setStatus(billPush.getStatus());
            billPushDTO.setPushTime(billPush.getPushTime());
            billPushDTO.setPayee(billPush.getPayee());
            billPushDTO.setIsOpenWechat(billPush.getIsOpenWechat());
            billPushDTO.setIsOpenAlipay(billPush.getIsOpenAlipay());
            billPushDTO.setInvoiceType(billPush.getInvoiceType());
            billPushDTO.setInvoiced(billPush.getInvoiced());

            pageDto.add(billPushDTO);
        }

        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 = "goodsPageList",method = RequestMethod.POST)
    public MessageResult<Object> goodsPageList(
            String billPushId,
            @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("sort_no","asc"));

            BillPush billPush = billPushService.get(billPushId);

            searchParams.put("billPushId",billPushId);

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

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


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

                map.put("id", billPushGoods.getId());

                if(StringUtils.isNotEmpty(billPushGoods.getGoodsId())) {
                    GoodsInfo goodsInfo = goodsInfoService.get(billPushGoods.getGoodsId());
                    map.put("goodsName", goodsInfo.getName());
                }
                String beginEndStr = billPushGoods.getBeginEndTime();
                String begin = "";
                String end = "";
                if(StringUtils.isNotEmpty(beginEndStr)){
                    String[] beginEndArray = beginEndStr.split(",");
                    begin = beginEndArray[0];
                    end = beginEndArray[1];
                }

                map.put("beginEndTime", begin + "至" + end);

                if(StringUtils.isNotEmpty(billPushGoods.getDetails())) {
                    JSONObject jsonObject = JSONObject.fromObject(billPushGoods.getDetails());
                    if (jsonObject!=null) {
                        if (jsonObject.get("standard") != null) {
                            String standard = jsonObject.getString("standard");

                            map.put("standard", standard);
                        }
                        if (jsonObject.get("totalFee") != null) {
                            String totalFeeStr = jsonObject.getString("totalFee");
                            if (StringUtils.isNotEmpty(totalFeeStr)) {
                                BigDecimal totalFee = BigDecimal.valueOf(Double.parseDouble(totalFeeStr));
                                map.put("totalFee", totalFee);
                            }
                        }
                    }
                }

                String num = "";
                String start="";
                String endStr="";
                String total="";

                if(StringUtils.isNotEmpty(billPushGoods.getNumStr())){
                    String numStr = billPushGoods.getNumStr();
                    JSONObject jsonObject = JSONObject.fromObject(numStr);
                    if (jsonObject!=null) {
                        if (jsonObject.get("start") != null) {
                            start = jsonObject.getString("start");
                        }
                        if (jsonObject.get("end") != null) {
                            endStr = jsonObject.getString("end");
                        }
                        if (jsonObject.get("total") != null) {
                            total = jsonObject.getString("total");
                        }
                    }
                }

                if(start.equals("")&&endStr.equals("")){
                    map.put("num", total);
                }
                else{
                    map.put("num", "起码："+start+"，止码："+endStr+"，结算度数："+total+"度");
                }

                mapList.add(map);
            }


            if(exportFlag) {
                String filePath = exportXls(mapList,billPush);
                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,BillPush billPush) throws IOException {
        String downloadUrl = "";

        ClassPathResource resource = new ClassPathResource("static/billPushGoods.xls");

        Workbook wb = WorkbookFactory.create(resource.getInputStream());

        Sheet sheet = wb.getSheetAt(0);

        CompanyInfo companyInfo = companyInfoService.get(billPush.getCompanyId());

        CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.parseLong(billPush.getCollectionAccountId()));

        //单位名称
        Row headerRow1 = sheet.getRow(1);
        Cell cellHead = headerRow1.getCell(0);
        cellHead.setCellValue(companyInfo.getFullName() + "：");

        //开头
        Row headerRow2 = sheet.getRow(2);
        String cycle = headerRow2.getCell(0).getStringCellValue();
        headerRow2.getCell(0).setCellValue(String.format(cycle, companyPaymentInfo.getCycle()));

        BigDecimal total = BigDecimal.ZERO;

        Font normalFont = wb.createFont();
        normalFont.setFontHeightInPoints((short) 12);

        CellStyle textWithBorderStyle = wb.createCellStyle();
        textWithBorderStyle.setBorderBottom(BorderStyle.THIN);
        textWithBorderStyle.setBorderLeft(BorderStyle.THIN);
        textWithBorderStyle.setBorderRight(BorderStyle.THIN);
        textWithBorderStyle.setBorderTop(BorderStyle.THIN);
        textWithBorderStyle.setFont(normalFont);
        textWithBorderStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        textWithBorderStyle.setWrapText(true);

        CellStyle textStyle = wb.createCellStyle();
        textStyle.setFont(normalFont);

        //金额样式
        CellStyle decimalStyle = wb.createCellStyle();
        decimalStyle.setBorderBottom(BorderStyle.THIN);
        decimalStyle.setBorderLeft(BorderStyle.THIN);
        decimalStyle.setBorderRight(BorderStyle.THIN);
        decimalStyle.setBorderTop(BorderStyle.THIN);
        decimalStyle.setFont(normalFont);
        decimalStyle.setAlignment(HorizontalAlignment.CENTER);
        decimalStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));

        DecimalFormat df = new DecimalFormat("#.##");

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

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

            int colIndex = 0;

            String goodsNameStr = map.get("goodsName").toString()+"("+map.get("beginEndTime").toString()+")";

            Cell cell1 = row.createCell(colIndex++);
            cell1.setCellStyle(textWithBorderStyle);
            Cell cell2 = row.createCell(colIndex++);
            cell2.setCellStyle(textWithBorderStyle);
            Cell cell3 = row.createCell(colIndex++);
            cell3.setCellStyle(textWithBorderStyle);
            Cell cell4 = row.createCell(colIndex++);
            cell4.setCellStyle(decimalStyle);

            cell1.setCellValue(StringUtils.strValue(goodsNameStr,""));
            cell2.setCellValue(StringUtils.strValue(map.get("num"),""));
            cell3.setCellValue(StringUtils.strValue(map.get("standard"),""));

            if(map.get("totalFee")!=null){
                BigDecimal totalFee = new BigDecimal(map.get("totalFee").toString());

                cell4.setCellValue(totalFee.doubleValue());
                total = total.add(totalFee);
            }
        }

        Row row = sheet.createRow(4 + mapList.size());

        Cell cellTotalStr = row.createCell(0);
        cellTotalStr.setCellStyle(textWithBorderStyle);
        Cell cellTotalStr2 = row.createCell(1);
        cellTotalStr2.setCellStyle(textWithBorderStyle);
        Cell cellTotalStr3 = row.createCell(2);
        cellTotalStr3.setCellStyle(textWithBorderStyle);
        Cell cellTotal = row.createCell(3);
        cellTotal.setCellStyle(decimalStyle);

        cellTotalStr.setCellValue(StringUtils.strValue("合计：",""));
//        cellTotalStr2.setCellValue(StringUtils.strValue("",""));
//        cellTotalStr3.setCellValue(StringUtils.strValue("",""));
        cellTotal.setCellValue(total.doubleValue());

        Row footerRow0 = sheet.createRow(6 + mapList.size());
        footerRow0.createCell(2).setCellStyle(textStyle);
        footerRow0.getCell(2).setCellValue(StringUtils.strValue(companyPaymentInfo.getName(),""));

        Row footerRow1 = sheet.createRow(7 + mapList.size());
        footerRow1.createCell(0).setCellStyle(textStyle);
        footerRow1.getCell(0).setCellValue(StringUtils.strValue("总经理审核：",""));

        String realName = "";
        User user = userService.get(billPush.getCreateBy());

        if (user!=null){
            realName = user.getRealName();
        }

        footerRow1.createCell(2).setCellStyle(textStyle);
        footerRow1.getCell(2).setCellValue(StringUtils.strValue("经办人：" + realName,""));

        Row footerRow2 = sheet.createRow(8 + mapList.size());

        if (billPush.getPushTime()!=null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

            footerRow2.createCell(2).setCellStyle(textStyle);
            footerRow2.getCell(2).setCellValue(sdf.format(billPush.getPushTime()));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            wb.write(output);

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

            String fileName = companyInfo.getName().trim() + "-" + billPush.getName().trim() + ".xls";
            downloadUrl = OSSUtil.upload(ossConfig,"billPushGoods", fileName,input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }

    @ApiOperation(value="推送账单")
    @PostMapping("pushBill")
    public MessageResult<Integer> pushBill(String id,@RequestAttribute String subject) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {

            BillPush billPush = billPushService.get(id);

            if(billPush==null){
                throw new Exception("订单不存在！");
            }

            CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.parseLong(billPush.getCollectionAccountId()));

            if(companyPaymentInfo==null){
                throw new Exception("物业账户不存在！");
            }

            String cycle = companyPaymentInfo.getCycle();

            PersonInfo personInfo = personInfoService.get(billPush.getPersonId());

            if(personInfo == null) {
                throw new Exception("人员不存在！");
        }

            OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());

            if(orderInfo == null){
                throw new Exception("订单不存在！");
            }

            if(orderInfo.getPayStatus()!=10){
                throw new Exception("订单不是未支付状态！");
            }


            orderInfo.setPersonId(personInfo.getId());
            orderInfo.setUpdateBy(subject);
            orderInfo.setUpdateTime(new Date());
            orderInfoService.update(orderInfo);


            //异步模板消息发送
            new Thread(() -> {
                if (personInfo.getWechatNoticeEnabled()) {

                    String perosnToken = JwtUtil2.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(24*30).toDate());

                    boolean result = WechatMessageUtil.sendPayBill(personInfo.getOpenId(), personInfo.getName()+"您好：您有一笔新的账单需要支付，点击查看账单详情。",orderInfo.getBody(),String.valueOf(orderInfo.getTotalFee()),cycle+"天以内",billPush.getBak(),wxConfig.getPortalUrl() + "master/mine/bill/pay?id=" + orderInfo.getId() + "&exchange=1&role_id=" + personInfo.getPopedom() + "&token=" + perosnToken,wxPayProperties.getAppId(), wxPayProperties.getAppSecret());

                    String status = "";

                    if(result){
                        status = "1";
                    }
                    else{
                        status = "2";
                    }

                    billPush.setStatus(status);
                    billPush.setPushTime(new Date());
                    billPushService.update(billPush);
                }

                try{
                    companyPaymentInfoService.createDelayedNotPayBill(billPush);
                }catch (Exception ex){
                    logger.error(ex.getMessage(),ex);
                }

            }).start();

            msgResult.setResult(true);

        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;

    }


    @ApiOperation(value="更新订单")
    @PostMapping("updateOrder")
    public MessageResult<BillPush> updateOrder(@RequestBody OrderPayTimeDTO dto,@RequestAttribute String subject) {
        MessageResult<BillPush> msgResult = new MessageResult<>();

        try {
            BillPush billPush = billPushService.get(dto.getId());

            OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());

            if(orderInfo == null){
                throw new Exception("订单不存在！");
            }

            if(orderInfo.getPayStatus() != 10){
                throw new Exception("订单状态异常！");
            }

            orderInfo.setPayStatus(20);
            orderInfo.setPayName(dto.getPayName());
            orderInfo.setPayTime(DateUtil.parse(dto.getPayTime(),"yyyy-MM-dd HH:mm:ss"));
            orderInfo.setPayFee(orderInfo.getTotalFee());

            orderInfo.setUpdateBy(subject);
            orderInfo.setUpdateTime(new Date());
            int affectCount = orderInfoService.update(orderInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
            } 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("createPayTime/{id}")
    public MessageResult<OrderPayTimeDTO> createPayTime(@PathVariable("id") String id){
        MessageResult<OrderPayTimeDTO> msgResult = new MessageResult<>();

        BillPush billPush = billPushService.get(id);

        OrderPayTimeDTO dto = new OrderPayTimeDTO();
        dto.setId(billPush.getId());

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

        return msgResult;
    }

    @ApiOperation(value="修改")
    @GetMapping("editPayTime/{id}")
    public MessageResult<OrderPayTimeDTO> editPayTime(@PathVariable("id") String id){
        MessageResult<OrderPayTimeDTO> msgResult = new MessageResult<>();

        try {
            BillPush billPush = billPushService.get(id);

            OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());

            if(orderInfo == null){
                throw new Exception("订单不存在！");
            }

            OrderPayTimeDTO dto = new OrderPayTimeDTO();
            dto.setId(billPush.getId());
            dto.setPayName(orderInfo.getPayName());
            dto.setPayTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));

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

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

        return msgResult;
    }


    @ApiOperation(value="修改是否支持微信、支付宝支付、是否开票")
    @PostMapping("updateIsOpenWechatOrAlipay")
    public MessageResult<Integer> updateIsOpenWechatOrAlipay(String id,Boolean isOpen,String type, @RequestAttribute String subject) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            BillPush billPush = billPushService.get(id);

            if(billPush!=null){
                if("0".equals(type)){
                    billPush.setIsOpenWechat(isOpen);
                }
                else if("1".equals(type)){
                    billPush.setIsOpenAlipay(isOpen);
                }
                else if("2".equals(type)){
                    billPush.setInvoiced(isOpen);
                }

                billPush.setUpdateBy(subject);
                billPush.setUpdateTime(new Date());

                int count = billPushService.update(billPush);

                msgResult.setResult(true);
                msgResult.setData(count);
            }
            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 = "checkInBillpageList",method = RequestMethod.POST)
    public MessageResult<Map> checkInBillpageList(
            String name, String status,String payStatus,String payName,
            String collectionAccount,String pushTimeRange,String payTimeRange,
            @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("a.create_time","desc"));

        User user = userService.get(subject);

        searchParams.put("companyId",user.getCompanyId());


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

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

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

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



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

            searchParams.put("beginPushTime", beginPushTime);
            searchParams.put("endPushTime", endPushTime);
        }

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

            searchParams.put("beginPayTime", beginPayTime);
            searchParams.put("endPayTime", endPayTime);
        }

        Page<BillPush> page = billPushService.pageSearch(searchParams,pageIndex,pageSize,sortList);

        Page<BillPushDTO> pageDto = new Page<>();

        for (BillPush billPush:page) {
            BillPushDTO billPushDTO = new BillPushDTO();
            billPushDTO.setId(billPush.getId());
            billPushDTO.setName(billPush.getName());
            CompanyInfo companyInfo = companyInfoService.get(billPush.getCompanyId());
            if(companyInfo!=null) {
                billPushDTO.setCompanyName(companyInfo.getName());
            }
            PersonInfo personInfo = personInfoService.get(billPush.getPersonId());
            if(personInfo!=null){
                billPushDTO.setPersonName(personInfo.getName());
                billPushDTO.setPhone(personInfo.getPhone());
            }

            if(StringUtils.isNotEmpty(billPush.getCollectionAccountId())){
                CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.parseLong(billPush.getCollectionAccountId()));
                if(companyPaymentInfo!=null) {
                    billPushDTO.setCollectionAccount(companyPaymentInfo.getName());
                }
            }

            OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());

            if(orderInfo!=null) {
                billPushDTO.setTotalFee(orderInfo.getTotalFee());
                billPushDTO.setPayStatus(orderInfo.getPayStatus());
                billPushDTO.setPayTime(orderInfo.getPayTime());

                if (StringUtils.isNotEmpty(orderInfo.getPayName())) {
                    if ("wechat".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("微信");
                    } else if ("alipay".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("支付宝");
                    }
                    else if ("cash".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("现金支付");
                    }
                    else if ("transfer".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("对公转账");
                    }
                    else if ("individual".equals(orderInfo.getPayName())) {
                        billPushDTO.setPayName("个人账户");
                    }
                    else {
                        billPushDTO.setPayName("线下支付");
                    }
                }
            }
            billPushDTO.setStatus(billPush.getStatus());
            billPushDTO.setPushTime(billPush.getPushTime());
            billPushDTO.setPayee(billPush.getPayee());
            billPushDTO.setIsOpenWechat(billPush.getIsOpenWechat());
            billPushDTO.setIsOpenAlipay(billPush.getIsOpenAlipay());

            pageDto.add(billPushDTO);
        }

        pageDto.setPageSize(page.getPageSize());
        pageDto.setTotal(page.getTotal());
        pageDto.setPageNum(page.getPageNum());

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(pageDto));

        return msgResult;
    }


    @ApiOperation(value="获取开票类型列表")
    @PostMapping("invoiceTypeList")
    public MessageResult<Object> invoiceTypeList(){
        MessageResult<Object> msgResult = new MessageResult<>();

        List<DataDictionary> list = dataDictionaryService.findByCatalogName("开票类型");

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

        return msgResult;
    }


    @ApiOperation(value="统计列表")
    @RequestMapping(value = "billPushGoodStatisticsList",method = RequestMethod.POST)
    public MessageResult<Object> billPushGoodStatisticsList(
            String companyId,String payStatus,String payTimeRange,String invoiced,String payName,String invoiceType,
            @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"));


            User user = userService.get(subject);

            if(StringUtils.isNotEmpty(companyId)){
                searchParams.put("companyId",companyId);
            }
            else{
                List<CompanyPaymentInfo> companyPaymentInfoList = companyPaymentInfoService.findListByCompanyId(user.getCompanyId());
                searchParams.put("companyPaymentInfoList",companyPaymentInfoList);
            }

            if(StringUtils.isNotEmpty(payStatus)){
                searchParams.put("payStatus",payStatus);
            }
            else{
                searchParams.put("notPayStatus",30);
            }

            if(StringUtils.isNotEmpty(invoiced)){
                searchParams.put("invoiced", Boolean.valueOf(invoiced));
            }

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

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

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

                searchParams.put("beginPayTime", beginPayTime);
                searchParams.put("endPayTime", endPayTime);
            }

            Page<BillPushGoods> page = billPushGoodsService.pageSearchStatistics(searchParams,pageIndex,pageSize,true,sortList);

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

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

            for (BillPushGoods billPushGoods:page) {

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

                BillPush billPush = billPushService.get(billPushGoods.getBillPushId());

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

                if(StringUtils.isNotEmpty(billPushGoods.getGoodsId())) {
                    GoodsInfo goodsInfo = goodsInfoService.get(billPushGoods.getGoodsId());
                    if(goodsInfo!=null) {
                        map.put("goodsName", goodsInfo.getName());
                    }
                    else{
                        map.put("goodsName", "");
                    }
                }
                else{
                    map.put("goodsName", "");
                }

                String beginEndStr = billPushGoods.getBeginEndTime();
                String begin = "";
                String end = "";
                if(StringUtils.isNotEmpty(beginEndStr)){
                    String[] beginEndArray = beginEndStr.split(",");
                    begin = beginEndArray[0];
                    end = beginEndArray[1];
                    map.put("beginEndTime", begin + "至" + end);
                }
                else{
                    map.put("beginEndTime", "");
                }


                if(StringUtils.isNotEmpty(billPushGoods.getDetails())) {
                    JSONObject jsonObject = JSONObject.fromObject(billPushGoods.getDetails());
                    if (jsonObject!=null) {
                        if (jsonObject.get("totalFee") != null) {
                            String totalFeeStr = jsonObject.getString("totalFee");
                            if (StringUtils.isNotEmpty(totalFeeStr)) {
                                BigDecimal totalFee = BigDecimal.valueOf(Double.parseDouble(totalFeeStr));
                                map.put("totalFee", totalFee);
                            }
                        }
                    }
                }
                else{
                    map.put("totalFee", "");
                }

                map.put("invoiced", billPush.getInvoiced());

                if(billPush.getInvoiced()!=null) {
                    if(billPush.getInvoiced()){
                        map.put("invoicedN", "是");
                    }
                    else{
                        map.put("invoicedN", "否");
                    }
                }
                else{
                    map.put("invoicedN", "");
                }

                if(StringUtils.isNotEmpty(billPush.getInvoiceType())){
                    List<DataDictionary> dictionaryList = dataDictionaryService.findByCatalogName("开票类型");

                    for (DataDictionary item:dictionaryList) {
                        if(item.getValue().equals(billPush.getInvoiceType())){
                            map.put("invoiceType",item.getName());
                        }
                    }
                }
                else{
                    map.put("invoiceType","");
                }

                OrderInfo orderInfo = orderInfoService.get(billPush.getOrderId());

                if(orderInfo!=null) {
                    map.put("payStatus",orderInfo.getPayStatus());
                    if(orderInfo.getPayStatus()!=null){
                        if(orderInfo.getPayStatus()==10){
                            map.put("payStatusN","未支付");
                        }
                        else if(orderInfo.getPayStatus()==15){
                            map.put("payStatusN","部分支付");
                        }
                        else if(orderInfo.getPayStatus()==20){
                            map.put("payStatusN","已支付");
                        }
                        else if(orderInfo.getPayStatus()==30){
                            map.put("payStatusN","已关闭");
                        }
                        else if(orderInfo.getPayStatus()==40){
                            map.put("payStatusN","已退款");
                        }
                    }
                    else{
                        map.put("payStatusN","");
                    }
                    if(orderInfo.getPayTime()!=null){
                        map.put("payTime",sdf.format(orderInfo.getPayTime()));
                    }
                    else{
                        map.put("payTime","");
                    }

                    if (StringUtils.isNotEmpty(orderInfo.getPayName())) {
                        if ("wechat".equals(orderInfo.getPayName())) {
                            map.put("payName","微信");
                        } else if ("alipay".equals(orderInfo.getPayName())) {
                            map.put("payName","支付宝");
                        }
                        else if ("cash".equals(orderInfo.getPayName())) {
                            map.put("payName","现金支付");
                        }
                        else if ("transfer".equals(orderInfo.getPayName())) {
                            map.put("payName","对公转账");
                        }
                        else if ("individual".equals(orderInfo.getPayName())) {
                            map.put("payName","个人账户");
                        }
                        else {
                            map.put("payName","线下支付");
                        }
                    }
                    else{
                        map.put("payName","");
                    }
                }


                map.put("payee",billPush.getPayee());

                mapList.add(map);
            }

            if(exportFlag) {
                String filePath = statisticsExportXls(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 statisticsExportXls(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(StringUtils.strValue(map.get("companyName"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("goodsName"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("beginEndTime"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("totalFee"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("invoicedN"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("invoiceType"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("payStatusN"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("payTime"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("payName"),""));
            row.createCell(colIndex++).setCellValue(StringUtils.strValue(map.get("payee"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

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

            downloadUrl = OSSUtil.upload(ossConfig,"billPushGoodStatistics","账单推送统计.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }


    @ApiOperation(value="统计列表")
    @RequestMapping(value = "getInvoiceTypeList",method = RequestMethod.POST)
    public MessageResult<Object> getInvoiceTypeList(){
        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            List<DataDictionary> dictionaryList = dataDictionaryService.findByCatalogName("开票类型");

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

        return msgResult;
    }


    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

        String str = sdf.format(new Date());

        System.out.println(str);
    }
}
