package com.ruoyi.finance.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.approvalFlow.domain.AuditItems;
import com.ruoyi.approvalFlow.service.impl.AuditItemsServiceImpl;
import com.ruoyi.basicData.domain.TCorps;
import com.ruoyi.basicData.domain.TFees;
import com.ruoyi.basicData.mapper.TCorpsMapper;
import com.ruoyi.basicData.mapper.TFeesMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.finance.domain.TFee;
import com.ruoyi.finance.domain.TFeeDo;
import com.ruoyi.finance.domain.TWareHouseFees;
import com.ruoyi.finance.excel.Charge;
import com.ruoyi.finance.excel.Contrast;
import com.ruoyi.finance.excel.Detailed;
import com.ruoyi.finance.excel.Payment;
import com.ruoyi.finance.mapper.TFeeDoMapper;
import com.ruoyi.finance.mapper.TFeeMapper;
import com.ruoyi.finance.service.ITFeeService;
import com.ruoyi.reportManagement.dto.TWarehousebill;
import com.ruoyi.reportManagement.excel.Payable;
import com.ruoyi.reportManagement.excel.Profit;
import com.ruoyi.reportManagement.excel.Receivable;
import com.ruoyi.shipping.domain.TAccount;
import com.ruoyi.shipping.domain.TFeeInvoice;
import com.ruoyi.shipping.excel.Account;
import com.ruoyi.shipping.mapper.TFeeInvoiceMapper;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.warehouseBusiness.domain.BillnoDel;
import com.ruoyi.warehouseBusiness.domain.TWarehouseBills;
import com.ruoyi.warehouseBusiness.domain.TWarehousebillsfees;
import com.ruoyi.warehouseBusiness.excel.ListMapToBeanUtils;
import com.ruoyi.warehouseBusiness.excel.TWareHouseExcelItem;
import com.ruoyi.warehouseBusiness.mapper.BillnoDelMapper;
import com.ruoyi.warehouseBusiness.mapper.TWarehouseBillsMapper;
import com.ruoyi.warehouseBusiness.mapper.TWarehousebillsfeesMapper;
import com.ruoyi.warehouseBusiness.service.impl.BillnoSerialServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;

/**
 * 财务数据主Service业务层处理
 *
 * @author ruoyi
 * @date 2021-01-18
 */
@Service
public class TFeeServiceImpl implements ITFeeService {
    @Autowired
    private TFeeMapper tFeeMapper;

    @Autowired
    private TFeeDoMapper tFeeDoMapper;

    @Autowired
    private BillnoSerialServiceImpl billnoSerialServiceImpl;

    @Autowired
    private BillnoDelMapper billnoDelMapper;

    @Autowired
    private TCorpsMapper tCorpsMapper;

    @Autowired
    private TFeesMapper tFeesMapper;

    @Autowired
    private TWarehouseBillsMapper tWarehouseBillsMapper;

    @Autowired
    private TWarehousebillsfeesMapper tWarehousebillsfeesMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private AuditItemsServiceImpl auditItemsService;

    @Autowired
    private ISysDictDataService iSysDictDataService;
    @Autowired
    private TFeeInvoiceMapper tFeeInvoiceMapper;


    /**
     * 查询财务数据主
     *
     * @param fId 财务数据主ID
     * @return 财务数据主
     */
    @Override
    public Map<String, Object> selectTFeeById(Long fId) {
        Map<String, Object> map = new HashMap<>();
        // 客户表
        List<Long> corpsId = new ArrayList<>();
        // 费用
        List<Long> feesId = new ArrayList<>();
        //费用名称
        String feeName = null;

        TFee tFee = tFeeMapper.selectTFeeById(fId);
        if (StringUtils.isNotNull(tFee.getfCorpid())) {
            corpsId.add(tFee.getfCorpid());
        }
        corpsId.add(tFee.getfCorpid());

        // 查询从表数据
        TFeeDo tFeeDo = new TFeeDo();
        tFeeDo.setfPid(fId);
        List<TFeeDo> tFeeDoList = tFeeDoMapper.selectTFeeDoList(tFeeDo);
        List<Map<String, Object>> feeDoList = new ArrayList<>();
        if (StringUtils.isNotEmpty(tFeeDoList)) {
            for (TFeeDo fees : tFeeDoList) {
                Map<String, Object> map1 = new HashMap<>();
                feesId.add(fees.getfFeeid());
                // 查询主表
                TWarehouseBills tWarehousebills = tWarehouseBillsMapper.selectTWarehousebillsById(fees.getfSrcpid());
                // 费用名称
                TFees tFees = tFeesMapper.selectTFeesById(fees.getfFeeid());
                if (tFees != null){
                    feeName = tFees.getfName();
                }
                // 费用表数据
                TWarehousebillsfees tWarehousebillsfees = tWarehousebillsfeesMapper.selectTWarehousebillsfeesById(fees.getfSrcid());
                if (tWarehousebillsfees == null) {
                    return AjaxResult.error("费用数据为空，请确认");
                }
                // 字典宝
                SysDictData sysDictData = new SysDictData();
                sysDictData.setDictType("data_unitfees");
                sysDictData.setDictValue(String.valueOf(tWarehousebillsfees.getfFeeunitid()));
                sysDictData.setStatus("0");
                List<SysDictData> sysDictDataList = iSysDictDataService.selectDictDataList(sysDictData);

                List<SysDictData> sysDictDataListIn = new ArrayList<>();
                SysDictData sysDictDataIn = new SysDictData();
                if (tWarehousebillsfees.getfBilltype().equals("SJRK")) {
                    sysDictData.setDictType("st_in_type");
                    sysDictData.setDictValue(String.valueOf(tWarehousebillsfees.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                } else if (tWarehousebillsfees.getfBilltype().equals("SJCK")) {
                    sysDictData.setDictType("st_out_type");
                    sysDictData.setDictValue(String.valueOf(tWarehousebillsfees.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                } else if (tWarehousebillsfees.getfBilltype().equals("CKDB") | tWarehousebillsfees.getfBilltype().equals("HWTG")) {
                    sysDictData.setDictType("st_trans_type");
                    sysDictData.setDictValue(String.valueOf(tWarehousebillsfees.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                }
                map1.put("fId", fees.getfId());
                map1.put("fSrcid", fees.getfSrcid());
                map1.put("fSrcpid", fees.getfSrcpid());
                map1.put("fMblno", tWarehousebillsfees.getfMblno());
                map1.put("fBscorpno", tWarehousebills.getfBscorpno());
                map1.put("fProductName", tWarehousebillsfees.getfProductName());
                map1.put("fBsdate", tWarehousebillsfees.getfBsdate());
                map1.put("fFeeid", fees.getfFeeid());
                map1.put("fFeeName", feeName);
                map1.put("fSrcdc", fees.getfSrcdc());
                map1.put("fAmt", fees.getfAmt());
                map1.put("fAmtdr", fees.getfAmtdr());
                map1.put("fRemarks", fees.getfRemarks());
                map1.put("srcBillNo", tWarehousebillsfees.getSrcId());
                map1.put("fMarks", tWarehousebillsfees.getfMarks());
                map1.put("fChargedate", tWarehousebillsfees.getfChargedate());
                map1.put("fBillingDeadline", tWarehousebillsfees.getfBillingDeadline());
                map1.put("fBillingDays", tWarehousebillsfees.getfBillingDays());
                map1.put("fInventoryDays", tWarehousebillsfees.getfInventoryDays());
                map1.put("fFeeunitid", sysDictDataList.get(0).getDictLabel());
                map1.put("fQty", tWarehousebillsfees.getfQty());
                map1.put("fUnitprice", tWarehousebillsfees.getfUnitprice());
                if (tWarehousebillsfees.getfBilltype().equals("KHDD")) {
                    map1.put("fBusinessType", "船运订单");
                } else {
                    map1.put("fBusinessType", sysDictDataListIn.get(0).getDictLabel());
                }
                if (tWarehousebills.getfBilltype().equals("SJRK")) {
                    map1.put("fBilltype", "入库");
                } else if (tWarehousebills.getfBilltype().equals("SJCK")) {
                    map1.put("fBilltype", "出库");
                } else if (tWarehousebills.getfBilltype().equals("CKDB")) {
                    map1.put("fBilltype", "调拨");
                } else if (tWarehousebills.getfBilltype().equals("HWTG")) {
                    map1.put("fBilltype", "货物通关");
                } else if (tWarehousebills.getfBilltype().equals("HQZY")) {
                    map1.put("fBilltype", "货权转移");
                } else if (tWarehousebills.getfBilltype().equals("KHDD")) {
                    map1.put("fBilltype", "船运订单");
                }
                feeDoList.add(map1);
            }
        }

        List<TCorps> corpsList = new ArrayList<>();
        List<Long> corpsIdList = StringUtils.integerDeduplication(corpsId);
        for (Long corpId : corpsIdList) {
            TCorps corps = tCorpsMapper.selectTCorpsById(corpId);
            if (StringUtils.isNotNull(corps)) {
                corpsList.add(corps);
            }
        }
        List<TFees> feesList = new ArrayList<>();
        List<Long> longList = StringUtils.integerDeduplication(feesId);
        for (Long fees : longList) {
            TFees tFees = tFeesMapper.selectTFeesById(fees);
            if (StringUtils.isNotNull(tFees)) {
                feesList.add(tFees);
            }
        }
        map.put("tFee", tFee);
        map.put("corps", corpsList);
        map.put("feesList", feesList);
        map.put("feeDoList", feeDoList);
        return map;
    }

    @Override
    public Map<String, Object> selectTFeeByIdNew(Long fId) {
        Map<String, Object> map = new HashMap<>();
        TFee tFee = tFeeMapper.selectTFeeByIdNew(fId);
        List<TFeeDo> feeDoList = tFeeDoMapper.selectTFeeDoByfPid(fId);
        TFeeInvoice tFeeInvoice = new TFeeInvoice();
        tFeeInvoice.setfPid(fId);
        List<TFeeInvoice> tFeeInvoiceList = tFeeInvoiceMapper.selectTFeeInvoiceList(tFeeInvoice);
        map.put("tFee", tFee);
        map.put("feeDoList", feeDoList);
        map.put("tFeeInvoiceList", tFeeInvoiceList);
        return map;
    }

    /**
     * 查询财务数据主列表
     *
     * @param tFee 财务数据主
     * @return 财务数据主
     */
    @Override
    public List<TFee> selectTFeeList(TFee tFee) {
        return tFeeMapper.selectTFeeList(tFee);
    }

    @Override
    public List<Map<String, Object>> selectTFeeList1(TFee tFee) {
        return tFeeMapper.selectTFeeList1(tFee);
    }

    @Override
    public List<Map<String, Object>> webVersionTFee(TFee tFee) {
        return tFeeMapper.webVersionTFee(tFee);
    }

    @Override
    public List<Map<String, Object>> webVersionDetail(TAccount tAccount) {
        return tWarehousebillsfeesMapper.webVersionDetail(tAccount);
    }

    @Override
    public List<Map<String, Object>> webVersionInvoice(TFee tFee) {
        return tFeeMapper.webVersionInvoice(tFee);
    }

    @Override
    public List<Map<String, Object>> webVersionInvoiceDetail(TFee tFee) {
        List<Map<String, Object>> list = tFeeMapper.webVersionInvoice(tFee);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, Object> map : list) {
                Long fId = Long.valueOf(map.get("fId").toString());
                List<TFeeDo> tFeeDos = tFeeDoMapper.selectTFeeDoByfPid(fId);
                map.put("tFeeDoList", tFeeDos);
                TFeeInvoice tFeeInvoice = new TFeeInvoice();
                tFeeInvoice.setfPid(fId);
                List<TFeeInvoice> tFeeInvoiceList = tFeeInvoiceMapper.selectTFeeInvoiceList(tFeeInvoice);
                map.put("tFeeInvoiceList", tFeeInvoiceList);
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> webVersionList(TAccount tAccount) {
        return tWarehousebillsfeesMapper.webVersionReconciliation(tAccount);
    }

    /**
     * 新增财务数据主
     *
     * @param tFee 财务数据主
     * @return 结果
     */
    @Override
    public int insertTFee(TFee tFee) {
        tFee.setCreateTime(DateUtils.getNowDate());
        return tFeeMapper.insertTFee(tFee);
    }

    /**
     * 新增对账 、收费、
     *
     * @param tfee
     * @param tfeeDo
     * @param loginUser
     * @param fBilltype
     * @return
     */
    @Override
    @Transactional
    public AjaxResult insertTFeeTFeeDo(String tfee, String tfeeDo, LoginUser loginUser, String fBilltype) {
        Long fPid = null;
        Map<String, Object> map = new HashMap<>();
        TFee tFee = JSONArray.parseObject(tfee, TFee.class);
        if (StringUtils.isNull(tFee.getfId())) {
            // 如果是新数据
            tFee.setCreateBy(loginUser.getUser().getUserName());
            tFee.setCreateTime(new Date());
            tFee.setfDeptid(loginUser.getUser().getDeptId());
            tFee.setfBilltype(fBilltype);
            // 业务编码
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getBillNo(fBilltype, time);
            tFee.setfBillno(billNo);
            tFee.setfBillstatus("2");
            tFeeMapper.insertTFee(tFee);
            fPid = tFee.getfId();
        } else {
            fPid = tFee.getfId();
            tFee.setUpdateBy(loginUser.getUser().getUserName());
            tFee.setUpdateTime(new Date());
            tFeeMapper.updateTFee(tFee);
            // 删除从表
            tFeeDoMapper.deleteByFPid(fPid);
        }
        //  财务从表
        if (StringUtils.isNotNull(tfeeDo)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tfeeDo);
            List<TFeeDo> tFeeDoList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeDo.class);
            for (TFeeDo tFeeDo : tFeeDoList) {
                tFeeDo.setfPid(fPid);
                tFeeDo.setCreateBy(loginUser.getUser().getUserName());
                tFeeDo.setCreateTime(new Date());
                tFeeDo.setfStatus("2");
                tFeeDoMapper.insertTFeeDo(tFeeDo);
            }
        }
        map.put("tFee", tFee);
        return AjaxResult.success("成功", map);
    }

    @Override
    public AjaxResult insertWebVersion(String tfee, String tfeeDo, LoginUser loginUser, String fBilltype) {
        Long fPid = null;
        Map<String, Object> map = new HashMap<>();
        TFee tFee = JSONArray.parseObject(tfee, TFee.class);
        if (StringUtils.isNull(tFee.getfId())) {
            // 如果是新数据
            tFee.setCreateBy(loginUser.getUser().getUserName());
            tFee.setCreateTime(new Date());
            tFee.setfDeptid(loginUser.getUser().getDeptId());
            tFee.setfBilltype(fBilltype);
            // 业务编码
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getBillNo(fBilltype, time);
            tFee.setfBillno(billNo);
            tFee.setfBillstatus("2");
            tFee.setfAccbilldate(new Date());
            tFeeMapper.insertTFee(tFee);
            fPid = tFee.getfId();
        } else {
            fPid = tFee.getfId();
            tFee.setUpdateBy(loginUser.getUser().getUserName());
            tFee.setUpdateTime(new Date());
            tFeeMapper.updateTFee(tFee);
            // 删除从表
            tFeeDoMapper.deleteByFPid(fPid);
        }
        //  财务从表
        if (StringUtils.isNotNull(tfeeDo)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tfeeDo);
            List<TAccount> tFeeDoList = JSONObject.parseArray(jsonDrArray.toJSONString(), TAccount.class);
            for (TAccount tAccount : tFeeDoList) {
                TFeeDo tFeeDo = new TFeeDo();
                tFeeDo.setfSrcid(tAccount.getfSrcid());
                tFeeDo.setfSrcpid(tAccount.getfSrcpid());
                tFeeDo.setfPid(fPid);
                tFeeDo.setCreateBy(loginUser.getUser().getUserName());
                tFeeDo.setCreateTime(new Date());
                tFeeDo.setfStatus("2");
                tFeeDo.setfSrcdc("D");
                tFeeDo.setfAmtdr(tAccount.getfAmtdr());
                tFeeDo.setfAmt(tAccount.getfAmt());
                tFeeDo.setfFeeid(tAccount.getfFeeid());
                tFeeDoMapper.insertTFeeDo(tFeeDo);
            }
        }
        map.put("tFee", tFee);
        return AjaxResult.success("成功", map);
    }

    /**
     * 新增对账 、收费、
     *
     * @param tfee
     * @param tfeeDo
     * @param loginUser
     * @param fBilltype
     * @return
     */
    @Override
    @Transactional
    public AjaxResult insertKHTFeeTFeeDo(String tfee, String tfeeDo, String tFeeInvoice, LoginUser loginUser, String fBilltype) {
        Long fPid = null;
        Map<String, Object> map = new HashMap<>();
        String billStatus = "2";
        if (fBilltype.equals("INV")){
            billStatus = "6";
        }
        TFee tFee = JSONArray.parseObject(tfee, TFee.class);
        if (StringUtils.isNull(tFee.getfId())) {
            // 如果是新数据
            tFee.setCreateBy(loginUser.getUser().getUserName());
            tFee.setCreateTime(new Date());
            tFee.setfDeptid(loginUser.getUser().getDeptId());
            tFee.setfBilltype(fBilltype);
            // 业务编码
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getBillNo(fBilltype, time);
            tFee.setfBillno(billNo);
            tFee.setfBillstatus(billStatus);
            tFeeMapper.insertTFee(tFee);
            fPid = tFee.getfId();
        } else {
            fPid = tFee.getfId();
            boolean change = this.change(fPid);
            if (!change && !"INV".equals(fBilltype)) {
                return AjaxResult.error("当前数据不支持修改");
            }
            tFee.setUpdateBy(loginUser.getUser().getUserName());
            tFee.setUpdateTime(new Date());
            tFeeMapper.updateTFee(tFee);
            // 删除从表
            tFeeDoMapper.deleteByFPid(fPid);
            tFeeInvoiceMapper.deleteByFPid(fPid);
        }
        //  财务从表
        if (StringUtils.isNotNull(tfeeDo)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tfeeDo);
            List<TFeeDo> tFeeDoList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeDo.class);
            for (TFeeDo tFeeDo : tFeeDoList) {
                tFeeDo.setfPid(fPid);
                tFeeDo.setCreateBy(loginUser.getUser().getUserName());
                tFeeDo.setCreateTime(new Date());
                tFeeDo.setfStatus(billStatus);
                tFeeDoMapper.insertTFeeDo(tFeeDo);
            }
        }
        if (!"".equals(tFeeInvoice) && tFeeInvoice != null && !"null".equals(tFeeInvoice)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tFeeInvoice);
            List<TFeeInvoice> tFeeInvoiceList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeInvoice.class);
            for (TFeeInvoice feeInvoice : tFeeInvoiceList) {
                feeInvoice.setfPid(fPid);
                feeInvoice.setCreateBy(loginUser.getUser().getUserName());
                feeInvoice.setCreateTime(new Date());
                feeInvoice.setfBillstatus(billStatus);
                tFeeInvoiceMapper.insertTFeeInvoice(feeInvoice);
            }
        }
        map.put("tFee", tFee);
        return AjaxResult.success("成功", map);
    }

    /**
     * 修改财务数据主
     *
     * @param tFee 财务数据主
     * @return 结果
     */
    @Override
    public int updateTFee(TFee tFee) {
        tFee.setUpdateTime(DateUtils.getNowDate());
        return tFeeMapper.updateTFee(tFee);
    }

    /**
     * 批量删除财务数据主
     *
     * @param fIds 需要删除的财务数据主ID
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteWebVersionByIds(Long[] fIds) {
        // 取出业务编号、 放入 billno_del
        for (Long id : fIds) {
            // 1、查询主表信息
            TFee tFee = tFeeMapper.selectTFeeById(id);
            boolean change = this.change(id);
            if (change == false){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("数据正在审批或审批通过,不允许删除");
            }
            // 2、业务编号、客存编号 放入 billno_del
            BillnoDel billnoDel = new BillnoDel();
            billnoDel.setBillType(tFee.getfBilltype());
            billnoDel.setBillNo(tFee.getfBillno());
            billnoDelMapper.insertBillnoDel(billnoDel);
            if (tFee.getfAccountId() != null){
                TFee fee = tFeeMapper.selectTFeeById(tFee.getfAccountId());
                fee.setfMake(0);
                int updateTFee = tFeeMapper.updateTFee(fee);
            }
        }
        int i = tFeeMapper.deleteTFeeByIds(fIds);
        if (i<= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除发票申请失败,请找管理员");
        }
        return AjaxResult.success();
    }

    @Override
    public int deleteTFeeByIds(Long[] fIds) {
        // 取出业务编号、 放入 billno_del
        for (Long id : fIds) {
            // 1、查询主表信息
            TFee tFee = tFeeMapper.selectTFeeById(id);
            // 2、业务编号、客存编号 放入 billno_del
            BillnoDel billnoDel = new BillnoDel();
            billnoDel.setBillType(tFee.getfBilltype());
            billnoDel.setBillNo(tFee.getfBillno());
            billnoDelMapper.insertBillnoDel(billnoDel);
            if (tFee.getfAccountId() != null){
                TFee fee = tFeeMapper.selectTFeeById(tFee.getfAccountId());
                fee.setfMake(0);
                int updateTFee = tFeeMapper.updateTFee(fee);
            }
        }
        return tFeeMapper.deleteTFeeByIds(fIds);
    }

    /**
     * 删除财务数据主信息
     *
     * @param fId 财务数据主ID
     * @return 结果
     */
    @Override
    public int deleteTFeeById(Long fId) {
        return tFeeMapper.deleteTFeeById(fId);
    }

    @Override
    public List<Map<String, Object>> warehouseBillsFeesList(TWareHouseFees tWareHouseFees, String billsType) {
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<>();
        map.put("tWareHouseFees", tWareHouseFees);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (billsType.equals("DZ") || billsType.equals("KHDZ")) {
            mapList = tFeeMapper.warehouseBillsFeesListAccamount(map);
        } else if (billsType.equals("invoiceFP")) {
            mapList = tFeeMapper.warehouseInvoiceFPFeesList(map);
        } else if (billsType.equals("ApplyFP")) {
            mapList = tFeeMapper.warehouseApplyFPFeesList(map);
        } else {
            mapList = tFeeMapper.warehouseBillsFeesList(map);
            /*if(tWareHouseFees.getfStatementNo()!=null && !tWareHouseFees.getfStatementNo().equals("")){
                mapList = tFeeMapper.warehouseBillsFeesListAccamount(map);
            }else {

            }*/
        }
        return mapList;
    }

    @Override
    public List<Map<String, Object>> warehouseBillsFeesList(TWareHouseFees tWareHouseFees) {
        return tFeeMapper.warehouseBillsFeesList1(tWareHouseFees);
    }

    @Override
    public List<Map<String, Object>> warehouseBillsFeesProfitList(TWareHouseFees tWareHouseFees) {
        return tFeeMapper.warehouseBillsFeesProfitList(tWareHouseFees);
    }

    public static BigDecimal calculation1(String fTotalgross, String fGrossweightblc) {
        BigDecimal num1 = new BigDecimal(fTotalgross);
        BigDecimal num2 = new BigDecimal(fGrossweightblc);
        BigDecimal result = num1.subtract(num2);
        return result.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    @Transactional
    public AjaxResult confirm(String tfee, String tfeeDo, LoginUser loginUser, String fBilltype) {
        String key = "";
        boolean isApprove = false;
        Map<String, Object> messageMap = new HashMap<>();
        long actId = 0L;
        if ("DZ".equals(fBilltype)) {
            actId = 210L;
            key = "warehouse.contrast.ApprovalFlow";
        } else if ("SF".equals(fBilltype)) {
            actId = 220L;
            key = "warehouse.charge.ApprovalFlow";
        } else if ("FF".equals(fBilltype)) {
            actId = 230L;
            key = "warehouse.payment.ApprovalFlow";
        } else if ("KHDZ".equals(fBilltype)) {
            actId = 430L;
            key = "warehouse.kaiHeContrast.ApprovalFlow";
        } else if ("KHSF".equals(fBilltype)) {
            actId = 440L;
            key = "warehouse.kaiHeCharge.ApprovalFlow";
        } else if ("KHFF".equals(fBilltype)) {
            actId = 450L;
            key = "warehouse.kaiHePayment.ApprovalFlow";
        }
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        TFee tFee = JSONArray.parseObject(tfee, TFee.class);
        String billstatus = "";
        if (isApprove) {
            billstatus = "4";
        } else {
            billstatus = "6";
        }
        if (StringUtils.isNull(tFee.getfId())) {
            // 如果是新数据
            tFee.setCreateBy(loginUser.getUser().getUserName());
            tFee.setfDeptid(loginUser.getUser().getDeptId());
            tFee.setfBilltype(fBilltype);
            tFee.setfBillstatus(billstatus);
            // 业务编码
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getBillNo(fBilltype, time);
            tFee.setfBillno(billNo);
            tFeeMapper.insertTFee(tFee);
        } else {
            tFee.setUpdateBy(loginUser.getUser().getUserName());
            tFee.setUpdateTime(new Date());
            tFee.setfBillstatus(billstatus);
            tFeeMapper.updateTFee(tFee);
            // 删除从表
            tFeeDoMapper.deleteByFPid(tFee.getfId());
        }
        messageMap.put("tFee",tFee);
        //  财务从表
        if (StringUtils.isNotNull(tfeeDo) && !"[]".equals(tfeeDo)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tfeeDo);
            List<TFeeDo> tFeeDoList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeDo.class);
            for (TFeeDo tFeeDo : tFeeDoList) {
                Map<String, Object> map = this.judgeMoney(tFeeDo.getfSrcid(), tFeeDo.getfAmt(), fBilltype, tFeeDo.getfFeeid());
                boolean b = (Boolean) map.get("flag");
                if ( b == false){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error(map.get("message").toString());
                }
                tFeeDo.setfPid(tFee.getfId());
                tFeeDo.setCreateBy(loginUser.getUser().getUserName());
                tFeeDo.setCreateTime(new Date());
                tFeeDo.setfStatus(billstatus);
                tFeeDoMapper.insertTFeeDo(tFeeDo);
            }
        }
        // 这里加个判断取系统参数来确定是否需要启用审批流

        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(tFee.getfId());
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(tFee.getfBillno()); // 业务编号
            auditItems.setRefno1(String.valueOf(tFee.getfCorpid())); // 货权方
            auditItems.setRefno2(fBilltype);// 财务类型
            auditItems.setRefno3(tFee.gettMblno());// 提单号
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(loginUser.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setFidStatus("f_billstatus");
            auditItems.setTimes(1L);
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            if (code.equals(500L)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("发票申请提交审核失败,请找管理员");
            }
        } else {
            if (StringUtils.isNotNull(tfeeDo) && !"[]".equals(tfeeDo)) {
                JSONArray jsonDrArray = JSONArray.parseArray(tfeeDo);
                List<TFeeDo> tFeeDoList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeDo.class);
                for (TFeeDo tFeeDo : tFeeDoList) {
                    // 跟新费用明细
                    int m = updateBillsFees(tFee.getfId(), tFeeDo, fBilltype);
                    if (m == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("更新费用明细失败");
                    }
                }
            }
            AjaxResult ajaxResult = tfeeFollow(tFee.getfId(), 6L);
            Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if (code.equals(500L)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("发票申请提交审核失败,请找管理员");
            }
        }
        return AjaxResult.success("成功", messageMap);
    }

    @Override
    @Transactional
    public AjaxResult webVersionConfirm(Long[] fIds, String billsType, LoginUser loginUser) {
        String key = "";
        boolean isApprove = false;
        long actId = 0L;
        if ("DZ".equals(billsType)) {
            actId = 210L;
            key = "warehouse.contrast.ApprovalFlow";
        } else if ("SF".equals(billsType)) {
            actId = 220L;
            key = "warehouse.charge.ApprovalFlow";
        } else if ("FF".equals(billsType)) {
            actId = 230L;
            key = "warehouse.payment.ApprovalFlow";
        } else if ("KHDZ".equals(billsType)) {
            actId = 430L;
            key = "warehouse.kaiHeContrast.ApprovalFlow";
        } else if ("KHSF".equals(billsType)) {
            actId = 440L;
            key = "warehouse.kaiHeCharge.ApprovalFlow";
        } else if ("KHFF".equals(billsType)) {
            actId = 450L;
            key = "warehouse.kaiHePayment.ApprovalFlow";
        }
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        String billStatus = null;
        if (isApprove) {
            billStatus = "4";
        } else {
            billStatus = "6";
        }
        for (Long fId : fIds) {
            TFee tFee = tFeeMapper.selectTFeeById(fId);
            if (tFee == null) {
                return AjaxResult.error("对账数据有误请确认");
            }
            boolean change = this.change(tFee.getfId());
            if (change == false){
                return AjaxResult.error("数据正在审批或审批通过,不允许提交审核");
            }
            //更新主表数据状态
            TFee fee = new TFee();
            fee.setfId(fId);
            fee.setfBillstatus(billStatus);
            int i = tFeeMapper.updateTFee(fee);
            //更新从表数据状态
            int update = tFeeDoMapper.tfeeDoFollowUpdate(fId, Long.valueOf(billStatus));
            if (isApprove) {
                AuditItems auditItems = new AuditItems();
                auditItems.setLevelId(0L);
                auditItems.setBillId(tFee.getfId());
                auditItems.setActId(actId);
                auditItems.setIffinalItem("F");
                auditItems.setBillNo(tFee.getfBillno()); // 业务编号
                auditItems.setRefno1(String.valueOf(tFee.getfCorpid())); // 货权方
                auditItems.setRefno2(billsType);// 财务类型
                auditItems.setRefno3(tFee.gettMblno());// 提单号
                auditItems.setSendUserId(loginUser.getUser().getUserId());
                auditItems.setSendName(loginUser.getUsername());
                auditItems.setSendTime(new Date());
                auditItems.setAuditUserId(loginUser.getUser().getUserId());
                auditItems.setAuditItem(new Date());
                auditItems.setAuditOpTime(new Date());
                auditItems.setFidStatus("f_billstatus");
                auditItems.setTimes(1L);
                auditItems.setAuditMsg("提交");
                auditItems.setAuditStatus("O");
                AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
                Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
                if (code.equals(500L)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
                return approvalFlow;
            } else {
                TFeeDo tFeeDo = new TFeeDo();
                tFeeDo.setfPid(fId);
                List<TFeeDo> tFeeDoList = tFeeDoMapper.selectTFeeDoList(tFeeDo);
                for (TFeeDo feeDo : tFeeDoList) {
                    // 跟新费用明细
                    int m = updateBillsFees(fId, feeDo, billsType);
                    if (m == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("更新费用明细失败");
                    }
                }
            }
            AjaxResult ajaxResult = tfeeFollow(tFee.getfId(), 6L);
            Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            return ajaxResult;
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult confirmKaiHe(String tfee, String tfeeDo, String tFeeInvoice, LoginUser loginUser, String fBilltype) {
        Long fPid = null;
        TFee tFee = JSONArray.parseObject(tfee, TFee.class);
        Map<String, Object> messageMap = new HashMap<>();
        String key = "";
        boolean isApprove = false;
        long actId = 0L;
        String billStatus = "";
        if ("DZ".equals(fBilltype)) {
            actId = 210L;
            key = "warehouse.contrast.ApprovalFlow";
        } else if ("SF".equals(fBilltype)) {
            actId = 220L;
            key = "warehouse.charge.ApprovalFlow";
        } else if ("FF".equals(fBilltype)) {
            actId = 230L;
            key = "warehouse.payment.ApprovalFlow";
        } else if ("KHDZ".equals(fBilltype)) {
            actId = 430L;
            key = "warehouse.kaiHeContrast.ApprovalFlow";
        } else if ("KHSF".equals(fBilltype)) {
            actId = 440L;
            key = "warehouse.kaiHeCharge.ApprovalFlow";
        } else if ("KHFF".equals(fBilltype)) {
            actId = 450L;
            key = "warehouse.kaiHePayment.ApprovalFlow";
        } else if ("ApplyFP".equals(fBilltype)) {
            actId = 470L;
            key = "warehouse.kaiHeApplyFP.ApprovalFlow";
        }
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        if (isApprove) {
            billStatus = "4";
        } else {
            billStatus = "6";
        }
        if (StringUtils.isNull(tFee.getfId())) {
            // 如果是新数据
            tFee.setCreateBy(loginUser.getUser().getUserName());
            tFee.setfDeptid(loginUser.getUser().getDeptId());
            tFee.setfBilltype(fBilltype);
            // 业务编码
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getBillNo(fBilltype, time);
            tFee.setfBillno(billNo);
            tFee.setfBillstatus(billStatus);
            tFeeMapper.insertTFee(tFee);
            fPid = tFee.getfId();
        } else {
            fPid = tFee.getfId();
            boolean change = this.change(fPid);
            if (!change) {
                return AjaxResult.error("当前数据不支持修改");
            }
            tFee.setUpdateBy(loginUser.getUser().getUserName());
            tFee.setUpdateTime(new Date());
            tFee.setfBillstatus(billStatus);
            tFeeMapper.updateTFee(tFee);
            // 删除从表
            tFeeDoMapper.deleteByFPid(tFee.getfId());
            //删除开票从表
            tFeeInvoiceMapper.deleteByFPid(tFee.getfId());
        }
        messageMap.put("tFee", tFee);
        //  财务从表
        if (StringUtils.isNotNull(tfeeDo) && !"[]".equals(tfeeDo)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tfeeDo);
            List<TFeeDo> tFeeDoList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeDo.class);
            for (TFeeDo tFeeDo : tFeeDoList) {
                Map<String, Object> map = this.judgeMoney(tFeeDo.getfSrcid(), tFeeDo.getfAmt(), fBilltype, tFeeDo.getfFeeid());
                boolean b = (Boolean) map.get("flag");
                if ( b == false){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error(map.get("message").toString());
                }
                tFeeDo.setfPid(tFee.getfId());
                tFeeDo.setCreateBy(loginUser.getUser().getUserName());
                tFeeDo.setCreateTime(new Date());
                tFeeDo.setfStatus(billStatus);
                tFeeDoMapper.insertTFeeDo(tFeeDo);
            }
        }
        if (!"".equals(tFeeInvoice) && tFeeInvoice != null && !"null".equals(tFeeInvoice)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tFeeInvoice);
            List<TFeeInvoice> tFeeInvoiceList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeInvoice.class);
            for (TFeeInvoice feeInvoice : tFeeInvoiceList) {
                feeInvoice.setfPid(fPid);
                feeInvoice.setCreateBy(loginUser.getUser().getUserName());
                feeInvoice.setCreateTime(new Date());
                feeInvoice.setfBillstatus(billStatus);
                tFeeInvoiceMapper.insertTFeeInvoice(feeInvoice);
            }
        }
        // 这里加个判断取系统参数来确定是否需要启用审批流
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(tFee.getfId());
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(tFee.getfBillno()); // 业务编号
            auditItems.setRefno1(String.valueOf(tFee.getfCorpid())); // 货权方
            auditItems.setRefno2(fBilltype);// 财务类型
            auditItems.setRefno3(tFee.gettMblno());// 提单号
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(loginUser.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setFidStatus("f_billstatus");
            auditItems.setTimes(1L);
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            if (code.equals(500L)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("发票申请提交审核失败,请找管理员");
            }

        } else {
            if (StringUtils.isNotNull(tfeeDo) && !"[]".equals(tfeeDo)) {
                JSONArray jsonDrArray = JSONArray.parseArray(tfeeDo);
                List<TFeeDo> tFeeDoList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeDo.class);
                for (TFeeDo tFeeDo : tFeeDoList) {
                    // 跟新费用明细
                    int m = updateBillsFees(tFee.getfId(), tFeeDo, fBilltype);
                    if (m == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("更新费用明细失败");
                    }
                }
            }
            AjaxResult ajaxResult = tfeeFollow(tFee.getfId(), 6L);
            Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if (code.equals(500L)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("发票申请提交审核失败,请找管理员");
            }
        }
        return AjaxResult.success("成功", messageMap);
    }

    /**
     * 根据财务主表id 更新对应明细表状态
     *
     * @param fPid 财务主表id
     * @return 结果
     */
    @Transactional
    public AjaxResult tfeeFollow(Long fPid, long fettle) {
        if (StringUtils.isNull(fPid)) {
            return AjaxResult.error("财务更新状态未找到主表信息，请与管理员联系");
        }
        TFee tFee = new TFee();
        tFee.setfId(fPid);
        tFee.setfBillstatus(String.valueOf(fettle));
        int tFeeUpdateResult = tFeeMapper.updateTFee(tFee);
        if (tFeeUpdateResult <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新财务明细状态失败，请联系管理员");
        }
        try {
            int itemUpdateResult = tFeeDoMapper.tfeeDoFollowUpdate(fPid, fettle);
        } catch (Exception exception) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新财务明细状态失败，请联系管理员");
        }
        TFeeInvoice invoice = new TFeeInvoice();
        invoice.setfPid(fPid);
        List<TFeeInvoice> tFeeInvoiceList = tFeeInvoiceMapper.selectTFeeInvoiceList(invoice);
        if (CollectionUtils.isNotEmpty(tFeeInvoiceList)) {
            try {
                int itemUpdateResult = tFeeInvoiceMapper.tFeeInvoiceUpdate(fPid, fettle);
            } catch (Exception exception) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新开票明细状态失败，请联系管理员");
            }
        }
        return AjaxResult.success();
    }

    @Transactional
    public AjaxResult billsfeesFollow(Long fPid) {
        if (StringUtils.isNull(fPid)) {
            return AjaxResult.error("费用明细更新状态未找到主表信息，请与管理员联系");
        }
        TFee tFee = tFeeMapper.selectTFeeById(fPid);
        // 查询从表数据
        TFeeDo tFeeDo = new TFeeDo();
        tFeeDo.setfPid(fPid);
        List<TFeeDo> tFeeDoList = tFeeDoMapper.selectTFeeDoList(tFeeDo);
        for (TFeeDo tFeeDo1 : tFeeDoList) {
            // 跟新费用明细
            Map<String, Object> map = this.judgeMoney(tFeeDo1.getfSrcid(), tFeeDo1.getfAmt(), tFee.getfBilltype(), tFeeDo1.getfFeeid());
            boolean b = (Boolean) map.get("flag");
            if ( b == false){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error(map.get("message").toString());
            }
            int m = updateBillsFees(fPid, tFeeDo1, tFee.getfBilltype());
            if (m == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新费用明细失败");
            }
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult revoke(String tfee, String tfeeDo, LoginUser loginUser, String fBilltype) {
        // 更新 主表、从表
        TFee tFee = JSONArray.parseObject(tfee, TFee.class);
        if("DZApplyFP".equals(fBilltype)){
            TFee fee = tFeeMapper.selectTFeeById(tFee.getfId());
            if (fee.getfMake()==1){
                return AjaxResult.error("该申请发票已开销项发票,不能撤销");
            }
        }
        tFee.setUpdateBy(loginUser.getUser().getUserName());
        tFee.setUpdateTime(new Date());
        tFeeMapper.updateTFee(tFee);
        // 删除从表
        tFeeDoMapper.deleteByFPid(tFee.getfId());
        //  财务从表
        if (StringUtils.isNotNull(tfeeDo)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tfeeDo);
            List<TFeeDo> tFeeDoList = JSONObject.parseArray(jsonDrArray.toJSONString(), TFeeDo.class);
            for (TFeeDo tFeeDo : tFeeDoList) {
                tFeeDo.setfPid(tFee.getfId());
                tFeeDo.setCreateBy(loginUser.getUser().getUserName());
                tFeeDo.setCreateTime(new Date());
                tFeeDoMapper.insertTFeeDo(tFeeDo);
                // 跟新费用明细
                int m = updateBillsFees(tFee.getfId(), tFeeDo, fBilltype);
                if (m == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新费用明细失败");
                }
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult queryRemove(Long fId) {
        TFee tFee = tFeeMapper.selectTFeeById(fId);
        TFeeDo tFeeDo = new TFeeDo();
        tFeeDo.setfPid(tFee.getfId());
        List<TFeeDo> tFeeDoList = tFeeDoMapper.selectTFeeDoList(tFeeDo);
        if (StringUtils.isNull(tFee)) {
            return AjaxResult.success("0");
        } else if (StringUtils.isNotNull(tFee) && StringUtils.isEmpty(tFeeDoList)) {
            return AjaxResult.success("1");
        }else if (tFee.getfBilltype().equals("INV") && tFee.getfAccountId() !=null) {
            return AjaxResult.success("3");
        } else {
            return AjaxResult.success("2");
        }
    }

    @Override
    @Transactional
    public AjaxResult remove(Long fId) {
        TFee tFee = tFeeMapper.selectTFeeById(fId);
        if ("4".equals(tFee.getfBillstatus())) {
            return AjaxResult.error("数据已提交审批,暂不能删除");
        } else if ("5".equals(tFee.getfBillstatus())) {
            return AjaxResult.error("数据正在审批,暂不能删除");
        } else if ("6".equals(tFee.getfBillstatus())) {
            return AjaxResult.error("数据审批完成,不能删除");
        } else {
            try {
                tFeeMapper.deleteTFeeById(fId);
                tFeeDoMapper.deleteByFPid(fId);
                tFeeInvoiceMapper.deleteByFPid(fId);
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("删除失败,请找管理员");
            }
            return AjaxResult.success();
        }
    }

    @Override
    public List<TWareHouseExcelItem> selectTWarehousebillsItemsList(Long fId) {
        List<TWareHouseExcelItem> tWareHouseExcelItemList = tFeeMapper.selectTWarehousebillsItemsList(fId);
        List<TWareHouseExcelItem> tWareHouseExcelItemList1 = new ArrayList<>();
        for (TWareHouseExcelItem tWareHouseExcelItem : tWareHouseExcelItemList) {
            if (StringUtils.isNotNull(tWareHouseExcelItem.getfBusinessType())) {
                List<SysDictData> sysDictDataListIn = new ArrayList<>();
                SysDictData sysDictData = new SysDictData();
                if (tWareHouseExcelItem.getfBilltype().equals("入库")) {
                    sysDictData.setDictType("st_in_type");
                    sysDictData.setDictValue(String.valueOf(tWareHouseExcelItem.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                } else if (tWareHouseExcelItem.getfBilltype().equals("出库")) {
                    sysDictData.setDictType("st_out_type");
                    sysDictData.setDictValue(String.valueOf(tWareHouseExcelItem.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                } else if (tWareHouseExcelItem.getfBilltype().equals("调拨") | tWareHouseExcelItem.getfBilltype().equals("货物通关")) {
                    sysDictData.setDictType("st_trans_type");
                    sysDictData.setDictValue(String.valueOf(tWareHouseExcelItem.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                }
                if (null != sysDictDataListIn && sysDictDataListIn.size() > 0) {
                    tWareHouseExcelItem.setfBusinessType(sysDictDataListIn.get(0).getDictLabel());
                }
            }
            tWareHouseExcelItemList1.add(tWareHouseExcelItem);
        }
        return tWareHouseExcelItemList1;
    }

    @Override
    public String findCtrlcorpid(Long fId) {
        TFee tFee = tFeeMapper.selectTFeeById(fId);
        String exportName = tFee.getfCtrlcorpid() + "-" + tFee.getfBillno();
        return exportName;
    }

    @Override
    public List<Receivable> receivableExport(TWareHouseFees tWareHouseFees) throws Exception {
        List<Map<String, Object>> list = tFeeMapper.warehouseBillsFeesList1(tWareHouseFees);
        List<Receivable> list1 = ListMapToBeanUtils.castMapToBean(list, Receivable.class);
        return list1;
    }

    @Override
    public List<Payable> payableExport(TWareHouseFees tWareHouseFees) throws Exception {
        List<Map<String, Object>> list = tFeeMapper.warehouseBillsFeesList1(tWareHouseFees);
        List<Payable> list1 = ListMapToBeanUtils.castMapToBean(list, Payable.class);
        return list1;
    }

    @Override
    public List<Profit> profitExport(TWareHouseFees tWareHouseFees) throws Exception {
        List<Map<String, Object>> list = tFeeMapper.warehouseBillsFeesProfitList(tWareHouseFees);
        List<Profit> list1 = ListMapToBeanUtils.castMapToBean(list, Profit.class);
        return list1;
    }

    @Override
    public List<Contrast> contrastExport(TFee tFee) throws Exception {
        List<Map<String, Object>> list = tFeeMapper.selectTFeeList1(tFee);
        List<Contrast> list1 = ListMapToBeanUtils.castMapToBean(list, Contrast.class);
        return list1;
    }

    @Override
    public List<Payment> paymentExport(TFee tFee) throws Exception {
        List<Map<String, Object>> list = tFeeMapper.selectFeeList(tFee);
        List<Payment> list1 = ListMapToBeanUtils.castMapToBean(list, Payment.class);
        return list1;
    }

    @Override
    public List<Charge> chargeExport(TFee tFee) throws Exception {
        List<Map<String, Object>> list = tFeeMapper.selectFeeList(tFee);
        List<Charge> list1 = ListMapToBeanUtils.castMapToBean(list, Charge.class);
        return list1;
    }

    @Override
    public List<Account> accountExport(TFee tFee) throws Exception {
        List<Map<String, Object>> list = tFeeMapper.webVersionTFee(tFee);
        List<Account> accountList = ListMapToBeanUtils.castMapToBean(list, Account.class);
        return accountList;
    }

    @Override
    public List<Detailed> selectDetailedList(Long fId) {
        List<Detailed> detailedList = tFeeMapper.selectDetailedList(fId);
        List<Detailed> detailedList1 = new ArrayList<>();
        for (Detailed tWareHouseExcelItem : detailedList) {
            if (StringUtils.isNotNull(tWareHouseExcelItem.getfBusinessType())) {
                List<SysDictData> sysDictDataListIn = new ArrayList<>();
                SysDictData sysDictData = new SysDictData();
                if (tWareHouseExcelItem.getfBilltype().equals("入库")) {
                    sysDictData.setDictType("st_in_type");
                    sysDictData.setDictValue(String.valueOf(tWareHouseExcelItem.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                } else if (tWareHouseExcelItem.getfBilltype().equals("出库")) {
                    sysDictData.setDictType("st_out_type");
                    sysDictData.setDictValue(String.valueOf(tWareHouseExcelItem.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                } else if (tWareHouseExcelItem.getfBilltype().equals("调拨") | tWareHouseExcelItem.getfBilltype().equals("货物通关")) {
                    sysDictData.setDictType("st_trans_type");
                    sysDictData.setDictValue(String.valueOf(tWareHouseExcelItem.getfBusinessType()));
                    sysDictData.setStatus("0");
                    sysDictDataListIn = iSysDictDataService.selectDictDataList(sysDictData);
                }
                if (null != sysDictDataListIn && sysDictDataListIn.size() > 0) {
                    tWareHouseExcelItem.setfBusinessType(sysDictDataListIn.get(0).getDictLabel());
                }
            }
            detailedList1.add(tWareHouseExcelItem);
        }
        return detailedList1;
    }

    @Override
    public List<Map<String, Object>> selectdetailedList(TWarehousebill tWarehousebill) {
        return tFeeMapper.selectDetailedList1(tWarehousebill);
    }

    /**
     * 更新费用明细
     *
     * @param fid
     * @param tFeeDo
     * @param billsType
     * @return
     */
    @Transactional
    public int updateBillsFees(Long fid, TFeeDo tFeeDo, String billsType) {
        // 查询从表数据
        TFee tFee = tFeeMapper.selectTFeeById(fid);
        if (billsType.equals("SF") || billsType.equals("FF")
                || billsType.equals("KHSF") || billsType.equals("KHFF")) {
            billsType = "DC";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("tFee", tFee);
        map.put("billType", billsType);
        map.put("tFeeDo", tFeeDo);
        return tWarehousebillsfeesMapper.updateTWarehousebillsfee(map);
    }

    public boolean change(Long fId) {
        boolean flag = false;
        TFee tFee = tFeeMapper.selectTFeeById(fId);
        if ("4".equals(tFee.getfBillstatus())
                || "5".equals(tFee.getfBillstatus())
                || "6".equals(tFee.getfBillstatus())) {
            flag = false;
        } else {
            flag = true;
        }
        return flag;
    }

    @Override
    @Transactional
    public AjaxResult webVersionSubmitApplyFP(TFee tFee, LoginUser loginUser, String fBilltype) {
        String key = "";
        boolean isApprove = false;
        long actId = 0L;
        String billStatus = "";
        if ("ApplyFP".equals(fBilltype)) {
            actId = 470L;
            key = "warehouse.kaiHeApplyFP.ApprovalFlow";
        }
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        if (isApprove) {
            billStatus = "4";
        } else {
            billStatus = "6";
        }
        /*for (Long getfId : tFee.getfIds()) {*/
        TFee fee = tFeeMapper.selectTFeeById(tFee.getfId());
        if (fee == null) {
            return AjaxResult.error("财务主表数据有误,请确认");
        }
        boolean change = this.change(tFee.getfId());
        if (change == false){
            return AjaxResult.error("数据正在审批或审批通过,不允许提交审核");
        }
        fee.setfId(tFee.getfId());
        fee.setfBillstatus(billStatus);
        fee.setUpdateBy(loginUser.getUser().getUserName());
        fee.setUpdateTime(new Date());
        int updateTFee = tFeeMapper.updateTFee(fee);
        if (updateTFee <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新财务主表数据出错，请找管理员");
        }
        TFeeDo tFeeDo = new TFeeDo();
        tFeeDo.setfPid(tFee.getfId());
        List<TFeeDo> tFeeDos = tFeeDoMapper.selectTFeeDoList(tFeeDo);
        if (CollectionUtils.isEmpty(tFeeDos)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("财务从表数据有误,请确认");
        }
        for (TFeeDo feeDo : tFeeDos) {
            feeDo.setfId(feeDo.getfId());
            feeDo.setfStatus(billStatus);
            feeDo.setUpdateBy(loginUser.getUser().getUserName());
            feeDo.setUpdateTime(new Date());
            int i = tFeeDoMapper.updateTFeeDo(feeDo);
            if (i <= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新财务主表数据出错，请找管理员");
            }
        }
        TFeeInvoice tFeeInvoice = new TFeeInvoice();
        tFeeInvoice.setfPid(tFee.getfId());
        List<TFeeInvoice> tFeeInvoiceList = tFeeInvoiceMapper.selectTFeeInvoiceList(tFeeInvoice);
        if (CollectionUtils.isNotEmpty(tFeeInvoiceList)){
            for (TFeeInvoice invoice : tFeeInvoiceList) {
                tFeeInvoice.setfBillstatus(billStatus);
                tFeeInvoice.setfId(invoice.getfId());
                tFeeInvoice.setUpdateBy(loginUser.getUser().getUserName());
                tFeeInvoice.setUpdateTime(new Date());
                tFeeInvoiceMapper.updateTFeeInvoice(tFeeInvoice);
            }
        }
        //添加审批流
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(fee.getfId());
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(fee.getfBillno()); // 业务编号
            auditItems.setRefno1(String.valueOf(fee.getfCorpid())); // 货权方
            auditItems.setRefno2(fee.getfBilltype());// 财务类型
            auditItems.setRefno3(fee.gettMblno());// 提单号
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(loginUser.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setFidStatus("f_billstatus");
            auditItems.setTimes(1L);
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            if (code.equals(500L)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("提交审核失败,请找管理员");
            }
            return approvalFlow;
        } else {
            for (TFeeDo t : tFeeDos) {
                // 跟新费用明细
                int m = updateBillsFees(tFee.getfId(), t, fBilltype);
                if (m == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新费用明细失败");
                }
            }
            AjaxResult ajaxResult = tfeeFollow(tFee.getfId(), 6L);
            Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if (code.equals(500L)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("提交审核失败,请找管理员");
            }
            return ajaxResult;
        }
        /*}*/
        //return AjaxResult.success();
    }

    @Override
    public AjaxResult webVersionUpdateApplyFP(TFee tFee, LoginUser loginUser, String billType) {
        TFeeInvoice tFeeInvoice = tFee.gettFeeInvoice();
        tFeeInvoice.setfPid(tFee.getfId());
        int i = 0;
        if (tFeeInvoice.getfId() != null){
            tFeeInvoice.setUpdateBy(loginUser.getUser().getUserName());
            tFeeInvoice.setUpdateTime(new Date());
            i = tFeeInvoiceMapper.updateTFeeInvoice(tFeeInvoice);
        }else {
            return AjaxResult.error("开票信息为空,请找管理员");
        }
        if (i<= 0){
            return AjaxResult.error("更新数据失败,请找管理员");
        }else {
           return AjaxResult.success();
        }
    }

    @Override
    @Transactional
    public AjaxResult webVersionApplyFP(TFee tFee, LoginUser loginUser, String fBilltype, TFeeInvoice tFeeInvoice) {
        Long fPid = null;
        String billStatus = "2";
        try {
            /*for (Long getfId : tFee.getfIds()) {*/
            TFee account = new TFee();
            TFee fee = tFeeMapper.selectTFeeById(tFee.getfId());
            if (fee == null) {
                return AjaxResult.error("财务主表数据有误,请确认");
            }
            account.setfId(fee.getfId());
            account.setfMake(1);
            fee.setfBilltype(fBilltype);
            fee.setfBillstatus(billStatus);
            fee.setCreateBy(loginUser.getUser().getUserName());
            fee.setCreateTime(new Date());
            fee.setfDeptid(loginUser.getUser().getDeptId());
            fee.setUpdateBy(null);
            fee.setUpdateTime(null);
            fee.setfInvoiceRise(tFee.getfInvoiceRise());
            fee.setfAccountId(fee.getfId());
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getBillNo(fBilltype, time);
            fee.setfBillno(billNo);
            fee.setfAccbilldate(null);
            fee.setfId(null);
            tFeeMapper.insertTFee(fee);
            tFeeMapper.updateTFee(account);
            //修改原来的数据的开票金额
            fPid = fee.getfId();
            TFeeDo tFeeDo = new TFeeDo();
            tFeeDo.setfPid(tFee.getfId());
            List<TFeeDo> tFeeDos = tFeeDoMapper.selectTFeeDoList(tFeeDo);
            if (CollectionUtils.isEmpty(tFeeDos)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("财务从表数据有误,请确认");
            }
            for (TFeeDo feeDo : tFeeDos) {
                feeDo.setfPid(fPid);
                feeDo.setfStatus(billStatus);
                feeDo.setCreateBy(loginUser.getUser().getUserName());
                feeDo.setCreateTime(new Date());
                feeDo.setUpdateBy(null);
                feeDo.setUpdateTime(null);
                int i = tFeeDoMapper.insertTFeeDo(feeDo);
            }
            tFeeInvoice.setfBillstatus(billStatus);
            tFeeInvoice.setfPid(fPid);
            tFeeInvoice.setCreateBy(loginUser.getUser().getUserName());
            tFeeInvoice.setCreateTime(new Date());
            tFeeInvoiceMapper.insertTFeeInvoice(tFeeInvoice);
            /*}*/
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("申请发票出错,请找管理员");
        }
        return AjaxResult.success();
    }

    /**
     * 判断金额是否超过可用金额
     *
     * @param fid   费用明细表主键
     * @param money 申请金额
     * @param type  DZ 对账 SF 收费 FF 付费 ApplyFP 开票申请  invoiceFP 开票
     * @return
     */
    public Map<String,Object> judgeMoney(long fid, BigDecimal money, String type,Long feeId) {
        Map<String,Object> map = new HashMap<>();
        boolean flag = true;
        TWarehousebillsfees warehousebillsfees = tWarehousebillsfeesMapper.selectTWarehousebillsfeesById(fid);
        TFees tFees = tFeesMapper.selectTFeesById(feeId);
        BigDecimal amount = warehousebillsfees.getfAmount();//金额
        BigDecimal accamount = warehousebillsfees.getfAccamount();//对账金额
        BigDecimal stlamount = warehousebillsfees.getfStlamount();//结算金额
        BigDecimal invamount = warehousebillsfees.getfInvamount();//开票金额a
        BigDecimal askamount = warehousebillsfees.getfAskamount();//申请金额
        if (warehousebillsfees == null) {
            map.put("message","费用明细数据有误,请找管理员");
        }else if ("DZ".equals(type) || "KHDZ".equals(type)) {
            BigDecimal subtract = amount.subtract(accamount);
            int i = subtract.compareTo(money);
            if (i == -1){
                flag = false;
                map.put("message",tFees.getfName()+"对账金额超过可对账金额,当前可对账金额为"+subtract+"元");
            }
        }else if ("SF".equals(type) ||"KHSF".equals(type)) {
            BigDecimal subtract = amount.subtract(stlamount);
            int i = subtract.compareTo(money);
            if (i == -1){
                flag = false;
                map.put("message",tFees.getfName()+"收费金额超过可收费金额,当前可对账金额为"+subtract+"元");
            }
        }else if ("FF".equals(type)||"KHFF".equals(type)) {
            BigDecimal subtract = amount.subtract(stlamount);
            int i = subtract.compareTo(money);
            if (i == -1){
                flag = false;
                map.put("message",tFees.getfName()+"付费金额超过可付费金额,当前可对账金额为"+subtract+"元");
            }
        }else if ("ApplyFP".equals(type)) {
            BigDecimal subtract = amount.subtract(askamount);
            int i = subtract.compareTo(money);
            if (i == -1){
                flag = false;
                map.put("message",tFees.getfName()+"开票金额超过可开票金额,当前可对账金额为"+subtract+"元");
            }
        }else if ("invoiceFP".equals(type)) {
            BigDecimal subtract = amount.subtract(invamount);
            int i = subtract.compareTo(money);
            if (i == -1){
                flag = false;
                map.put("message",tFees.getfName()+"开票金额超过可开票金额,当前可对账金额为"+subtract+"元");
            }
        }
        map.put("flag",flag);
        return map;
    }

    /**
     * 申请发票审核成功复制数据到销项发票中
     * @param fId  主表id
     * @param fBilltype  类型
     * @return
     */
    @Transactional
    public AjaxResult copyInvoiceFp(Long fId,String fBilltype){
        //查询费用主表信息复制主表信息
        Integer insert = null;
        TFee fee = tFeeMapper.selectTFeeById(fId);
        TFee tFee = new TFee();
        tFee.setfId(fee.getfId());
        Date time = new Date();
        String billNo = billnoSerialServiceImpl.getBillNo(fBilltype, time);
        //查询费用从表信息复制主表信息
        fee.setfAccountId(fee.getfId());
        fee.setfBillno(billNo);
        fee.setfBilltype(fBilltype);
        fee.setfId(null);
        insert = tFeeMapper.insertTFee(fee);
        tFee.setfMake(1);
        //修改原发票数据代表已开销项发票
        insert = tFeeMapper.updateTFee(tFee);
        TFeeDo tFeeDo = new TFeeDo();
        tFeeDo.setfPid(fId);
        List<TFeeDo> tFeeDoList = tFeeDoMapper.selectTFeeDoList(tFeeDo);
        if (CollectionUtils.isNotEmpty(tFeeDoList)){
            for (TFeeDo feeDo : tFeeDoList) {
                feeDo.setfId(null);
                feeDo.setfPid(fee.getfId());
                feeDo.setfBilltype(fBilltype);
                insert = tFeeDoMapper.insertTFeeDo(feeDo);
            }
        }
        //查询开票信息复制主表信息
        TFeeInvoice tFeeInvoice = new TFeeInvoice();
        tFeeInvoice.setfPid(fId);
        List<TFeeInvoice> tFeeInvoiceList = tFeeInvoiceMapper.selectTFeeInvoiceList(tFeeInvoice);
        if (CollectionUtils.isNotEmpty(tFeeInvoiceList)){
            for (TFeeInvoice invoice : tFeeInvoiceList) {
                invoice.setfId(null);
                invoice.setfPid(fee.getfId());
                insert = tFeeInvoiceMapper.insertTFeeInvoice(invoice);
            }
        }
        if (insert != null && insert >0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error("生成销项发票失败,请找管理员");
        }
    }


}
