package com.tofly.feesapi.dzfp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.bmgl.entity.SysChildCode;
import com.tofly.feesapi.bmgl.service.SysChildCodeService;
import com.tofly.feesapi.common.core.dto.Order;
import com.tofly.feesapi.common.core.dto.PageDto;
import com.tofly.feesapi.common.core.vo.PageResult;
import com.tofly.feesapi.common.dzfp.InvoiceAmounts;
import com.tofly.feesapi.common.dzfp.InvoiceService;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.common.util.GuidGenerator;
import com.tofly.feesapi.dzfp.entity.EiFpkjMx;
import com.tofly.feesapi.dzfp.entity.EiFpkjRequest;
import com.tofly.feesapi.dzfp.entity.EiSalerConfig;
import com.tofly.feesapi.dzfp.entity.EiSpbm;
import com.tofly.feesapi.dzfp.entity.dto.EiFpkjRequestFilter;
import com.tofly.feesapi.dzfp.entity.dto.EiFpkjRequestTjFilter;
import com.tofly.feesapi.dzfp.entity.dto.EiFpkjRequest_dzfpsq;
import com.tofly.feesapi.dzfp.entity.vo.EiFpkjRequestSelectTj;
import com.tofly.feesapi.dzfp.entity.vo.EiFpkjRequest_Excel;
import com.tofly.feesapi.dzfp.entity.vo.EiFpkjRequest_select;
import com.tofly.feesapi.dzfp.entity.vo.EiFpkjRequest_sum;
import com.tofly.feesapi.dzfp.mapper.EiFpkjRequestMapper;
import com.tofly.feesapi.dzfp.service.EiFpkjMxService;
import com.tofly.feesapi.dzfp.service.EiFpkjRequestService;
import com.tofly.feesapi.dzfp.service.EiSalerConfigService;
import com.tofly.feesapi.dzfp.service.EiSpbmService;

import com.tofly.feesapi.sfgl.entity.YyQfmx;
import com.tofly.feesapi.sfgl.entity.YySspjxx;
import com.tofly.feesapi.sfgl.service.YyQfmxService;
import com.tofly.feesapi.sfgl.service.YySspjxxService;
import com.tofly.feesapi.udb.service.IUserService;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EiFpkjRequestServiceImpl extends ServiceImpl<EiFpkjRequestMapper, EiFpkjRequest> implements EiFpkjRequestService {

    @Autowired
    private EiFpkjMxService eiFpkjMxService;
    @Autowired
    private EiSpbmService eiSpbmService;
    @Autowired
    private EiSalerConfigService eiSalerConfigService;

    @Autowired
    private YhKhjbxxService yhKhjbxxService;

    @Autowired
    private YyQfmxService yyQfmxService;

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private YySspjxxService yySspjxxService;

    @Autowired
    private SysChildCodeService sysChildCodeService;

    @Override
    public PageResult<EiFpkjRequest_select> getPage(PageDto pageDto, EiFpkjRequestFilter filter) {
        List<Order> orders = pageDto.getOrders();
        orders = orders.stream().map(item -> {
            if (item.getColumn().equals("sfrq")) {
                Order order = new Order();
                //  if (item.getColumn().equals("yhbh")) {
                order.setColumn("sfrq");
                // }
                order.setAsc(item.isAsc());
                return order;
            }
            return item;
        }).collect(Collectors.toList());
        pageDto.setOrders(orders);
        PageDto<EiFpkjRequest_select> page = baseMapper.getPage(pageDto, filter);
        return page.toVo();
    }

    @Override
    public PageResult<EiFpkjRequest_select> getSfPage(PageDto pageDto, EiFpkjRequestFilter filter) {
        List<Order> orders = pageDto.getOrders();
        orders = orders.stream().map(item -> {
            if (item.getColumn().equals("sfrq")) {
                Order order = new Order();
                //  if (item.getColumn().equals("yhbh")) {
                order.setColumn("sfrq");
                // }
                order.setAsc(item.isAsc());
                return order;
            }
            return item;
        }).collect(Collectors.toList());
        pageDto.setOrders(orders);
        PageDto<EiFpkjRequest_select> page = this.baseMapper.getSfPage(pageDto, filter);
        return page.toVo();
    }

    @Override
    public PageResult<EiFpkjRequest_select> getFpPage(PageDto pageDto, EiFpkjRequestFilter filter) {
        List<Order> orders = pageDto.getOrders();
        orders = orders.stream().map(item -> {
            if (item.getColumn().equals("sfrq")) {
                Order order = new Order();
                //  if (item.getColumn().equals("yhbh")) {
                order.setColumn("sfrq");
                // }
                order.setAsc(item.isAsc());
                return order;
            }
            return item;
        }).collect(Collectors.toList());
        pageDto.setOrders(orders);
        PageDto<EiFpkjRequest_select> page = this.baseMapper.getFpPage(pageDto, filter);
        return page.toVo();
    }

    @Override
    public PageResult<EiFpkjRequest_select> getWsfPage(PageDto pageDto, EiFpkjRequestFilter filter) {
        List<Order> orders = pageDto.getOrders();
        orders = orders.stream().map(item -> {
            if (item.getColumn().equals("sfrq")) {
                Order order = new Order();
                //  if (item.getColumn().equals("yhbh")) {
                order.setColumn("sfrq");
                // }
                order.setAsc(item.isAsc());
                return order;
            }
            return item;
        }).collect(Collectors.toList());
        pageDto.setOrders(orders);
        PageDto<EiFpkjRequest_select> page = this.baseMapper.getWsfPage(pageDto, filter);
        return page.toVo();
    }

    @Override
    public PageResult<EiFpkjRequest_select> getZnjPage(PageDto pageDto, EiFpkjRequestFilter filter) {
        List<Order> orders = pageDto.getOrders();
        orders = orders.stream().map(item -> {
            if (item.getColumn().equals("sfrq")) {
                Order order = new Order();
                //  if (item.getColumn().equals("yhbh")) {
                order.setColumn("sfrq");
                // }
                order.setAsc(item.isAsc());
                return order;
            }
            return item;
        }).collect(Collectors.toList());
        pageDto.setOrders(orders);
        PageDto<EiFpkjRequest_select> page = this.baseMapper.getZnjPage(pageDto, filter);
        return page.toVo();
    }

    @Override
    public List<EiFpkjRequest_Excel> getList(EiFpkjRequestFilter filter) {
        List<EiFpkjRequest_Excel> list = this.baseMapper.getList(filter);
        return list;
    }

    @Override
    public List<EiFpkjRequest_sum> getListSum(EiFpkjRequestFilter filter) {
        List<EiFpkjRequest_sum> list = this.baseMapper.getListSum(filter);
        return list;
    }

    public List<EiFpkjRequestSelectTj> getFprkptjList(EiFpkjRequestTjFilter filter) {
        List<EiFpkjRequestSelectTj> list = this.baseMapper.getFprkptjList(filter);
        if (!list.isEmpty()) {
//            List<User> userList = userService.getAllUser();
//            list.forEach(e -> {
//                if (e.getSfry() != null) {
//                    User user = userList.stream().filter(u -> u.getId().equals(Long.valueOf(e.getSfry()))).findFirst().orElse(null);
//                    if (user != null) {
//                        e.setSfry(user.getRealName());
//                    }
//                }
//            });
            EiFpkjRequestSelectTj eiFpkjRequestSelectTj = new EiFpkjRequestSelectTj();
            eiFpkjRequestSelectTj.setYhbh("合计");
            eiFpkjRequestSelectTj.setExTaxAmount(list.stream().map(EiFpkjRequestSelectTj::getExTaxAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            eiFpkjRequestSelectTj.setSf(list.stream().map(EiFpkjRequestSelectTj::getSf).reduce(BigDecimal.ZERO, BigDecimal::add));
            eiFpkjRequestSelectTj.setWsf(list.stream().map(EiFpkjRequestSelectTj::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add));
            eiFpkjRequestSelectTj.setLjf(list.stream().map(EiFpkjRequestSelectTj::getLjf).reduce(BigDecimal.ZERO, BigDecimal::add));
            eiFpkjRequestSelectTj.setSzyf(list.stream().map(EiFpkjRequestSelectTj::getSzyf).reduce(BigDecimal.ZERO, BigDecimal::add));
            eiFpkjRequestSelectTj.setWyj(list.stream().map(EiFpkjRequestSelectTj::getWyj).reduce(BigDecimal.ZERO, BigDecimal::add));
            list.add(eiFpkjRequestSelectTj);
        }
        return list;
    }

    @Override
    @Transactional
    public boolean dzfpch(EiFpkjRequest eiFpkjRequest) {
        //修改汇总发票信息
        this.lambdaUpdate()
                .set(EiFpkjRequest::getZfZfbz, "1")
                .eq(EiFpkjRequest::getLsbh, eiFpkjRequest.getLsbh())
                .update();
        if (eiFpkjRequest.getClCljg().equals("0")) {
            return true;
        }

        EiFpkjRequest eiFpkjRequest_ch = new EiFpkjRequest();//冲红
        //添加汇总作废票据信息
        BeanUtils.copyProperties(eiFpkjRequest, eiFpkjRequest_ch);
        eiFpkjRequest_ch.setLsbh(GuidGenerator.getGuid());
        if (eiFpkjRequest_ch.getSsje().compareTo(BigDecimal.ONE) > 0) {
            eiFpkjRequest_ch.setSsje(eiFpkjRequest_ch.getSsje().multiply(BigDecimal.valueOf(-1)));//实收金额
        }

        if (eiFpkjRequest_ch.getExtaxamount().compareTo(BigDecimal.ONE) > 0) {
            eiFpkjRequest_ch.setExtaxamount(eiFpkjRequest_ch.getExtaxamount().multiply(BigDecimal.valueOf(-1)));//不含税金额
        }

        if (eiFpkjRequest_ch.getTaxamount().compareTo(BigDecimal.ONE) > 0) {
            eiFpkjRequest_ch.setTaxamount(eiFpkjRequest_ch.getTaxamount().multiply(BigDecimal.valueOf(-1)));//合计税额
        }

        if (eiFpkjRequest_ch.getOrderamount().compareTo(BigDecimal.ONE) > 0) {
            eiFpkjRequest_ch.setOrderamount(eiFpkjRequest_ch.getOrderamount().multiply(BigDecimal.valueOf(-1)));//价税合计
        }

        eiFpkjRequest_ch.setNextinvoicecode(eiFpkjRequest.getInvoicecode());
        eiFpkjRequest_ch.setNextinvoicenum(eiFpkjRequest.getInvoicenum());
        eiFpkjRequest_ch.setZfZfbz("2");
        eiFpkjRequest_ch.setFpSfkp("1");
        eiFpkjRequest_ch.setInvoicetype("2");
        eiFpkjRequest_ch.setStatus("0");
        eiFpkjRequest_ch.setClLock("0");
        eiFpkjRequest_ch.setClCljg("0");
        eiFpkjRequest_ch.setJfYxbz("0");
        eiFpkjRequest_ch.setRemark("对应正数发票代码:" + (StringUtil.isNotEmpty(eiFpkjRequest.getInvoicecode()) ? eiFpkjRequest.getInvoicecode() : "")
                + "号码:" + (StringUtil.isNotEmpty(eiFpkjRequest.getInvoicenum()) ? eiFpkjRequest.getInvoicenum() : "")); //备注
        //为空字段
        eiFpkjRequest_ch.setInvoicecode("");
        eiFpkjRequest_ch.setInvoicenum("");
        eiFpkjRequest_ch.setJfPdf("");
        eiFpkjRequest_ch.setPdfurl("");
        eiFpkjRequest_ch.setJfPdffilename("");
        eiFpkjRequest_ch.setJfJsurl("");
        eiFpkjRequest_ch.setInvoicetime("");
        eiFpkjRequest_ch.setClClsj(null);
        eiFpkjRequest_ch.setClRemessage("");
        eiFpkjRequest_ch.setNnwFplsh("");


        //添加开票作废明细信息
        List<EiFpkjMx> eiFpkjMxList = eiFpkjMxService.lambdaQuery()
                .eq(EiFpkjMx::getLsbh, eiFpkjRequest.getLsbh())
                .list();
        for (EiFpkjMx e : eiFpkjMxList) {
            EiFpkjMx eiFpkjMx_ch = new EiFpkjMx(); //冲红明细
            BeanUtils.copyProperties(e, eiFpkjMx_ch);
            eiFpkjMx_ch.setMxid(GuidGenerator.getGuid());
            eiFpkjMx_ch.setLsbh(eiFpkjRequest_ch.getLsbh());
            if (e.getNum().compareTo(BigDecimal.ZERO) > 0) {
                eiFpkjMx_ch.setNum(e.getNum().multiply(BigDecimal.valueOf(-1)));//数量
            }

            if (e.getTax().compareTo(BigDecimal.ZERO) > 0) {
                eiFpkjMx_ch.setTax(e.getTax().multiply(BigDecimal.valueOf(-1)));//税额
            }

            if (e.getTax().compareTo(BigDecimal.ZERO) > 0) {
                eiFpkjMx_ch.setTax(e.getTax().multiply(BigDecimal.valueOf(-1)));//税额
            }

            eiFpkjMx_ch.setTaxrate(e.getTaxrate());//税率
            if (e.getTaxexcludedamount().compareTo(BigDecimal.ZERO) > 0) {
                eiFpkjMx_ch.setTaxexcludedamount(e.getTaxexcludedamount().multiply(BigDecimal.valueOf(-1)));//不含税金额
            }

            if (e.getTaxincludedamount().compareTo(BigDecimal.ZERO) > 0) {
                eiFpkjMx_ch.setTaxincludedamount(e.getTaxincludedamount().multiply(BigDecimal.valueOf(-1)));//含税金额
            }
            eiFpkjMxService.save(eiFpkjMx_ch);//添加冲红发票明细

        }
        save(eiFpkjRequest_ch);//添加汇总发票信息

        return true;
    }

    @Override
    @Transactional
    public String bzkpxxtj(EiFpkjRequest eiFpkjRequest) {
        if (StringUtil.isEmpty(eiFpkjRequest.getSfid())) {
            throw new FeesException("收费ID不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(eiFpkjRequest.getYhbh())) {
            throw new FeesException("用户编号不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isNull(eiFpkjRequest.getYhlx())) {
            throw new FeesException("用户类型不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isNull(eiFpkjRequest.getSsje())) {
            throw new FeesException("实收金额不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (eiFpkjRequest.getSsje().compareTo(BigDecimal.ZERO) <= 0) {
            throw new FeesException("实收金额必须大于0！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(eiFpkjRequest.getFpSfkp())) {
            eiFpkjRequest.setFpSfkp("1");
        }
        if (StringUtil.isEmpty(eiFpkjRequest.getInvoicetype())) {
            eiFpkjRequest.setInvoicetype("1");
        }
        if (StringUtil.isEmpty(eiFpkjRequest.getJfYxbz())) {
            eiFpkjRequest.setJfYxbz("0");
        }
        if (StringUtil.isEmpty(eiFpkjRequest.getZfZfbz())) {
            eiFpkjRequest.setZfZfbz("0");
        }
        if (StringUtil.isNotEmpty(eiFpkjRequest.getPayee())) {
            eiFpkjRequest.setSfry(eiFpkjRequest.getPayee()); // 收费人员
            eiFpkjRequest.setClerk(eiFpkjRequest.getPayee());//开票人员
            eiFpkjRequest.setChecker(eiFpkjRequest.getPayee());//复核人员
        }
        eiFpkjRequest.setClLock("0");
        eiFpkjRequest.setClCljg("0");
        eiFpkjRequest.setPushmode(-1);
        EiSpbm eiSpbm = eiSpbmService.getById("08"); //安装服务
        BigDecimal taxrate = BigDecimal.valueOf(Double.parseDouble(eiSpbm.getSl()));//税率
        BigDecimal tax = eiFpkjRequest.getSsje().multiply(taxrate).divide(taxrate.add(BigDecimal.ONE), 2, RoundingMode.HALF_UP);//合计税
        BigDecimal taxExcludedAmount = eiFpkjRequest.getSsje().subtract(tax);//汇总不含税金额
        BigDecimal taxIncludedAmount = eiFpkjRequest.getSsje();//含税金额

        eiFpkjRequest.setExtaxamount(taxExcludedAmount);
        eiFpkjRequest.setTaxamount(tax);
        eiFpkjRequest.setOrderamount(taxIncludedAmount);
        eiFpkjRequest.setLsbh(GuidGenerator.getGuid());

        EiSalerConfig fpConfig = eiSalerConfigService.getById(1);
        eiFpkjRequest.setSalertaxnum(fpConfig.getSalertaxnum());//销方税号
        eiFpkjRequest.setSalertel(fpConfig.getSalertel());//销方电话
        eiFpkjRequest.setSaleraddress(fpConfig.getSaleraddress());//销方地址
        eiFpkjRequest.setSaleraccount(fpConfig.getSaleraccount());//销方银行账号
        eiFpkjRequest.setSalerbank(fpConfig.getSalerbank());//销方银行

        if (StringUtil.isNull(eiFpkjRequest.getSfrq())) {
            eiFpkjRequest.setSfrq(new Date());
        }
        if (!this.save(eiFpkjRequest)) {
            throw new FeesException("报装开票信息添加失败！", FeesErrorCode.BUSINESS_ERROR);
        }
        EiFpkjMx eiFpkjMx = new EiFpkjMx();
        eiFpkjMx.setMxid(GuidGenerator.getGuid());
        eiFpkjMx.setUnit("元"); // 单位
        eiFpkjMx.setTaxrate(taxrate); // 税率
        eiFpkjMx.setSpectype("无");//规格型号
        eiFpkjMx.setGoodsname(eiSpbm.getName()); // 商品名称
        eiFpkjMx.setGoodscode(eiSpbm.getSszlbm()); // 商品编码
        eiFpkjMx.setWithtaxflag(eiSpbm.getDjHsbs()); // 单价含税标识
        eiFpkjMx.setInvoicelineproperty("0"); // 发票行性质
        eiFpkjMx.setFavouredpolicyflag(eiSpbm.getYhZcbs()); // 优惠政策
        eiFpkjMx.setFavouredpolicyname(eiSpbm.getYhZcmc()); // 优惠政策名称
        eiFpkjMx.setZerorateflag(eiSpbm.getYhZcmc()); // 零税率标识
        eiFpkjMx.setNum(BigDecimal.ONE); // 数量
        eiFpkjMx.setLsbh(eiFpkjRequest.getLsbh());//流水编号，与汇总表关联
        eiFpkjMx.setPrice(taxIncludedAmount); // 单价
        eiFpkjMx.setTax(tax); // 税额
        eiFpkjMx.setTaxexcludedamount(taxExcludedAmount);
        eiFpkjMx.setTaxincludedamount(taxIncludedAmount);
        if (!eiFpkjMxService.save(eiFpkjMx)) {
            throw new FeesException("报装开票明细添加失败！", FeesErrorCode.BUSINESS_ERROR);
        }
        return eiFpkjRequest.getLsbh();
    }

    @Override
    @Transactional
    public void qtfykp(YhKhjbxx yhKhjbxx, List<YySspjxx> yySspjxxs, String sfkp, String ishbkp) {
        if (ishbkp.equals("0")) {
            dgkp(yhKhjbxx, yySspjxxs, sfkp);
        } else {
            hbkp(yhKhjbxx, yySspjxxs, sfkp);
        }
    }

    /**
     * 合并开票
     *
     * @param yhKhjbxx  用户信息
     * @param yySspjxxs 实收信息
     * @param sfkp      是否开票
     */
    private void hbkp(YhKhjbxx yhKhjbxx, List<YySspjxx> yySspjxxs, String sfkp) {
        String lsbh = GuidGenerator.getGuid();
        InvoiceAmounts amounts = new InvoiceAmounts(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
        for (YySspjxx yySspjxx : yySspjxxs) {
            //根据费用类型获取通用编码
            SysChildCode sysChildCode = sysChildCodeService.get("48", yySspjxx.getFylx());
            EiSpbm eiSpbm = eiSpbmService.getById(sysChildCode.getCcname());
            BigDecimal taxrate = BigDecimal.valueOf(Double.parseDouble(eiSpbm.getSl()));//税率
            BigDecimal tax = yySspjxx.getSszje().multiply(taxrate).divide(taxrate.add(BigDecimal.ONE), 2, RoundingMode.HALF_UP);//合计税
            BigDecimal taxExcludedAmount = yySspjxx.getSszje().subtract(tax);//汇总不含税金额
            BigDecimal taxIncludedAmount = yySspjxx.getSszje();//含税金额
            amounts = new InvoiceAmounts(amounts, new InvoiceAmounts(
                    taxExcludedAmount,
                    tax,
                    taxIncludedAmount
            ));

            EiFpkjMx eiFpkjMx = new EiFpkjMx();
            eiFpkjMx.setMxid(GuidGenerator.getGuid());
            eiFpkjMx.setUnit("元"); // 单位
            eiFpkjMx.setTaxrate(taxrate); // 税率
            eiFpkjMx.setSpectype("无");//规格型号
            eiFpkjMx.setGoodsname(eiSpbm.getName()); // 商品名称
            eiFpkjMx.setGoodscode(eiSpbm.getSszlbm()); // 商品编码
            eiFpkjMx.setInvoicelineproperty("0"); // 发票行性质
            eiFpkjMx.setFavouredpolicyflag(eiSpbm.getYhZcbs()); // 优惠政策
            eiFpkjMx.setFavouredpolicyname(eiSpbm.getYhZcmc()); // 优惠政策名称
            eiFpkjMx.setZerorateflag(eiSpbm.getYhZcmc()); // 零税率标识
            eiFpkjMx.setLsbh(lsbh);//流水编号，与汇总表关联
            eiFpkjMx.setTax(tax); // 税额
            eiFpkjMx.setTaxexcludedamount(taxExcludedAmount);
            eiFpkjMx.setTaxincludedamount(taxIncludedAmount);
            //eiFpkjMx.setWithtaxflag(eiSpbm.getDjHsbs()); // 单价含税标识
            //eiFpkjMx.setNum(BigDecimal.ONE); // 数量
            //eiFpkjMx.setPrice(taxIncludedAmount); // 单价
            if (!eiFpkjMxService.save(eiFpkjMx)) {
                throw new FeesException("开票明细添加失败！", FeesErrorCode.BUSINESS_ERROR);
            }
        }
        EiFpkjRequest eiFpkjRequest = new EiFpkjRequest();
        eiFpkjRequest.setYhbh(yhKhjbxx.getYhbh());
        eiFpkjRequest.setYhlx(2);
        eiFpkjRequest.setSsgs(yhKhjbxx.getSsgs());
        eiFpkjRequest.setYhSspq(yhKhjbxx.getSscbpq());
        eiFpkjRequest.setPushmode(-1);
        eiFpkjRequest.setBuyername(StringUtil.isNotEmpty(yhKhjbxx.getFpName()) ? yhKhjbxx.getFpName() : yhKhjbxx.getYhxm()); // 购买方
        eiFpkjRequest.setBuyertaxnum(yhKhjbxx.getFpNsrsbh()); // 购方税号
        eiFpkjRequest.setBuyertel(yhKhjbxx.getFpLxdh()); // 购方电话
        eiFpkjRequest.setBuyeraddress(yhKhjbxx.getFpDz()); // 购方地址
        eiFpkjRequest.setBuyeraccount(yhKhjbxx.getFpBankcode()); // 购方银行账号
        eiFpkjRequest.setBuyerbank(yhKhjbxx.getFpBankname()); // 购方银行
        eiFpkjRequest.setInvoicetype("1"); // 开票类型（蓝票）
        eiFpkjRequest.setStatus("0");//发票状态
        eiFpkjRequest.setClLock("0");//是否锁定
        eiFpkjRequest.setClCljg("0");//处理结果
        eiFpkjRequest.setZfZfbz("0");//作废标识
        eiFpkjRequest.setJfYxbz("0");//交付有效标识
        eiFpkjRequest.setCxJfbz("0");//重新交付标识
        eiFpkjRequest.setFpCkbz("0");//发票重开标识
        eiFpkjRequest.setProxyinvoiceflag("0");//代开标识

        eiFpkjRequest.setListflag("0");//清单标识

        String fplx = yhKhjbxx.getFplx();
        if (StringUtil.isNotEmpty(fplx) && fplx.equals("2")) {
            eiFpkjRequest.setInvoiceline("bs");//发票种类(专票)
        } else {
            eiFpkjRequest.setInvoiceline("pc");//发票种类(普票)
        }

        EiSalerConfig fpConfig = eiSalerConfigService.getById(1);
        eiFpkjRequest.setSalertaxnum(fpConfig.getSalertaxnum());//销方税号
        eiFpkjRequest.setSalertel(fpConfig.getSalertel());//销方电话
        eiFpkjRequest.setSaleraddress(fpConfig.getSaleraddress());//销方地址
        eiFpkjRequest.setSaleraccount(fpConfig.getSaleraccount());//销方银行账号
        eiFpkjRequest.setSalerbank(fpConfig.getSalerbank());//销方银行
        eiFpkjRequest.setFpSfkp(sfkp);
        eiFpkjRequest.setFpSfHb("1");
        eiFpkjRequest.setTaxamount(amounts.getTax());//合计税额
        eiFpkjRequest.setOrderamount(amounts.getTaxIncludedAmount());//含税金额
        eiFpkjRequest.setExtaxamount(amounts.getTaxExcludedAmount());//不含税金额

        if (!this.save(eiFpkjRequest)) {
            throw new FeesException("开票信息添加失败！", FeesErrorCode.BUSINESS_ERROR);
        }
    }

    /**
     * 单个开票
     *
     * @param yhKhjbxx  用户信息
     * @param yySspjxxs 实收信息
     * @param sfkp      是否开票
     */
    private void dgkp(YhKhjbxx yhKhjbxx, List<YySspjxx> yySspjxxs, String sfkp) {
        EiFpkjRequest eiFpkjRequest = new EiFpkjRequest();
        eiFpkjRequest.setYhbh(yhKhjbxx.getYhbh());
        eiFpkjRequest.setYhlx(2);
        eiFpkjRequest.setSsgs(yhKhjbxx.getSsgs());
        eiFpkjRequest.setYhSspq(yhKhjbxx.getSscbpq());
        eiFpkjRequest.setPushmode(-1);
        eiFpkjRequest.setBuyername(StringUtil.isNotEmpty(yhKhjbxx.getFpName()) ? yhKhjbxx.getFpName() : yhKhjbxx.getYhxm()); // 购买方
        eiFpkjRequest.setBuyertaxnum(yhKhjbxx.getFpNsrsbh()); // 购方税号
        eiFpkjRequest.setBuyertel(yhKhjbxx.getFpLxdh()); // 购方电话
        eiFpkjRequest.setBuyeraddress(yhKhjbxx.getFpDz()); // 购方地址
        eiFpkjRequest.setBuyeraccount(yhKhjbxx.getFpBankcode()); // 购方银行账号
        eiFpkjRequest.setBuyerbank(yhKhjbxx.getFpBankname()); // 购方银行
        eiFpkjRequest.setInvoicetype("1"); // 开票类型（蓝票）
        eiFpkjRequest.setStatus("0");//发票状态
        eiFpkjRequest.setClLock("0");//是否锁定
        eiFpkjRequest.setClCljg("0");//处理结果
        eiFpkjRequest.setZfZfbz("0");//作废标识
        eiFpkjRequest.setJfYxbz("0");//交付有效标识
        eiFpkjRequest.setCxJfbz("0");//重新交付标识
        eiFpkjRequest.setFpCkbz("0");//发票重开标识
        eiFpkjRequest.setProxyinvoiceflag("0");//代开标识

        eiFpkjRequest.setListflag("0");//清单标识

        String fplx = yhKhjbxx.getFplx();
        if (StringUtil.isNotEmpty(fplx) && fplx.equals("2")) {
            eiFpkjRequest.setInvoiceline("bs");//发票种类(专票)
        } else {
            eiFpkjRequest.setInvoiceline("pc");//发票种类(普票)
        }

        EiSalerConfig fpConfig = eiSalerConfigService.getById(1);
        eiFpkjRequest.setSalertaxnum(fpConfig.getSalertaxnum());//销方税号
        eiFpkjRequest.setSalertel(fpConfig.getSalertel());//销方电话
        eiFpkjRequest.setSaleraddress(fpConfig.getSaleraddress());//销方地址
        eiFpkjRequest.setSaleraccount(fpConfig.getSaleraccount());//销方银行账号
        eiFpkjRequest.setSalerbank(fpConfig.getSalerbank());//销方银行
        eiFpkjRequest.setFpSfkp(sfkp);
        eiFpkjRequest.setFpSfHb("0");

        for (YySspjxx yySspjxx : yySspjxxs) {
            String sfrybm = yySspjxx.getSfrybm();
            String sfryxm = yySspjxx.getSfryxm();
            eiFpkjRequest.setLsbh(GuidGenerator.getGuid());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String strorderno = sdf.format(new Date()) + GuidGenerator.getGuid().substring(0, 6);
            eiFpkjRequest.setOrderno(strorderno);//订单号
            eiFpkjRequest.setInvoicedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));// 订单时间
            eiFpkjRequest.setSfry(sfryxm); // 收费人员
            eiFpkjRequest.setPayee(sfryxm);// 收款人员
            eiFpkjRequest.setClerk(sfryxm);// 开票人员
            eiFpkjRequest.setClerkid(sfrybm);// 开票人员id
            eiFpkjRequest.setChecker(sfryxm);// 复核人员
            eiFpkjRequest.setSpecificfactor("0");//特定要素
            eiFpkjRequest.setSfid(yySspjxx.getId()); //用于关联欠费明细与实收明细表
            eiFpkjRequest.setSflsbh(yySspjxx.getSflsbh());//收费流水编号
            eiFpkjRequest.setCwrq(yySspjxx.getCwrq()); // 财务月份
            eiFpkjRequest.setSsje(yySspjxx.getYsje()); // 实收金额=应收金额

            //根据费用类型获取通用编码
            SysChildCode sysChildCode = sysChildCodeService.get("48", yySspjxx.getFylx());
            EiSpbm eiSpbm = eiSpbmService.getById(sysChildCode.getCcname()); //安装服务
            BigDecimal taxrate = BigDecimal.valueOf(Double.parseDouble(eiSpbm.getSl()));//税率
            BigDecimal tax = eiFpkjRequest.getSsje().multiply(taxrate).divide(taxrate.add(BigDecimal.ONE), 2, RoundingMode.HALF_UP);//合计税
            BigDecimal taxExcludedAmount = eiFpkjRequest.getSsje().subtract(tax);//汇总不含税金额
            BigDecimal taxIncludedAmount = eiFpkjRequest.getSsje();//含税金额
            eiFpkjRequest.setTaxamount(tax);//合计税额
            eiFpkjRequest.setOrderamount(taxIncludedAmount);//含税金额
            eiFpkjRequest.setExtaxamount(taxExcludedAmount);//不含税金额

            if (!this.save(Deserialization(eiFpkjRequest))) {
                throw new FeesException("开票信息添加失败！", FeesErrorCode.BUSINESS_ERROR);
            }
            EiFpkjMx eiFpkjMx = new EiFpkjMx();
            eiFpkjMx.setMxid(GuidGenerator.getGuid());
            eiFpkjMx.setUnit("元"); // 单位
            eiFpkjMx.setTaxrate(taxrate); // 税率
            eiFpkjMx.setSpectype("无");//规格型号
            eiFpkjMx.setGoodsname(eiSpbm.getName()); // 商品名称
            eiFpkjMx.setGoodscode(eiSpbm.getSszlbm()); // 商品编码
            eiFpkjMx.setInvoicelineproperty("0"); // 发票行性质
            eiFpkjMx.setFavouredpolicyflag(eiSpbm.getYhZcbs()); // 优惠政策
            eiFpkjMx.setFavouredpolicyname(eiSpbm.getYhZcmc()); // 优惠政策名称
            eiFpkjMx.setZerorateflag(eiSpbm.getYhZcmc()); // 零税率标识
            eiFpkjMx.setLsbh(eiFpkjRequest.getLsbh());//流水编号，与汇总表关联
            eiFpkjMx.setTax(tax); // 税额
            eiFpkjMx.setTaxexcludedamount(taxExcludedAmount);
            eiFpkjMx.setTaxincludedamount(taxIncludedAmount);
            //eiFpkjMx.setWithtaxflag(eiSpbm.getDjHsbs()); // 单价含税标识
            //eiFpkjMx.setNum(BigDecimal.ONE); // 数量
            //eiFpkjMx.setPrice(taxIncludedAmount); // 单价
            if (!eiFpkjMxService.save(eiFpkjMx)) {
                throw new FeesException("开票明细添加失败！", FeesErrorCode.BUSINESS_ERROR);
            }
        }
    }

    /**
     * 反序列化(处理修改问题)
     *
     * @param eiFpkjMx
     * @return
     */
    private EiFpkjMx Deserialization(EiFpkjMx eiFpkjMx) {
        return JSONObject.parseObject(JSON.toJSONString(eiFpkjMx), EiFpkjMx.class);
    }

    /**
     * 反序列化(处理修改问题)
     *
     * @param eiFpkjRequest
     * @return
     */
    private EiFpkjRequest Deserialization(EiFpkjRequest eiFpkjRequest) {
        return JSONObject.parseObject(JSON.toJSONString(eiFpkjRequest), EiFpkjRequest.class);
    }

    @Override
    @Transactional
    public boolean dzfpsq(EiFpkjRequest_dzfpsq eifpkjrequest_dzfpsq) {
        if (StringUtil.isEmpty(eifpkjrequest_dzfpsq.getYhbh())) {
            throw new FeesException("用户编号不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(eifpkjrequest_dzfpsq.getSflsbh())) {
            throw new FeesException("收费流水编号不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        YhKhjbxx yhKhjbxx = yhKhjbxxService.getById(eifpkjrequest_dzfpsq.getYhbh());
        if (StringUtil.isNull(yhKhjbxx)) {
            throw new FeesException("用户信息不存在！", FeesErrorCode.BUSINESS_ERROR);
        }
        long count = this.lambdaQuery()
                .eq(EiFpkjRequest::getYhbh, yhKhjbxx.getYhbh())
                .eq(EiFpkjRequest::getSflsbh, eifpkjrequest_dzfpsq.getSflsbh())
                .eq(EiFpkjRequest::getZfZfbz, "0")
                .count();
        if (count > 0) {
            throw new FeesException("该记录已存在正常申请的发票", FeesErrorCode.BUSINESS_ERROR);
        }
        //购方姓名
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getBuyername())) {
            yhKhjbxx.setFpName(eifpkjrequest_dzfpsq.getBuyername());
        }
        //购方税号
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getBuyertaxnum())) {
            yhKhjbxx.setFpNsrsbh(eifpkjrequest_dzfpsq.getBuyertaxnum());
        }//购方联系号码
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getBuyertel())) {
            yhKhjbxx.setFpLxdh(eifpkjrequest_dzfpsq.getBuyertel());
        }
        //购方地址
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getBuyeraddress())) {
            yhKhjbxx.setFpDz(eifpkjrequest_dzfpsq.getBuyeraddress());
        }
        //购方银行账号
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getBuyeraccount())) {
            yhKhjbxx.setFpBankcode(eifpkjrequest_dzfpsq.getBuyeraccount());
        }
        //购方银行开户行
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getBuyerbank())) {
            yhKhjbxx.setFpBankname(eifpkjrequest_dzfpsq.getBuyerbank());
        }
        //推送方式
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getPushmode())) {
            yhKhjbxx.setPushmode(eifpkjrequest_dzfpsq.getPushmode());
        }
        //购方手机
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getBuyerphone())) {
            yhKhjbxx.setFpLxdh(eifpkjrequest_dzfpsq.getBuyerphone());
        }
        //推送邮箱
        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getEmail())) {
            yhKhjbxx.setEmail(eifpkjrequest_dzfpsq.getEmail());
            yhKhjbxx.setDzyx(eifpkjrequest_dzfpsq.getEmail());
        }

        if (StringUtil.isNotEmpty(eifpkjrequest_dzfpsq.getInvoiceline())) {
            if (eifpkjrequest_dzfpsq.getInvoiceline().equals("bs")) {
                yhKhjbxx.setFplx("2");
            } else {
                yhKhjbxx.setFplx("1");
            }
        }

        if (!yhKhjbxxService.updateById(yhKhjbxx)) {
            throw new FeesException("用户信息修改失败！", FeesErrorCode.BUSINESS_ERROR);
        }

        List<YyQfmx> yyQfmxList = yyQfmxService.lambdaQuery()
                .eq(YyQfmx::getSflsbh, eifpkjrequest_dzfpsq.getSflsbh())
                .eq(YyQfmx::getEiYkfpBz, "0")
                .list();
        if (yyQfmxList.size() > 0) {
            List<YySspjxx> list = yySspjxxService.lambdaQuery()
                    .eq(YySspjxx::getSflsbh, eifpkjrequest_dzfpsq.getSflsbh())
                    .list();
            invoiceService.addInvoiceData(yyQfmxList, list, yhKhjbxx, "0", "1");
        } else {
            throw new FeesException("收费流水编号错误，未查询到收费记录！", FeesErrorCode.BUSINESS_ERROR);
        }
        return true;
    }
}
