package com.huyi.service.credit.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huyi.service.base.entity.*;
import com.huyi.service.base.service.*;
import com.huyi.service.credit.service.OwnCreditService;
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.domain.SysUser;
import com.tianhu.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 融信信息
 * xuefy
 * 2021-08-17
 */
@RestController
@RequestMapping("/ownCredit")
public class OwnCreditController extends BaseController {
    @Autowired
    private TokenService tokenService;
    //自写融信服务类
    @Autowired
    private OwnCreditService    ownCreditService;
    //核心授信服务类
    @Autowired
    private IZcFinanceProComRelService financeProComRelService;
    //融信应收付关系的服务类
    @Autowired
    private IZcFinanceBillRelService    financeBillRelService;
    //融信应收付关系的服务类
    @Autowired
    private IZcFinanceInfService    financeInfService;
    //供应商授信服务类
    @Autowired
    private IZcFinanceSupplierQuotaService financeSupplierQuotaService;
    //用户服务类
    @Autowired
    private ISysUserService     sysUserService;
    //公司服务类
    @Autowired
    private ISysCompanyService companyService;
    //产品服务类
    @Autowired
    private IZcFinanceProductService productService;


    /**
     * 查询融信信息
     * @param zfiNumber
     * @param zfiStatus
     * @param openCompany
     * @param receiveCompany
     * @param zfpName
     * @param zfiSignDate
     * @param zfiExpireDate
     * @param zfiRate
     * @param request
     * @return
     */

    @PreAuthorize(hasPermi = "credit:credit:list")
    @GetMapping("/list")
    public R list(
                  @RequestParam(required=false) String zfiNumber,
                  @RequestParam(required=false) String zfiStatus,
                  @RequestParam(required=false) String openCompany,
                  @RequestParam(required=false) String receiveCompany,
                  @RequestParam(required=false) String zfpName,
                  @RequestParam(required=false) String startAmt,
                  @RequestParam(required=false) String endAmt,
                  @RequestParam(required=false) Map zfiSignDate,
                  @RequestParam(required=false) Map zfiExpireDate,
                  @RequestParam(required=false) String zfiRate,
                  QueryRequest request) {
        //查询当前操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取企业
        String companyId = use.getCompanyId();
        Map map = new HashMap();
        /*if (!SalaryConstants.OPEX.equals(companyId)) {
            map.put("ziiCompanyId", companyId);
        }*/
        //融信编号
        map.put("zfiNumber", zfiNumber);
        //状态
        map.put("zfiStatus", zfiStatus);
        //开立企业
        map.put("openCompany", openCompany);
        //接收企业
        map.put("receiveCompany", receiveCompany);
        //融资产品
        map.put("zfpName",zfpName);
        //利率
        map.put("zfiRate",CommonUtil.objToBigDecimal(zfiRate));
        //签收日期
        map.put("startTime",zfiSignDate.get("zfiSignDate[0]"));
        map.put("endTime",zfiSignDate.get("zfiSignDate[1]"));
        //承诺还款日
        map.put("zfiExpireDateStart",zfiExpireDate.get("zfiExpireDate[0]"));
        map.put("zfiExpireDateEnd",zfiExpireDate.get("zfiExpireDate[1]"));
        if(!CommonUtil.isEmpty(startAmt)){
            if(!AmtUtil.isMoney(startAmt)){
                return R.fail("请输入正确的融信金额开始范围值");
            }
            if(CommonUtil.isEmpty(endAmt)){
                return R.fail("请输入融信金额的结束范围值");

            }
        }
        if(!CommonUtil.isEmpty(endAmt)){
            if(CommonUtil.isEmpty(startAmt)){
                map.put("startAmt","0");
            }
        }
        //合同金额结束范围
        if(!CommonUtil.isEmpty(endAmt)){
            if(!AmtUtil.isMoney(endAmt)){
                return R.fail("请输入正确的融信金额结束范围值");
            }

        }
        if(!CommonUtil.isEmpty(startAmt) && !CommonUtil.isEmpty(endAmt)){
            if(CommonUtil.compare(startAmt,endAmt) == 1){
                return R.fail("融信金额范围输入有误");
            }
        }

        map.put("startAmt",CommonUtil.objToBigDecimal(startAmt));
        map.put("endAmt",CommonUtil.objToBigDecimal(endAmt));
        //获取企业类型
        String companyType =  use.getCompanyType();
        IPage<Map> list = ownCreditService.selectCreditList(map,request);
        return R.ok(list);
    }

    /**
     * 获取融信详情
     * @param zfiId
     * @return
     */
    @PreAuthorize(hasPermi = "credit:credit:query")
    @GetMapping(value = "/{zfiId}")
    public AjaxResult getInfo(@PathVariable("zfiId") String zfiId,QueryRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //查询融信详情
        ZcFinanceInf financeInf =  financeInfService.getById(zfiId);
        if(financeInf == null){
            return AjaxResult.error("获取融信信息失败");
        }
        //查询创建人
        String userId = financeInf.getCreateBy();
        com.huyi.service.base.entity.SysUser user =  sysUserService.getById(userId);
        String createName = "";
        Map map = new HashMap();
        if(user != null){
           createName = user.getNickName();
        }
        //创建人
        map.put("createName",createName);
        //融信
        map.put("financeInf",financeInf);
        //接收方
        String zfiSupplierId = financeInf.getZfiSupplierId();
        SysCompany company =  companyService.getById(zfiSupplierId);
        String receiveName = "";
        if(company != null){
            receiveName = company.getScyName();
        }
        map.put("receiveName",receiveName);
        //开立方
        String zfiCoreId = financeInf.getZfiCoreId();
        SysCompany coreCompany =  companyService.getById(zfiCoreId);
        String openName = "";
        if(coreCompany != null){
            openName = coreCompany.getScyName();
        }
        map.put("openName",openName);
        //产品
        String productId = financeInf.getZfiProductId();
        ZcFinanceProduct product =   productService.getById(productId);
        String zfpName = "";
        if(product != null){
            zfpName = product.getZfpName();
        }
        map.put("zfpName",zfpName);
        //获取核心授信额度信息
        String zfiCoreQuotaId = financeInf.getZfiCoreQuotaId();
        ZcFinanceProComRel proComRel = financeProComRelService.getById(zfiCoreQuotaId);
        map.put("proComRel",proComRel);
        //查询该融信下关联的应收付款
        LambdaQueryWrapper<ZcFinanceBillRel> relLambdaQueryWrapper = new LambdaQueryWrapper<>();
        relLambdaQueryWrapper.eq(ZcFinanceBillRel::getZfbrFinanceId,zfiId);
        List<ZcFinanceBillRel>   relList =  financeBillRelService.findZcFinanceBillRels(relLambdaQueryWrapper);
        if(relList.size() > 0 ){
            //提取应收付款的编号
            List<String> payIdList = CommonUtil.getIdFromList(relList,"zfbrBillId");
            Map p = new HashMap();
            p.put("payIdList",CommonUtil.listToStr4InSql(payIdList));
            IPage<Map> payList = ownCreditService.getAccountsPay(p,request);
            map.put("payList",payList);
        }
        return AjaxResult.success(map);
    }

    /**
     * 修改融信
     * @param map
     * @return
     * @throws Exception
     */
    @PreAuthorize(hasPermi = "credit:credit:update")
    @Log(title = "融信管理", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> map)  throws Exception{
        //获取此操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser user = userInfo.getSysUser();
        //获取用户编号
        String userId = user.getUserId()+"";
        //获取融信编号
        String id = CommonUtil.objToString(map.get("zfiId"));
        //获取融信的类型
        String type = CommonUtil.objToString(map.get("type"));
        //获取产品是否可拆分
        String zfpSplit = CommonUtil.objToString(map.get("zfpSplit"));
        //获取放款方式
        String zfpcrLoanType = CommonUtil.objToString(map.get("zfpcrLoanType"));
        //融信编号
        String  str = "";
        //判断类型
        //开立
        if("1".equals(type) || "2".equals(type)){
            str = "CM";
        }else if("0".equals(type)){
            //申请
            str = "SM";
        }
        //产品不可拆分
        if("0".equals(zfpSplit)){
            str += "D";
        }else if("1".equals(zfpSplit)){
            //可拆分
            str += "R";
        }
        //放款方式--供应商
        if("0".equals(zfpcrLoanType)){
            str += "P";
        }else if("1".equals(zfpcrLoanType)){
            //平台电子记账
            str += "E";
        }

        ZcFinanceInf inf = new ZcFinanceInf();
        //主键
        inf.setZfiId(id);
        //非开立
        if(!"0".equals(type)){
            //获取之前的融信编号
            String zfiNumber = CommonUtil.objToString(map.get("zfiNumber"));
            //获取之前融信编号的时间戳
            String time = zfiNumber.substring(5);
            str += time;
            //融信编号
            inf.setZfiNumber(str);
        }
        //获取申请金额
        String zfiAmount = CommonUtil.objToString(map.get("zfiAmount"));
        inf.setZfiAmount(zfiAmount);
        if(CommonUtil.isEmpty(zfiAmount)){
            throw new Exception("请输入申请金额");
        }
        if(!AmtUtil.isMoney(zfiAmount)){
            throw new Exception("请输入正确的申请金额");
        }
        //非供应商申请
        if(!"0".equals(type)){
            //承诺付款日
            String zfiExpireDate = CommonUtil.objToString(map.get("zfiExpireDate"));
            //签发有效期
            String zfiEffectiveDate = CommonUtil.objToString(map.get("zfiEffectiveDate"));
            if(CommonUtil.isEmpty(zfiEffectiveDate)){
                throw new Exception("请选择签发有效期");
            }
            if(CommonUtil.isEmpty(zfiExpireDate)){
                throw new Exception("请选择承诺付款日");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(zfiEffectiveDate);
            inf.setZfiEffectiveDate(date);
            Date signDate = simpleDateFormat.parse(zfiExpireDate);
            inf.setZfiExpireDate(signDate);
        }
        //修改人
        inf.setUpdateBy(userId);
        //修改时间
        inf.setUpdateTime(DateUtils.getNowDate());
        //获取产品
        String productId  = CommonUtil.objToString(map.get("zfpId"));
        inf.setZfiProductId(productId);
        //获取收付款
        List<Map<String,String>> ticketList = (List<Map<String, String>>) map.get("ticketList");
        if("1".equals(type)){
            //核心企业授信额度
            String zfiCoreQuotaId = CommonUtil.objToString(map.get("zfiCoreQuotaId"));
            inf.setZfiCoreQuotaId(zfiCoreQuotaId);
            //接收企业
            String zfiSupplierId = CommonUtil.objToString(map.get("zfiSupplierId"));
            inf.setZfiSupplierId(zfiSupplierId);
            //选择
            if(ticketList.size() > 1){
                //获取第一个应收企业
                String receiveName = ticketList.get(0).get("receiveName");
                //获取预计还款日期
                String zbiPayDate = ticketList.get(0).get("zbiPayDate");
                for(int i = 0 ; i < ticketList.size();i++){
                    if(!receiveName.equals(ticketList.get(i).get("receiveName"))){
                        throw new Exception("请选择应收企业相同的应付账款");
                    }
                    if(!zbiPayDate.equals(ticketList.get(i).get("zbiPayDate"))){
                        throw new Exception("请选择预计还款日期相同的应付账款");
                    }
                }

            }
        }else if("0".equals(type) || "2".equals(type)){//供应商开立/申请
            //获取可用额度
            String availableAmt = CommonUtil.objToString(map.get("availableAmt"));
            //获取合计金额
            String checkTotalAmt = CommonUtil.objToString(map.get("checkTotalAmt"));
            //供应商开立
            if("2".equals(type)){
                if(CommonUtil.compare(zfiAmount,availableAmt) == 1){
                    throw new Exception("签发金额不可大于可用额度");
                }
                //供应商企业授信额度
                String zfiSupplierQuotaId = CommonUtil.objToString(map.get("zfiSupplierQuotaId"));
                inf.setZfiSupplierQuotaId(zfiSupplierQuotaId);
                //获取供应商对应的核心授信额度
                ZcFinanceSupplierQuota  supplierQuota = financeSupplierQuotaService.getById(zfiSupplierQuotaId);
                if(supplierQuota == null){
                    throw new Exception("获取供应商授信额度失败");
                }
                String zfsqCoreQuotaId = supplierQuota.getZfsqCoreQuotaId();
                //核心授信额度
                inf.setZfiCoreQuotaId(zfsqCoreQuotaId);
                //获取收款账号
                String zfiCollectionAccount = CommonUtil.objToString(map.get("zfiCollectionAccount"));
                //获取放款方式--供应商指定的话为收款账号必输
                if("1".equals(zfpcrLoanType)){
                    if(CommonUtil.isEmpty(zfiCollectionAccount)){
                        throw new Exception("请输入收款账号");
                    }
                }
                //非电子
                if(!"0".equals(zfpcrLoanType)){
                    inf.setZfiCollectionAccount(zfiCollectionAccount);
                }
            }
            if(CommonUtil.compare(zfiAmount,checkTotalAmt) == 1){
                throw new Exception("签发金额不可大于合计金额");
            }
            if(ticketList.size() < 1){
                throw new Exception("请选择应收账款");
            }else if(ticketList.size() > 1){
                //获取第一个应付企业
                String payName = ticketList.get(0).get("payName");
                //获取预计还款日期
                String zbiPayDate = ticketList.get(0).get("zbiPayDate");
                for(int i = 0 ; i < ticketList.size();i++){
                    if(!payName.equals(ticketList.get(i).get("payName"))){
                        throw new Exception("请选择应付企业相同的应收账款");
                    }
                    if(!zbiPayDate.equals(ticketList.get(i).get("zbiPayDate"))){
                        throw new Exception("请选择预计还款日期相同的应收账款");
                    }
                }

            }
            //开立方==应付企业
            inf.setZfiCoreId(ticketList.get(0).get("zbiPayerId"));
        }
        //利率
        String zfiRate = CommonUtil.objToString(map.get("zfiRate"));
        inf.setZfiRate(zfiRate);
        //先删除该融信与应收付款的关系
        LambdaQueryWrapper<ZcFinanceBillRel> relLambdaQueryWrapper = new LambdaQueryWrapper<>();
        relLambdaQueryWrapper.eq(ZcFinanceBillRel::getZfbrFinanceId,id);
        financeBillRelService.deleteZcFinanceBillRel(relLambdaQueryWrapper);

        //插入融信和应收付款的关系
        for(int i = 0 ; i < ticketList.size();i++){
            //获取收付款编号
            String billId = ticketList.get(i).get("zbiId");
            ZcFinanceBillRel  rel = new ZcFinanceBillRel();
            rel.setZfbrFinanceId(id);
            rel.setZfbrBillId(billId);
            financeBillRelService.createZcFinanceBillRel(rel);
        }
        //修改数据
        financeInfService.updateById(inf);
        return AjaxResult.success();
    }





    /**
     * 查询核心开立授信额度
     * @param zfpcrId
     * @return
     */
    @GetMapping("/getCreditLineList")
    public AjaxResult getCreditLineList(@RequestParam(required=false) String zfpcrId,
                                        @RequestParam(required=false) String type)
    {
        //获取当前企业的编号
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        Map<String,String> map = new HashMap<>();
        //获取企业
        String companyId = use.getCompanyId();
        if (!SalaryConstants.OPEX.equals(companyId)) {
            map.put("zfpcrCompanyId", companyId);
        }
        //授信额度编号
        map.put("zfpcrId",zfpcrId);
        //类型--1查询反向产品  0 查询正向产品
        map.put("type",type);
        List<Map>  creditLineList =  ownCreditService.selectCreditLineList(map);
        return AjaxResult.success(creditLineList);
    }

    /**
     * 获取供应商授信额度
     * @param zfsqId
     * @return
     */
    @GetMapping("/getSupplierCreditLineList")
    public AjaxResult getSupplierCreditLineList(@RequestParam(required=false) String zfsqId)
    {
        //获取当前企业的编号
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        Map<String,String> map = new HashMap<>();
        //获取企业
        String companyId = use.getCompanyId();
        map.put("zfsqCompanyId", companyId);
        //授信额度编号
        map.put("zfsqId",zfsqId);

        List<Map>  creditLineList =  ownCreditService.selectSupplierCreditLineList(map);
        return AjaxResult.success(creditLineList);
    }

    /**
     * 融信开立
     * @param map
     * @return
     * @throws Exception
     */
    @PreAuthorize(hasPermi = "credit:credit:add")
    @Log(title = "融信开立", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> map)throws Exception
    {
        //获取收付款
        List<Map<String,String>> ticketList = (List<Map<String, String>>) map.get("ticketList");
        //获取融信的类型
        String type = CommonUtil.objToString(map.get("type"));
        //获取此操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser user = userInfo.getSysUser();
        //获取用户编号
        String userId = user.getUserId()+"";
        //获取企业
        String companyId = user.getCompanyId();
        //主键
        String id = IdUtils.fastSimpleUUID();
        //获取创建时间
        Date  createTime =  DateUtils.getNowDate();
        //获取当前时间
        String currentTime = DateUtils.parseDateToStr("yyyyMMddHHmmss",createTime);
        //获取产品是否可拆分
        String zfpSplit = CommonUtil.objToString(map.get("zfpSplit"));
        //获取放款方式
        String zfpcrLoanType = CommonUtil.objToString(map.get("zfpcrLoanType"));
        //融信编号
        String  str = "";
        //判断类型
        //开立
        if("1".equals(type) || "2".equals(type)){
            str = "CM";
        }else if("0".equals(type)){
            //申请
            str = "SM";
        }
        //产品不可拆分
        if("0".equals(zfpSplit)){
            str += "D";
        }else if("1".equals(zfpSplit)){
            //可拆分
            str += "R";
        }
        //放款方式--供应商
        if("0".equals(zfpcrLoanType)){
            str += "P";
        }else if("1".equals(zfpcrLoanType)){
            //平台电子记账
            str += "E";
        }
        str = str + currentTime;
        ZcFinanceInf inf = new ZcFinanceInf();
        //主键
        inf.setZfiId(id);
        //融信编号--申请
        if("0".equals(type)){
            inf.setZfiNumber(currentTime);
        }else{//开立
            inf.setZfiNumber(str);
        }
        //创建类型--  0供应商申请 1核心开立 2供应商开立
        inf.setZfiCreateType(type);
        //获取申请金额
        String zfiAmount = CommonUtil.objToString(map.get("zfiAmount"));
        inf.setZfiAmount(zfiAmount);
        if(CommonUtil.isEmpty(zfiAmount)){
            throw new Exception("请输入申请金额");
        }
        if(!AmtUtil.isMoney(zfiAmount)){
            throw new Exception("请输入正确的申请金额");
        }
        //非供应商申请
        if(!"0".equals(type)){
            //承诺付款日
            String zfiExpireDate = CommonUtil.objToString(map.get("zfiExpireDate"));
            //签发有效期
            String zfiEffectiveDate = CommonUtil.objToString(map.get("zfiEffectiveDate"));
            if(CommonUtil.isEmpty(zfiEffectiveDate)){
                throw new Exception("请选择签发有效期");
            }
            if(CommonUtil.isEmpty(zfiExpireDate)){
                throw new Exception("请选择承诺付款日");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(zfiEffectiveDate);
            inf.setZfiEffectiveDate(date);
            Date signDate = simpleDateFormat.parse(zfiExpireDate);
            inf.setZfiExpireDate(signDate);
        }

        //融信状态
        inf.setZfiStatus("");
        //创建人
        inf.setCreateBy(userId);
        //创建时间
        inf.setCreateTime(createTime);
        //获取产品
        String productId  = CommonUtil.objToString(map.get("zfpId"));
        inf.setZfiProductId(productId);
        //利率
        String zfiRate = CommonUtil.objToString(map.get("zfiRate"));
        inf.setZfiRate(zfiRate);
        //核心开立
        if("1".equals(type)){
            //接收企业
            String zfiSupplierId = CommonUtil.objToString(map.get("zfiSupplierId"));
            inf.setZfiSupplierId(zfiSupplierId);
            //开立企业
            inf.setZfiCoreId(companyId);
            //核心企业授信额度
            String zfiCoreQuotaId = CommonUtil.objToString(map.get("zfiCoreQuotaId"));
            inf.setZfiCoreQuotaId(zfiCoreQuotaId);
            //选择
            if(ticketList.size() > 1){
                //获取第一个应收企业
                String receiveName = ticketList.get(0).get("receiveName");
                //获取预计还款日期
                String zbiPayDate = ticketList.get(0).get("zbiPayDate");
                for(int i = 0 ; i < ticketList.size();i++){
                    if(!receiveName.equals(ticketList.get(i).get("receiveName"))){
                        throw new Exception("请选择应收企业相同的应付账款");
                    }
                    if(!zbiPayDate.equals(ticketList.get(i).get("zbiPayDate"))){
                        throw new Exception("请选择预计还款日期相同的应付账款");
                    }
                }

            }
        }else if("0".equals(type) || "2".equals(type)){//供应商开立/申请
            //获取可用额度
            String availableAmt = CommonUtil.objToString(map.get("availableAmt"));
            //获取合计金额
            String checkTotalAmt = CommonUtil.objToString(map.get("checkTotalAmt"));
            //供应商开立
            if("2".equals(type)){
                if(CommonUtil.compare(zfiAmount,availableAmt) == 1){
                    throw new Exception("签发金额不可大于可用额度");
                }
                //供应商企业授信额度
                String zfiSupplierQuotaId = CommonUtil.objToString(map.get("zfiSupplierQuotaId"));
                inf.setZfiSupplierQuotaId(zfiSupplierQuotaId);
                //获取供应商对应的核心授信额度
                ZcFinanceSupplierQuota  supplierQuota = financeSupplierQuotaService.getById(zfiSupplierQuotaId);
                if(supplierQuota == null){
                    throw new Exception("获取供应商授信额度失败");
                }
                String zfsqCoreQuotaId = supplierQuota.getZfsqCoreQuotaId();
                //核心授信额度
                inf.setZfiCoreQuotaId(zfsqCoreQuotaId);
                //获取收款账号
                String zfiCollectionAccount = CommonUtil.objToString(map.get("zfiCollectionAccount"));
                //获取放款方式--供应商指定的话为收款账号必输
                if("1".equals(zfpcrLoanType)){
                    if(CommonUtil.isEmpty(zfiCollectionAccount)){
                        throw new Exception("请输入收款账号");
                    }
                }
                //非电子
                if(!"0".equals(zfpcrLoanType)){
                    inf.setZfiCollectionAccount(zfiCollectionAccount);
                }
            }
            if(CommonUtil.compare(zfiAmount,checkTotalAmt) == 1){
                throw new Exception("签发金额不可大于合计金额");
            }
            if(ticketList.size() < 1){
                throw new Exception("请选择应收账款");
            }else if(ticketList.size() > 1){
                    //获取第一个应付企业
                    String payName = ticketList.get(0).get("payName");
                    //获取预计还款日期
                    String zbiPayDate = ticketList.get(0).get("zbiPayDate");
                    for(int i = 0 ; i < ticketList.size();i++){
                        if(!payName.equals(ticketList.get(i).get("payName"))){
                            throw new Exception("请选择应付企业相同的应收账款");
                        }
                        if(!zbiPayDate.equals(ticketList.get(i).get("zbiPayDate"))){
                            throw new Exception("请选择预计还款日期相同的应收账款");
                        }
                    }

                }
            //开立方==应付企业
            inf.setZfiCoreId(ticketList.get(0).get("zbiPayerId"));
            //接收方 ==本公司
            inf.setZfiSupplierId(companyId);
        }
        //插入融信和应收付款的关系
        for(int i = 0 ; i < ticketList.size();i++){
            //获取收付款编号
            String billId = ticketList.get(i).get("zbiId");
            ZcFinanceBillRel  rel = new ZcFinanceBillRel();
                rel.setZfbrFinanceId(id);
                rel.setZfbrBillId(billId);
            financeBillRelService.createZcFinanceBillRel(rel);
         }
        //插入数据
        financeInfService.createZcFinanceInf(inf);
        return AjaxResult.success();
    }




    /**
     * 获取核心开立接收方
     * @param zfiSupplierId
     * @return
     */
    @GetMapping("/getReceiverList")
    public AjaxResult getReceiverList(@RequestParam(required=false) String zfiSupplierId, QueryRequest request)
    {
        //获取当前企业的编号
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取当前公司
        String companyId = use.getCompanyId();
        Map<String,String> map = new HashMap<>();
        map.put("companyId",companyId);
        map.put("zfiSupplierId",zfiSupplierId);
        IPage<Map>  companyList =  ownCreditService.getReceiverList(map,request);
        return AjaxResult.success(companyList);
    }

    /**
     * 核心开立查询应付账款
     * @return
     */
    @GetMapping("/getAccountsPay")
    public AjaxResult getAccountsPay(@RequestParam(required=false) String zbiName,
                                     @RequestParam(required=false) String receiveName,
                                     QueryRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //获取当前企业的编号
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //查询融信已关联应付账款
        LambdaQueryWrapper<ZcFinanceBillRel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<ZcFinanceBillRel>  relList =  financeBillRelService.findZcFinanceBillRels(lambdaQueryWrapper);
        Map<String,String> map = new HashMap<>();
        if(relList.size() > 0){
            //提取所有的
            List<String>  billIdList = CommonUtil.getIdFromList(relList,"zfbrBillId");
            map.put("billIdList",CommonUtil.listToStr4InSql(billIdList));
        }
        //获取公司编号
        String companyId = use.getCompanyId();
        map.put("zbiPayerId",companyId);
        //账款名称
        map.put("zbiName",zbiName);
        //应收企业
        map.put("receiveName",receiveName);
        IPage<Map> payList = ownCreditService.getAccountsPay(map,request);
        return AjaxResult.success(payList);
    }


    /**
     *
     *融资开立查询应收账款
     * @param zbiName
     * @param payName
     * @param request
     * @return
     */
    @GetMapping("/getAccountsCollection")
    public AjaxResult getAccountsCollection(@RequestParam(required=false) String zbiName,
                                     @RequestParam(required=false) String payName,
                                     QueryRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //获取当前企业的编号
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取公司编号
        String companyId = use.getCompanyId();
        Map<String,String> map = new HashMap<>();
        //查询融信已关联应付账款
        LambdaQueryWrapper<ZcFinanceBillRel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<ZcFinanceBillRel>  relList =  financeBillRelService.findZcFinanceBillRels(lambdaQueryWrapper);
        if(relList.size() > 0){
            //提取所有的
            List<String>  billIdList = CommonUtil.getIdFromList(relList,"zfbrBillId");
            map.put("billIdList",CommonUtil.listToStr4InSql(billIdList));
        }
        //应收企业
        map.put("zbiPayeeId",companyId);
        //账款名称
        map.put("zbiName",zbiName);
        //应付企业
        map.put("payName",payName);
        IPage<Map> collectionList = ownCreditService.getAccountsCollection(map,request);
        return AjaxResult.success(collectionList);
    }

    /**
     * 核心开立获取可用余额
     * @param zfpcrId
     * @return
     */
    @GetMapping("/getAvailableBalance")
    public AjaxResult getAvailableBalance(@RequestParam(required=false) String zfpcrId)
    {
        //获取当前企业的编号
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取公司编号
        String companyId = use.getCompanyId();
        LambdaQueryWrapper<ZcFinanceProComRel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //公司
        lambdaQueryWrapper.eq(ZcFinanceProComRel::getZfpcrCompanyId,companyId);
        //授信编号
        lambdaQueryWrapper.eq(ZcFinanceProComRel::getZfpcrId,zfpcrId);
        //授信额度
        String amount = "";
        List<ZcFinanceProComRel>   list = financeProComRelService.findZcFinanceProComRels(lambdaQueryWrapper);
        if(list.size() < 1){
            return AjaxResult.error("获取授信额度信息失败");
        }
        amount = list.get(0).getZfpcrAmount();
        //获取已用的授信额度
        Map m = new HashMap();
        m.put("zfpcrId",zfpcrId);
        m.put("companyId",companyId);
        String userdBalance =  ownCreditService.getUsedBalance(m);
        //获取剩余额度
        String remaining = AmtUtil.subtract(amount,userdBalance,2);
        Map map = new HashMap();
        map.put("remaining",remaining);
        return AjaxResult.success(map);
    }


    /**
     * 获取供应商开立可用额度
     * @param zfsqId
     * @return
     */
    @GetMapping("/getSupplierAvailableBalance")
    public AjaxResult getSupplierAvailableBalance(@RequestParam(required=false) String zfsqId)
    {
        //获取当前企业的编号
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取公司编号
        String companyId = use.getCompanyId();
        //查询供应商的授信额度
        LambdaQueryWrapper<ZcFinanceSupplierQuota> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //公司
        lambdaQueryWrapper.eq(ZcFinanceSupplierQuota::getZfsqCompanyId,companyId);
        //授信编号
        lambdaQueryWrapper.eq(ZcFinanceSupplierQuota::getZfsqId,zfsqId);
        //授信额度
        String amount = "";
        List<ZcFinanceSupplierQuota>   list = financeSupplierQuotaService.findZcFinanceSupplierQuotas(lambdaQueryWrapper);
        if(list.size() < 1){
            return AjaxResult.error("获取授信额度信息失败");
        }
        amount = list.get(0).getZfsqAmount();
        //获取已用的授信额度
        Map m = new HashMap();
        m.put("zfsqId",zfsqId);
        m.put("companyId",companyId);
        String userdBalance =  ownCreditService.getSupplierUsedBalance(m);
        //获取剩余额度
        String remaining = AmtUtil.subtract(amount,userdBalance,2);
        Map map = new HashMap();
        map.put("remaining",remaining);
        return AjaxResult.success(map);
    }






}
