package com.huyi.service.bill.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huyi.service.base.entity.ZcBillFileRel;
import com.huyi.service.base.entity.ZcBillInf;
import com.huyi.service.base.entity.ZcBillInvoiceRel;
import com.huyi.service.base.entity.ZcInvoiceInf;
import com.huyi.service.base.service.*;
import com.huyi.service.bill.service.IOwnBillService;
import com.keao.tianhu.starter.mybatis.plus.entity.QueryRequest;
import com.tianhu.common.core.constant.SalaryConstants;
import com.tianhu.common.core.domain.R;
import com.tianhu.common.core.utils.*;
import com.tianhu.common.core.web.controller.BaseController;
import com.tianhu.common.core.web.domain.AjaxResult;
import com.tianhu.common.log.annotation.Log;
import com.tianhu.common.log.enums.BusinessType;
import com.tianhu.common.security.annotation.PreAuthorize;
import com.tianhu.common.security.service.TokenService;
import com.tianhu.system.api.RemoteFileService;
import com.tianhu.system.api.domain.PubFileInf;
import com.tianhu.system.api.domain.SysUser;
import com.tianhu.system.api.model.LoginUser;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 往来账款管理
 *
 * @author dudm@minpay.cc
 * @date 2021-08-17
 */
@RestController
@RequestMapping("ownBill")
public class OwnBillController extends BaseController {

    /**
     * 验证状态 0未验证1成功2失败
     */
    private static String CHECK_SUCCESS = "1";

    @Autowired
    private IOwnBillService iOwnBillService;

    @Autowired
    private IZcBillInfService iZcBillInfService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private  IZcInvoiceInfService iZcInvoiceInfService;

    @Autowired
    private IZcBillInvoiceRelService iZcBillInvoiceRelService;

    @Autowired
    private IZcBillFileRelService iZcBillFileRelService;

    @Autowired
    private IPubFileInfService iPubFileInfService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 往来账款列表
     *
     * @param zbiName           账款名称
     * @param zbiNumber         账款编号
     * @param payerName         应付方
     * @param payeeName         应收方
     * @param zbiType           账款类型
     * @param zbiStatus         账款状态
     * @return
     */
    @GetMapping("/billList")
    public R list(
            @RequestParam(required=false) String zbiName,
            @RequestParam(required=false) String zbiNumber,
            @RequestParam(required=false) String payerName,
            @RequestParam(required=false) String payeeName,
            @RequestParam(required=false) String zbiType,
            @RequestParam(required=false) String zbiStatus,
            QueryRequest request) {
        //查询当前操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser user = userInfo.getSysUser();
        //获取企业
        String companyId = user.getCompanyId();
        Map map = new HashMap();
        //账款类型
        if("00".equals(zbiType)){
            map.put("payerId", companyId);
        }else if ("01".equals(zbiType)){
            map.put("payeeId", companyId);
        }
        if (!SalaryConstants.OPEX.equals(companyId)) {
            map.put("companyId", companyId);
        }
        //账款名称
        map.put("zbiName", zbiName);
        //账款编号
        map.put("zbiNumber", zbiNumber);
        //应付方
        map.put("payerName", payerName);
        //应收方
        map.put("payeeName", payeeName);
        //账款状态
        map.put("zbiStatus", zbiStatus);
        IPage<Map> list = iOwnBillService.selectBillInfList(map,request);
        return R.ok(list);
    }

    /**
     * 获取往来账款明细信息
     */
    @GetMapping(value = "/{zbiId}")
    public AjaxResult getBillInf(@PathVariable("zbiId") String zbiId) {
        //获取用户信息
        LoginUser userInfo = tokenService.getLoginUser();
        //企业id
        String companyId = userInfo.getSysUser().getCompanyId();
        //查询往来账款
        ZcBillInf zcBillInf = iZcBillInfService.getById(zbiId);
        Map map = new HashMap();
        if (zcBillInf != null) {
            com.huyi.service.base.entity.SysUser user = iSysUserService.getById(zcBillInf.getCreateBy());
            BeanMap beanMap = BeanMap.create(zcBillInf);
            for (Object key : beanMap.keySet()) {
                map.put(key+"", beanMap.get(key));
            }
            //创建人
            map.put("createUser",user.getNickName());
        }
        return AjaxResult.success(map);
    }

    /**
     * 初始化账款信息
     *
     * @param map    账款信息
     * @return
     */
    @Log(title = "初始化往来账款信息", businessType = BusinessType.UPDATE)
    @PostMapping("/add")
    public R add(@RequestBody Map map) throws ParseException {
        //获取登录用户
        LoginUser user = tokenService.getLoginUser();
        ZcBillInf zcBillInf = new ZcBillInf();
        //账款名称
        String zbiId = CommonUtil.objToString(map.get("zbiId"));
        //账款名称
        String zbiName = CommonUtil.objToString(map.get("zbiName"));
        zcBillInf.setZbiName(zbiName);
        //应付方
        String zbiPayerId = CommonUtil.objToString(map.get("zbiPayerId"));
        zcBillInf.setZbiPayerId(zbiPayerId);
        //应收方
        String zbiPayeeId = CommonUtil.objToString(map.get("zbiPayeeId"));
        zcBillInf.setZbiPayeeId(zbiPayeeId);
        //时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //贸易日期
        String zbiDate = CommonUtil.objToString(map.get("zbiDate"));
        Date date = sdf.parse(zbiDate);
        zcBillInf.setZbiDate(date);
        //预计收付款日期
        String zbiPayDate = CommonUtil.objToString(map.get("zbiPayDate"));
        Date payDate = sdf.parse(zbiPayDate);
        zcBillInf.setZbiPayDate(payDate);
        //贸易金额
        String zbiAmount = CommonUtil.objToString(map.get("zbiAmount"));
        zcBillInf.setZbiAmount(zbiAmount);
        //合同编号
        String zbiContractNo = CommonUtil.objToString(map.get("zbiContractNo"));
        zcBillInf.setZbiContractNo(zbiContractNo);
        //账款服务
        String zbiService = CommonUtil.objToString(map.get("zbiService"));
        zcBillInf.setZbiService(zbiService);
        //配送订单
        String zbiOrderNo = CommonUtil.objToString(map.get("zbiOrderNo"));
        zcBillInf.setZbiOrderNo(zbiOrderNo);
        //配送企业
        String zbiDistributor = CommonUtil.objToString(map.get("zbiDistributor"));
        zcBillInf.setZbiDistributor(zbiDistributor);
        //备注
        String zbiRemark = CommonUtil.objToString(map.get("zbiRemark"));
        zcBillInf.setZbiRemark(zbiRemark);
        //创建人
        zcBillInf.setCreateBy(user.getUserid().toString());
        //创建时间
        zcBillInf.setCreateTime(DateUtils.getNowDate());
        if(CommonUtil.isEmpty(zbiId)){
            //主键
            zbiId = IdUtils.fastSimpleUUID();
            zcBillInf.setZbiId(zbiId);
            //编号
            String number = "ASSET1121" + System.currentTimeMillis();
            zcBillInf.setZbiNumber(number);
            iZcBillInfService.createZcBillInf(zcBillInf);
        }else{
            zcBillInf.setZbiId(zbiId);
            iZcBillInfService.updateZcBillInf(zcBillInf);
        }
        Map res = new HashMap();
        //返回账款id
        res.put("zbiId", zbiId);
        return R.ok(res);
    }

    /**
     * 获取往来账款发票信息
     */
    @GetMapping(value = "getInvoice/{zbiId}")
    public AjaxResult getBillInvoice(@PathVariable("zbiId") String zbiId) {
        //获取用户信息
        LoginUser userInfo = tokenService.getLoginUser();
        //企业id
        String companyId = userInfo.getSysUser().getCompanyId();
        //查询关联往来账款的发票
        LambdaQueryWrapper<ZcBillInvoiceRel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //往来账款id
        lambdaQueryWrapper.eq(ZcBillInvoiceRel::getZbirBillId,zbiId);
        List<ZcBillInvoiceRel> relList = iZcBillInvoiceRelService.findZcBillInvoiceRels(lambdaQueryWrapper);
        List<Map> list = new ArrayList<>();
        for (ZcBillInvoiceRel zcBillInvoiceRel : relList) {
            //查询发票
            ZcInvoiceInf zcInvoiceInf = iZcInvoiceInfService.getById(zcBillInvoiceRel.getZbirInvoiceId());
            Map map = new HashMap();
            if (zcInvoiceInf != null) {
                com.huyi.service.base.entity.PubFileInf pubFileInf = iPubFileInfService.getById(zcInvoiceInf.getZiiFile());
                BeanMap beanMap = BeanMap.create(zcInvoiceInf);
                for (Object key : beanMap.keySet()) {
                    map.put(key+"", beanMap.get(key));
                }
                //文件名称
                map.put("name",pubFileInf.getPfiFileName());
                //文件url
                map.put("url",pubFileInf.getPfiUrl());
                //时间格式化
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String date = sdf.format(map.get("ziiDate"));
                map.put("ziiDate",date);
            }
            list.add(map);
        }
        return AjaxResult.success(list);
    }

    /**
     * 发票识别
     *
     * @param file    文件
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @Log(title = "上传往来账款发票", businessType = BusinessType.INSERT)
    @PostMapping("/getInvoiceText")
    public R getInvoiceText(@RequestParam("file")MultipartFile file, @RequestParam("zbiId") String zbiId) {
        if(CommonUtil.isEmpty(zbiId)){
            R.fail(500,"未获取到要上传发票的账款");
        }
        //获取登录用户
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        //获取发票信息
        ZcInvoiceInf zcInvoiceInf = iOwnBillService.getInvoice(file);
        LambdaQueryWrapper<ZcInvoiceInf> queryWrapper = new LambdaQueryWrapper<>();
        //发票代码
        queryWrapper.eq(ZcInvoiceInf::getZiiNo,zcInvoiceInf.getZiiNo());
        //发票号码
        queryWrapper.eq(ZcInvoiceInf::getZiiNumber,zcInvoiceInf.getZiiNumber());
        //发票状态
        queryWrapper.eq(ZcInvoiceInf::getZiiStatus,"00");
        List<ZcInvoiceInf> list = iZcInvoiceInfService.findZcInvoiceInfs(queryWrapper);
        String id = IdUtils.fastSimpleUUID();
        zcInvoiceInf.setZiiId(id);
        zcInvoiceInf.setZiiCompanyId(companyId);
        zcInvoiceInf.setCreateBy(user.getUserid().toString());
        zcInvoiceInf.setCreateTime(DateUtils.getNowDate());
        //不重复则储存发票并上传
        if(list.size() == 0){
            zcInvoiceInf.setZiiCheckStt("0");
        }else{
            zcInvoiceInf.setZiiCheckStt("3");
        }
        //获取上传文件token
        String token = SecurityUtils.getToken(ServletUtils.getRequest());
        //文件传输
        R<PubFileInf> fileResult = remoteFileService.uploadFile(file,"01","04","00", companyId, token);
        zcInvoiceInf.setZiiFile(fileResult.getData().getPfiFileId());
        //创建发票
        iZcInvoiceInfService.createZcInvoiceInf(zcInvoiceInf);
        //创建账款发票关联
        ZcBillInvoiceRel zcBillInvoiceRel = new ZcBillInvoiceRel();
        zcBillInvoiceRel.setZbirBillId(zbiId);
        zcBillInvoiceRel.setZbirInvoiceId(id);
        iZcBillInvoiceRelService.createZcBillInvoiceRel(zcBillInvoiceRel);
        Map map = new HashMap();
        map.put("name",fileResult.getData().getPfiFileName());
        map.put("url",fileResult.getData().getPfiUrl());
        //将发票对象转换成Map集合重新组合
        if (zcInvoiceInf != null) {
            BeanMap beanMap = BeanMap.create(zcInvoiceInf);
            for (Object key : beanMap.keySet()) {
                map.put(key+"", beanMap.get(key));
            }
            //时间格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date = sdf.format(map.get("ziiDate"));
            map.put("ziiDate",date);
        }

        //返回发票信息
        return R.ok(map);
    }

    /**
     * 重新验真
     *
     * @param fileList    发票信息列表
     * @return
     */
    @SneakyThrows
    @Transactional(rollbackFor=Exception.class)
    @Log(title = "往来账款发票验真", businessType = BusinessType.UPDATE)
    @PostMapping("/invoiceVerification")
    public List<ZcInvoiceInf> invoiceVerification(@RequestParam(required = false,value = "fileList") String fileList) {
        JSONArray jsonArray = JSONArray.parseArray(fileList);
        //获取登录用户
        LoginUser user = tokenService.getLoginUser();
        //默认第二条
        int checkNum = 1;
        //大于3条则获取随机一条
        if(jsonArray.size() > 3){
            Random random = new Random();
            int num = random.nextInt(jsonArray.size());
            //如果不是第一条或最后一条则使用随机数
            if(num != 0 && num != (jsonArray.size() - 1)){
                checkNum = num;
            }
        }
        List<ZcInvoiceInf> zcInvoiceInfs = new ArrayList<>();
        //批量验真
        for (int i = 0; i < jsonArray.size(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            ZcInvoiceInf zcInvoiceInf = iZcInvoiceInfService.getById(jsonObject.getString("ziiId"));

            LambdaQueryWrapper<ZcInvoiceInf> queryWrapper = new LambdaQueryWrapper<>();
            //时间格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            //发票代码
            String ziiNo = jsonObject.getString("ziiNo");
            //发票号码
            String ziiNumber = jsonObject.getString("ziiNumber");
            //发票日期
            String ziiDate = jsonObject.getString("ziiDate");
            //购方纳税人识别号
            String ziiPurchaserNo = jsonObject.getString("ziiPurchaserNo");
            //销方纳税人识别号
            String ziiSellerNo = jsonObject.getString("ziiSellerNo");
            //发票金额
            String ziiAmount = jsonObject.getString("ziiAmount");
            //价税合计
            String ziiTotalAmount = jsonObject.getString("ziiTotalAmount");
            queryWrapper.eq(ZcInvoiceInf::getZiiNo,ziiNo);
            //发票号码
            queryWrapper.eq(ZcInvoiceInf::getZiiNumber,ziiNumber);
            //发票主键
            queryWrapper.ne(ZcInvoiceInf::getZiiId,jsonObject.getString("ziiId"));
            //发票状态
            queryWrapper.eq(ZcInvoiceInf::getZiiStatus,"00");
            List<ZcInvoiceInf> list = iZcInvoiceInfService.findZcInvoiceInfs(queryWrapper);
            //不重复则储存发票并上传
            if(list.size() == 0){
                if(i != 0 && i != (jsonArray.size() - 1) && i != checkNum){
                    //没有验真的默认成功
                    zcInvoiceInf.setZiiCheckStt("1");
                }else{
                    //验真发票
                    zcInvoiceInf = iOwnBillService.invoiceVerification(zcInvoiceInf);
                }
            }else{
                zcInvoiceInf.setZiiCheckStt("3");
            }
            zcInvoiceInf.setZiiNo(ziiNo);
            zcInvoiceInf.setZiiNumber(ziiNumber);
            zcInvoiceInf.setZiiDate(sdf.parse(ziiDate));
            zcInvoiceInf.setZiiPurchaserNo(ziiPurchaserNo);
            zcInvoiceInf.setZiiSellerNo(ziiSellerNo);
            zcInvoiceInf.setZiiAmount(ziiAmount);
            zcInvoiceInf.setZiiExcludedAmount(ziiAmount);
            zcInvoiceInf.setZiiTotalAmount(ziiTotalAmount);
            zcInvoiceInf.setUpdateBy(user.getUserid().toString());
            zcInvoiceInf.setUpdateTime(DateUtils.getNowDate());
            //修改发票信息
            iZcInvoiceInfService.updateZcInvoiceInf(zcInvoiceInf);
            zcInvoiceInfs.add(zcInvoiceInf);
        }
        return zcInvoiceInfs;
    }

    /**
     * 删除发票
     *
     * @param ziiIds    发票id集合
     * @return
     */
    @SneakyThrows
    @Transactional(rollbackFor=Exception.class)
    @Log(title = "删除往来账款发票", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ziiIds}")
    public R delete(@PathVariable("ziiIds") String[] ziiIds) {
        //获取登录用户
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        //获取上传文件token
        String token = SecurityUtils.getToken(ServletUtils.getRequest());
        for (String ziiId : ziiIds) {
            ZcInvoiceInf zcInvoiceInf = iZcInvoiceInfService.getById(ziiId);
            zcInvoiceInf.setZiiStatus("99");
            //删除发票
            iZcInvoiceInfService.updateZcInvoiceInf(zcInvoiceInf);
            LambdaQueryWrapper<ZcBillInvoiceRel> queryWrapper = new LambdaQueryWrapper<>();
            //发票id
            queryWrapper.eq(ZcBillInvoiceRel::getZbirInvoiceId, ziiId);
            //删除发票关联
            iZcBillInvoiceRelService.deleteZcBillInvoiceRel(queryWrapper);
            //删除附件
            remoteFileService.delete(zcInvoiceInf.getZiiFile(), companyId, token);
        }
        return R.ok();
    }

    /**
     * 上传合同物流附件
     *
     * @param file    文件
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @Log(title = "上传往来账款附件", businessType = BusinessType.INSERT)
    @PostMapping("/uploadBillFile")
    public R uploadBillFile(@RequestParam("file")MultipartFile file, @RequestParam("zbiId") String zbiId, @RequestParam("type") String type) {
        if(CommonUtil.isEmpty(zbiId)){
            R.fail(500,"未获取到要上传发票的账款");
        }
        //获取登录用户
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        //获取上传文件token
        String token = SecurityUtils.getToken(ServletUtils.getRequest());
        //文件传输
        R<PubFileInf> fileResult = remoteFileService.uploadFile(file,"01","04","00", companyId, token);
        //创建账款附件关联
        ZcBillFileRel zcBillFileRel = new ZcBillFileRel();
        zcBillFileRel.setZbfrBillId(zbiId);
        zcBillFileRel.setZbfrFileId(fileResult.getData().getPfiFileId());
        zcBillFileRel.setZbfrType(type);
        iZcBillFileRelService.createZcBillFileRel(zcBillFileRel);
        Map map = new HashMap();
        map.put("id",fileResult.getData().getPfiFileId());
        map.put("name",fileResult.getData().getPfiFileName());
        map.put("url",fileResult.getData().getPfiUrl());
        //返回附件信息
        return R.ok(map);
    }

    /**
     * 获取往来账款附件信息
     */
    @GetMapping(value = "getFile/{type}/{zbiId}")
    public AjaxResult getFile(@PathVariable("type") String type, @PathVariable("zbiId") String zbiId) {
        //获取用户信息
        LoginUser userInfo = tokenService.getLoginUser();
        //企业id
        String companyId = userInfo.getSysUser().getCompanyId();
        //查询关联往来账款的发票
        LambdaQueryWrapper<ZcBillFileRel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //往来账款id
        lambdaQueryWrapper.eq(ZcBillFileRel::getZbfrBillId,zbiId);
        //附件类型
        lambdaQueryWrapper.eq(ZcBillFileRel::getZbfrType,type);
        List<ZcBillFileRel> relList = iZcBillFileRelService.findZcBillFileRels(lambdaQueryWrapper);
        List<Map> list = new ArrayList<>();
        for (ZcBillFileRel zcBillFileRel : relList) {
            //查询发票
            Map map = new HashMap();
            com.huyi.service.base.entity.PubFileInf pubFileInf = iPubFileInfService.getById(zcBillFileRel.getZbfrFileId());
            //文件id
            map.put("id",zcBillFileRel.getZbfrFileId());
            //文件名称
            map.put("name",pubFileInf.getPfiFileName());
            //文件url
            map.put("url",pubFileInf.getPfiUrl());
            list.add(map);
        }
        return AjaxResult.success(list);
    }

    /**
     * 删除附件
     *
     * @param ids    发票id集合
     * @return
     */
    @SneakyThrows
    @Transactional(rollbackFor=Exception.class)
    @Log(title = "删除往来账款附件", businessType = BusinessType.DELETE)
    @DeleteMapping("delFile/{ids}")
    public R delFile(@PathVariable("ids") String[] ids) {
        //获取登录用户
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        //获取上传文件token
        String token = SecurityUtils.getToken(ServletUtils.getRequest());
        for (String id : ids) {
            LambdaQueryWrapper<ZcBillFileRel> queryWrapper = new LambdaQueryWrapper<>();
            //附件id
            queryWrapper.eq(ZcBillFileRel::getZbfrFileId, id);
            //删除附件关联
            iZcBillFileRelService.deleteZcBillFileRel(queryWrapper);
            //删除附件
            remoteFileService.delete(id, companyId, token);
        }
        return R.ok();
    }

    /**
     * 提交账款信息
     *
     * @param zbiId    账款id
     * @return
     */
    @PostMapping("/commitBill/{zbiId}")
    @Log(title = "提交往来账款信息", businessType = BusinessType.UPDATE)
    public R commitBill(@PathVariable("zbiId") String zbiId) throws ParseException {
        //获取登录用户
        LoginUser user = tokenService.getLoginUser();
        ZcBillInf zcBillInf = new ZcBillInf();
        zcBillInf.setZbiId(zbiId);
        //创建人
        zcBillInf.setUpdateBy(user.getUserid().toString());
        //创建时间
        zcBillInf.setUpdateTime(DateUtils.getNowDate());
        //修改为正常状态
        zcBillInf.setZbiStatus("00");
        iZcBillInfService.updateZcBillInf(zcBillInf);
        return R.ok();
    }

    /**
     * 删除往来账款信息
     *
     * @param zbiIds    往来账款id集合
     * @return
     */
    @SneakyThrows
    @PreAuthorize(hasPermi = "service:bill:del")
    @Transactional(rollbackFor=Exception.class)
    @Log(title = "删除往来账款信息", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteBill/{zbiIds}")
    public R deleteBill(@PathVariable("zbiIds") String[] zbiIds) {
        //获取登录用户
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        //获取上传文件token
        String token = SecurityUtils.getToken(ServletUtils.getRequest());
        for (String zbiId : zbiIds) {
            ZcBillInf zcBillInf = iZcBillInfService.getById(zbiId);
            zcBillInf.setZbiStatus("99");
            zcBillInf.setUpdateBy(user.getUserid().toString());
            zcBillInf.setUpdateTime(DateUtils.getNowDate());
            //删除往来账款
            iZcBillInfService.updateZcBillInf(zcBillInf);

            LambdaQueryWrapper<ZcBillFileRel> queryWrapper = new LambdaQueryWrapper<>();
            //往来账款id
            queryWrapper.eq(ZcBillFileRel::getZbfrBillId, zbiId);
            List<ZcBillFileRel> billFileRels = iZcBillFileRelService.findZcBillFileRels(queryWrapper);
            for (ZcBillFileRel zcBillFileRel : billFileRels) {
                //删除附件
                remoteFileService.delete(zcBillFileRel.getZbfrFileId(), companyId, token);
            }
            //删除附件关联
            iZcBillFileRelService.deleteZcBillFileRel(queryWrapper);

            LambdaQueryWrapper<ZcBillInvoiceRel> queryWrapperInvoice = new LambdaQueryWrapper<>();
            //往来账款id
            queryWrapperInvoice.eq(ZcBillInvoiceRel::getZbirBillId, zbiId);
            List<ZcBillInvoiceRel>  billInvoiceRels = iZcBillInvoiceRelService.findZcBillInvoiceRels(queryWrapperInvoice);
            for (ZcBillInvoiceRel zcBillInvoiceRel : billInvoiceRels) {
                ZcInvoiceInf zcInvoiceInf = iZcInvoiceInfService.getById(zcBillInvoiceRel.getZbirInvoiceId());
                zcInvoiceInf.setZiiStatus("99");
                //删除发票
                iZcInvoiceInfService.updateZcInvoiceInf(zcInvoiceInf);
                //删除附件
                remoteFileService.delete(zcInvoiceInf.getZiiFile(), companyId, token);
            }
            //删除发票关联
            iZcBillInvoiceRelService.deleteZcBillInvoiceRel(queryWrapperInvoice);
        }
        return R.ok();
    }

}
