package cn.ezhizao.project.business.collection.controller;

import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.common.utils.uuid.SnowflakeIdWorker;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.annotation.distributedLock;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.domain.BaseEntity;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.account.domain.BizAccount;
import cn.ezhizao.project.business.account.service.IBizAccountService;
import cn.ezhizao.project.business.collection.domain.BizCollection;
import cn.ezhizao.project.business.collection.domain.BizCollectionDetail;
import cn.ezhizao.project.business.collection.domain.CollectionExcelLoopModel;
import cn.ezhizao.project.business.collection.domain.CollectionExcelOnceModel;
import cn.ezhizao.project.business.collection.domain.vo.ReqStatisticsVo;
import cn.ezhizao.project.business.collection.domain.vo.ResStatisticsVo;
import cn.ezhizao.project.business.collection.service.IBizCollectionDetailService;
import cn.ezhizao.project.business.collection.service.IBizCollectionService;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.business.order.domain.BizArchiveInput;
import cn.ezhizao.project.business.order.domain.BizArchiveInputDetail;
import cn.ezhizao.project.business.order.service.IBizArchiveInputDetailService;
import cn.ezhizao.project.business.order.service.IBizArchiveInputService;
import cn.ezhizao.project.business.payment.domain.BizPayment;
import cn.ezhizao.project.business.payment.domain.BizPaymentDetail;
import cn.ezhizao.project.business.taskType.domain.BizTaskType;
import cn.ezhizao.project.business.taskType.service.IBizTaskTypeService;
import cn.ezhizao.project.system.domain.SysDictData;
import cn.ezhizao.project.system.domain.SysFileStorage;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.service.ISysDictDataService;
import cn.ezhizao.project.system.service.ISysFileStorageService;
import cn.ezhizao.project.system.service.ISysUserService;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import static cn.ezhizao.common.utils.PageUtils.custStartPage;

@RestController
@Api(tags = "收票 数据接口")
@RequestMapping(value = "/business/collection")
public class BizCollectionController extends BaseController {
    @Resource
    IBizCollectionService collectionService;
    @Resource
    ResourceLoader resourceLoader;
    @Resource
    IBizCollectionDetailService collectionDetailService;
    @Resource
    IBizArchiveInputDetailService contractDetailService;
    @Resource
    IBizArchiveInputService archiveInputService;
    @Resource
    ISysFileStorageService fileStorageService;
    @Resource
    IBizCompanyService companyService;
    @Resource
    ISysUserService userService;
    @Resource
    SnowflakeIdWorker snowflakeIdWorker;
    @Resource
    IBizAccountService accountService;

    @Resource
    IBizTaskTypeService taskTypeService;


    @Resource
    ISysDictDataService sysDictDataService;
    @PreAuthorize("@ss.hasPermi('business:collection:query')")
    @GetMapping(value = "/{id}")
    @ResponseBody
    public AjaxResult getById(@PathVariable Long id) {
        BizCollection collection = getForId(id);
        return success(collection);
    }

    @GetMapping(value = "/detail/{id}")
    @ResponseBody
    public AjaxResult getCollectionDetailByInputId(@PathVariable Long id) {
        ArrayList<BizCollectionDetail> bizCollectionDetails = new ArrayList<>();
        //实收金额
        List<BizCollectionDetail> list = collectionDetailService.list(new LambdaQueryWrapper<BizCollectionDetail>()
                .eq(BizCollectionDetail::getContractId, id));
        for (BizCollectionDetail detail : list) {
            Long collectionId = detail.getCollectionId();
            BizCollection byId = collectionService.getById(collectionId);
            if (byId.getStatus()!=2){
                bizCollectionDetails.add(detail);
            }
        }
//        BigDecimal detailAmount  = list.stream().map(m -> m.getArriveAmount()).reduce(BigDecimal::add).get();
        return success(bizCollectionDetails);
    }

    @ApiOperation(value = "主从保存", notes = "主从保存")
    @PostMapping("/save")
    @PreAuthorize("@ss.hasPermi('business:collection:edit')")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @distributedLock(prefix = "financialCollectionSaveAll",key = "#collection.contractId")
    public AjaxResult saveAll(@RequestBody BizCollection collection) throws NoSuchFieldException, IllegalAccessException {
        boolean changeFormNo = true;
        final String redisKey = "collection_flow_no";
        setTenantId(collection);
        try {
            Long id = collection.getId();
            collection.setFormDate(collection.getFormDate() != null ? collection.getFormDate() : DateTime.now().toTimestamp());
            collection.setId(collection.getId() == null || collection.getId().equals(0L) ? snowflakeIdWorker.nextId() : collection.getId());

            if (collection.getFlowNo() == null || collection.getFlowNo().isEmpty()) {
                collection.setFlowNo(collection.getId().toString());
            }
            Long tenantId = getTenantId();
            long count = collectionService.query()
                    .eq("tenant_id", tenantId)
                    .eq("flow_no", collection.getFlowNo())
                    .ne("id", collection.getId())
                    .count();
            if (count > 0) {
//                changeFormNo = false;
                return error("流水号重复");
            }
            // 先删除明细
            SysFileStorage conditions = new SysFileStorage();

            List<SysFileStorage> files = collection.getFiles();

            files.forEach(l -> {
                l.setId(l.getId() == null || l.getId().equals(0L) ? snowflakeIdWorker.nextId() : l.getId());
                l.setMasterId(collection.getId());
                l.setMasterTableName("biz_collection");
            });


            conditions.setMasterTableName("biz_collection");
            conditions.setMasterId(collection.getId());
            fileStorageService.physicalDelete(conditions);

            List<BizCollectionDetail> details = collection.getDetails();
            details.forEach(l -> {
                l.setCollectionId(collection.getId());
                l.setTenantId(getTenantId());
            });
            BizCollectionDetail delConditions = new BizCollectionDetail();
            delConditions.setCollectionId(collection.getId());
            collectionDetailService.physicallyDelete(delConditions);

            return collectionService.saveOrUpdate(collection) && (details.isEmpty() || collectionDetailService.saveOrUpdateBatch(details)) && (files.isEmpty() || fileStorageService.saveOrUpdateBatch(files)) ? success(collection) : error();
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @PreAuthorize("@ss.hasPermi('business:collection:list')")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo getList(BizCollection conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startPage();
        startOrderBy();
        List<BizCollection> list = collectionService.getListByBean(conditions);
        return getDataTable(list);
    }

    /**
     * 导出收款管理
     */
    @PreAuthorize("@ss.hasPermi('business:collection:export')")
    @Log(title = "收款管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizCollection conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startOrderBy();
        List<BizCollection> list = collectionService.getListByBean(conditions);
        list.forEach(l -> {
            switch (l.getStatus()) {
                case 0:
                    l.setStatusName("未审核");
                    break;
                case 1:
                    l.setStatusName("审核通过");
                    break;
                case 2:
                    l.setStatusName("审核不通过");
                    break;
            }
            switch (l.getArriveStatus()) {
                case 0:
                    l.setArriveStatusName("未支付");
                    break;
                case 1:
                    l.setArriveStatusName("已支付");
                    break;
                case 2:
                    l.setArriveStatusName("部分支付");
                    break;
            }
        });
        ExcelUtil<BizCollection> util = new ExcelUtil<BizCollection>(BizCollection.class);
        util.exportExcel(response, list, "收款信息");

    }

    @ApiOperation("获取待收款合同")
    @GetMapping("/getWaitForCollection")
    @PreAuthorize("@ss.hasPermi('business:waitForCollection:list')")
    public TableDataInfo getContractForCollection(BizArchiveInput conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startPage();
        startOrderBy();
        List<BizArchiveInput> list = archiveInputService.getList(conditions);
        return getDataTable(list);
    }


    @ApiOperation("修改收款状态")
    @Log(title = "修改收款状态", businessType = BusinessType.UPDATE)
    @PutMapping("/setCollectionStatus")
    @distributedLock(prefix = "financialCollectionSetStatus",key = "#conditions.id")
    public AjaxResult setCollectionStatus(@RequestBody BizArchiveInput conditions) throws NoSuchFieldException, IllegalAccessException {

        return success(archiveInputService.updateById(conditions));
    }


    @Log(title = "修改收款的状态", businessType = BusinessType.UPDATE)
    @GetMapping ("/setCollectionZero/{id}")
    @distributedLock(prefix = "financialSetCollectionZero",key = "#id")
    public AjaxResult setCollectionZero(@PathVariable Long id) {

        LambdaUpdateWrapper<BizCollection> eq = new LambdaUpdateWrapper<BizCollection>().set(BizCollection::getStatus, 0)
                .set(BizCollection::getVerifyStatus, 0)
                .set(BizCollection::getArriveStatus,0)
                .set(BizCollection::getVerifyDate, "0000-00-00 00:00:00")
                .eq(BizCollection::getId, id);
        BizCollection bizCollection = collectionService.getOne(new LambdaQueryWrapper<BizCollection>().eq(BizCollection::getId, id));
        BizArchiveInput bizArchiveInput = archiveInputService.getOne(new LambdaQueryWrapper<BizArchiveInput>().eq(BizArchiveInput::getId, bizCollection.getContractId()));
        if(null != bizArchiveInput && null != bizArchiveInput.getId()) {
            LambdaUpdateWrapper<BizArchiveInput> eq2 = new LambdaUpdateWrapper<BizArchiveInput>()
                    .set(BizArchiveInput::getCollectionStatus, 1)
                    .eq(BizArchiveInput::getId, bizArchiveInput.getId());
            archiveInputService.update(eq2);
        }
        return success(collectionService.update(eq));
    }
    @ApiOperation("获取对应合同的收款单")
    @GetMapping("/getCollectionByContract")
    @PreAuthorize("@ss.hasPermi('business:collection:add')")
    public AjaxResult getCollectionByContract(BizArchiveInput conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        BizArchiveInput bizArchiveInput = archiveInputService.getList(conditions).stream().findFirst().orElse(null);
        if (bizArchiveInput == null) {
            throw new ServiceException("合同不存在");
        }
        BizCollection bizCollection = new BizCollection();
        // 获取已收款合同

        List<BizCollection> collected = collectionService.query().eq("contract_id", conditions.getId()).eq("status", 1).list();

        if(!collected.isEmpty()){
            List<BizCollection> collectionSortList = collected.stream().sorted(Comparator.comparing(BaseEntity::getCreateTime).reversed()).collect(Collectors.toList());
            BizCollection oldCollection = collectionSortList.get(0);
            bizCollection.setProjectName(oldCollection.getProjectName());
            bizCollection.setIsProject(oldCollection.getIsProject());
            bizCollection.setProjectNo(oldCollection.getProjectNo());
            bizCollection.setProjectMainName(oldCollection.getProjectMainName());
        }
        BigDecimal collectedAmount = BigDecimal.valueOf(collected.stream().mapToDouble(v -> v.getArriveAmount().doubleValue()).sum());

        SysUser user = SecurityUtils.getLoginUser().getUser();
        bizCollection.setContractId(bizArchiveInput.getId())
                .setContractNo(bizArchiveInput.getContractNo())
                .setContractAmount(bizArchiveInput.getTrueAmount())
                .setCompanyName(bizArchiveInput.getCompanyName())
                .setApplierId(user.getUserId())
                .setApplierName(user.getNickName())
                .setCompanyId(bizArchiveInput.getCompanyId())
                .setPaymentAmount(collectedAmount)
                .setNonpaymentAmount(bizArchiveInput.getTrueAmount().subtract(collectedAmount))
                .setIsNew(bizArchiveInput.getContractType())
                .setBoss(bizArchiveInput.getBoss()).setParty(bizArchiveInput.getParty());
        BizArchiveInputDetail detailConditions = new BizArchiveInputDetail();
        detailConditions.setContractId(conditions.getId());
        List<BizArchiveInputDetail> details = contractDetailService.getList(detailConditions);
        details.forEach(l -> {
            BizCollectionDetail detail = new BizCollectionDetail();
            detail.setContractDetailId(l.getId());
            detail.setContractId(l.getContractId());
            detail.setTenantId(getTenantId());
            detail.setCompanyId(l.getCompanyId());
            detail.setCustomerName(bizArchiveInput.getCompanyName());
            detail.setTaskTypeName(l.getTaskTypeName());
            detail.setTaskTypeId(l.getTaskTypeId());
            detail.setAmount(l.getAmount());
            detail.setArrived(l.getArrived());
            detail.setAddressStyle(l.getAddressStyle());
            detail.setFictionAddressId(l.getFictionAddressId());
            detail.setProvince(l.getProvince());
            detail.setCity(l.getCity());
            detail.setDistrict(l.getDistrict());
            detail.setBelongRegion(l.getBelongRegion());
            detail.setRegionName(l.getRegionName());
            detail.setInputRemark(l.getRemark());
            if(l.getTaskTypeId() == 4 && l.getBelongRegion()  != null){
                SysDictData sysDictData = sysDictDataService.selectDictDataById(l.getBelongRegion().longValue());
                detail.setExplain( sysDictData.getDictLabel());
            }
            if (!ObjectUtils.isEmpty(l.getAddressStyle()) && l.getAddressStyle() == 1 ){
                if (StringUtils.isNotEmpty(detail.getExplain())){
                    detail.setExplain(detail.getExplain().concat(l.getProvince() + l.getCity() + l.getDistrict()));
                }else {
                    detail.setExplain(l.getProvince() + l.getCity() + l.getDistrict());
                }
            }else {
                SysDictData sysDictData = sysDictDataService.selectDictDataById(l.getFictionAddressId());
                if (sysDictData != null) {
                    detail.setExplain(sysDictData.getDictLabel());
                }
            }
            if(StringUtils.isNotEmpty(l.getRemark())) {
                detail.setExplain(detail.getExplain().concat("," + l.getRemark()));
            }

            bizCollection.getDetails().add(detail);
        });
        return success(bizCollection);
    }

    @ApiOperation(value = "主从保存", notes = "主从保存")
    @PostMapping("/checkArrive")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @distributedLock(prefix = "financialCollectionCheckArrive",key = "#conditions.id")
    public AjaxResult checkArrive(@RequestBody BizCollection collection) {

        AtomicBoolean collectionCheck = new AtomicBoolean(true);
        collection.getDetails().forEach(l -> {
            l.setCollectionId(collection.getId());
            BigDecimal arriveAmount = l.getArriveAmount();
            Map<String, Object> map = new HashMap<>(2);
            map.put("contractDetailId", l.getContractDetailId());
            map.put("verifyStatus", 1);
            List<BizCollectionDetail> vDetail = collectionDetailService.getList(map);
            arriveAmount = arriveAmount.add(BigDecimal.valueOf(vDetail.stream().mapToDouble(t -> t.getArriveAmount().doubleValue()).sum()));
            BizArchiveInputDetail contractDetail = contractDetailService.getById(l.getContractDetailId());
            collectionCheck.set(collectionCheck.get() && (contractDetail.getAmount().compareTo(arriveAmount) >= 0));

        });

        if (!collectionCheck.get()) {
            return error("收款金额已超出合同总额，确定继续么？");
        } else {
            return success();
        }
    }


    @ApiOperation("审核")
    @PostMapping("/verified")
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "收款管理审核", businessType = BusinessType.UPDATE)
    @distributedLock(prefix = "financialCollectionVerified",key = "#conditions.id")
    public AjaxResult verified(@RequestBody BizCollection collection) {
        try {
            collection.setVerifyId(getUserId());
            collection.setVerifyDate(collection.getVerifyDate() == null ? DateTime.now().toTimestamp() : collection.getVerifyDate());
            BizArchiveInput contract = archiveInputService.getById(collection.getContractId());
            if (contract != null) {
                if (collection.getVerifyDate() != null) {
                    contract.setCollectionStatus((byte) (collection.getStatus() == 1 ? 2 : 3));
                    archiveInputService.saveOrUpdate(contract);
                }
                if (!CollectionUtils.isEmpty(collection.getEvidenceFiles())) {
                    List<SysFileStorage> fileStorageList = collection.getEvidenceFiles();
                    fileStorageList.forEach(l -> {
                        l.setId(l.getId() == null || l.getId().equals(0L) ? snowflakeIdWorker.nextId() : l.getId());
                        l.setMasterId(collection.getId());
                        l.setMasterTableName("biz_collection");
                    });
                    fileStorageService.saveBatch(fileStorageList);
                }
            }
            return collectionService.saveOrUpdate(collection) ? success(collection) : error();

        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    @Log(title = "收款导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('business:collection:import')")
    @PostMapping("/importLoop")
    @distributedLock(prefix = "financialCollectionImportLoop",key = "@tenantId")
    public AjaxResult importLoop(MultipartFile file) throws Exception {
        ExcelUtil<CollectionExcelLoopModel> util = new ExcelUtil<>(CollectionExcelLoopModel.class);
        List<CollectionExcelLoopModel> orderList = util.importExcel(file.getInputStream());
        String message = collectionService.importLoop(orderList, SecurityUtils.getUserId(), getTenantId() == null ? 0 : getTenantId());
        return success(message);
    }

    @Log(title = "收款导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('business:collection:import')")
    @PostMapping("/importOnce")
    @distributedLock(prefix = "financialCollectionImportOnce",key = "@tenantId")
    public AjaxResult importOnce(MultipartFile file) throws Exception {
        ExcelUtil<CollectionExcelOnceModel> util = new ExcelUtil<>(CollectionExcelOnceModel.class);
        List<CollectionExcelOnceModel> orderList = util.importExcel(file.getInputStream());
        String message = collectionService.importOnce(orderList, SecurityUtils.getUserId(), getTenantId() == null ? 0 : getTenantId());
        return success(message);
    }

    @Log(title = "收款删除", businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('business:collection:remove')")
    @DeleteMapping("/del/{ids}")
    public AjaxResult del(@PathVariable List<Long> ids) throws Exception {

        return success(collectionService.removeCollectionBatchByIds(ids));
    }

    @Log(title = "合同收款模板导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('business:collection:import')")
    @PostMapping("/exportLoop")
    public void exportLoop(HttpServletResponse response) throws Exception {
        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:importTemplate/循环订单收款导入.xlsx");
        if (resource.exists()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            String fileName = resource.getURI().toString().substring(resource.getURI().toString().lastIndexOf("/") + 1);
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            //放弃使用直接获取文件的方式, 改成使用流的方式
            BufferedInputStream bis = new BufferedInputStream(resource.getInputStream());
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            if (bis != null) {
                bis.close();
            }
        }
    }

    @Log(title = "合同收款模板导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('business:collection:import')")
    @PostMapping("/exportOnce")
    public void exportOnce(HttpServletResponse response) throws Exception {
        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:importTemplate/单次订单收款导入.xlsx");
        if (resource.exists()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            String fileName = resource.getURI().toString().substring(resource.getURI().toString().lastIndexOf("/") + 1);
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            //放弃使用直接获取文件的方式, 改成使用流的方式
            BufferedInputStream bis = new BufferedInputStream(resource.getInputStream());
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            if (bis != null) {
                bis.close();
            }
        }
    }


    private BizCollection getForId(Long collectionId) {
        BizCollection collection = collectionService.getById(collectionId);
        if (collection != null) {
            BizArchiveInput condition = new BizArchiveInput();
            condition.setId(collection.getContractId());
            List<BizArchiveInput> archiveInputs = archiveInputService.getList(condition);
            BizArchiveInput archiveInput = archiveInputs.isEmpty() ? null : archiveInputs.get(0);
            if (archiveInput != null) {
                collection.setContractNo(archiveInput.getContractNo());
                collection.setContractAmount(archiveInput.getTrueAmount());
                collection.setOrderRemark(archiveInput.getRemark());
                collection.setBoss(archiveInput.getBoss());
                collection.setParty(archiveInput.getParty());
                BizCollection collectionCondition = new BizCollection();
                if (archiveInput.getFormDate() != null) {
                    collection.setActuallyDate(new Timestamp(archiveInput.getFormDate().getTime()));
                }
                collectionCondition.setContractId(archiveInput.getId());
                collectionCondition.setStatus((byte) 1);
                List<BizCollection> collections = collectionService.getListByBean(collectionCondition);
                collection.setNonpayment(archiveInput.getTrueAmount().subtract(BigDecimal.valueOf(collections.stream().mapToDouble(v -> v.getAmount().doubleValue()).sum())).compareTo(BigDecimal.ZERO) > 0);
                collection.setNonpaymentAmount(archiveInput.getTrueAmount().subtract(BigDecimal.valueOf(collections.stream().mapToDouble(v -> v.getArriveAmount().doubleValue()).sum())));
            }
            SysFileStorage fileConditions = new SysFileStorage();
            fileConditions.setMasterId(collection.getId());
            fileConditions.setMasterTableName("biz_collection");
            List<SysFileStorage> files = fileStorageService.getList(fileConditions);
            collection.setFiles(files);
            SysUser applier = userService.selectUserById(collection.getApplierId());
            BizCompany company = companyService.getById(collection.getCompanyId());
            collection.setApplierName(applier != null ? applier.getNickName() : "系统管理员");
            collection.setCompanyName(company == null ? collection.getCompanyName() : company.getName());

            BizCollectionDetail detailCondition = new BizCollectionDetail();
            detailCondition.setCollectionId(collection.getId());
            List<BizCollectionDetail> details = collectionDetailService.getListByBean(detailCondition);
            details.forEach(l -> {
                if(l.getTaskTypeId() == 4 && l.getBelongRegion() != null){
                    SysDictData sysDictData = sysDictDataService.selectDictDataById(l.getBelongRegion().longValue());
                    l.setExplain( sysDictData.getDictLabel());
                }
                if (!ObjectUtils.isEmpty(l.getAddressStyle()) && l.getAddressStyle() == 1 ){
                    if (StringUtils.isNotEmpty(l.getExplain())){
                        l.setExplain(l.getExplain().concat(l.getProvince() + l.getCity() + l.getDistrict()));
                    }else {
                        l.setExplain(l.getProvince() + l.getCity() + l.getDistrict());
                    }
                }else {
                    SysDictData sysDictData = sysDictDataService.selectDictDataById(l.getFictionAddressId());
                    if (sysDictData== null) {
                        return;
                    }
                    l.setExplain(sysDictData.getDictLabel());
                }
                if(StringUtils.isNotEmpty(l.getInputRemark())) {
                    l.setExplain(l.getExplain().concat("," + l.getInputRemark()));
                }
            });
            contractDetailAmount(collection.getContractId(),details);
            collection.setDetails(details);
        }
        return collection;
    }
    private void contractDetailAmount(Long contractId, List<BizCollectionDetail> list) {
        List<BizCollection> paymentList = collectionService.list(new LambdaQueryWrapper<BizCollection>().eq(BizCollection::getContractId, contractId).and(item->item.eq(BizCollection::getStatus, 0).or().eq(BizCollection::getStatus, 1)));
        List<Long> idList = paymentList.stream().map(m -> m.getId()).collect(Collectors.toList());
        if (idList.size() > 0) {
            List<BizCollectionDetail> bizPaymentDetailList = collectionDetailService.list(new LambdaQueryWrapper<BizCollectionDetail>().in(BizCollectionDetail::getCollectionId, idList));
            Map<Long, BigDecimal> taskTypeToTotalAmount = bizPaymentDetailList.stream()
                    .collect(Collectors.groupingBy(BizCollectionDetail::getTaskTypeId,
                            Collectors.reducing(BigDecimal.ZERO, BizCollectionDetail::getArriveAmount, BigDecimal::add)));
            for (BizCollectionDetail detail : list) {
                BigDecimal bigDecimal = taskTypeToTotalAmount.get(detail.getTaskTypeId());
                detail.setCountAmount(bigDecimal);
                detail.setReviewAmount(detail.getArriveAmount());
            }
        }
    }

    /**
     * 删除渠道
     */
    @PreAuthorize("@ss.hasPermi('business:collection:remove')")
    @Log(title = "渠道", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(collectionService.removeBatchByIds(ids));
    }

    @ApiOperation("获取账户")
    @GetMapping("/listAccount")
    @PreAuthorize("@ss.hasPermi('business:payment:query')")
    public TableDataInfo listAccount(BizAccount bizAccount) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizAccount);
        startPage();
        List<BizAccount> list = accountService.getList(bizAccount);
        return getDataTable(list);
    }

    @ApiOperation("收款统计报表")
    @GetMapping("/statistics")
    public TableDataInfo statistics(ReqStatisticsVo conditions) throws NoSuchFieldException, IllegalAccessException {
        startPage();
        List<ResStatisticsVo> list = collectionService.statistics(conditions);
        return getDataTable(list);
    }

    @ApiOperation("导出收款统计报表")
//    @PreAuthorize("@ss.hasPermi('business:salary:export')")
    @Log(title = "导出收款统计报表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportStatistics")
    public void exportStatistics(ReqStatisticsVo conditions, HttpServletResponse response) throws NoSuchFieldException, IllegalAccessException {
        List<ResStatisticsVo> list = collectionService.statistics(conditions);
        ExcelUtil<ResStatisticsVo> util = new ExcelUtil<ResStatisticsVo>(ResStatisticsVo.class);
        util.exportExcel(response, list, "工资数据");
    }

    @ApiOperation("获取任务列表")
    @PostMapping("/listTask")
    public List<BizTaskType> listTask() {
        return taskTypeService.getList(new BizTaskType());
    }

    @ApiOperation("通过合同id查询具体收入支出")
    @PostMapping("/getByContract")
    public AjaxResult getByContract(@RequestBody  ReqStatisticsVo conditions) {
        HashMap<String, List<ResStatisticsVo>> map = new HashMap<>();
        //收款
        List<ResStatisticsVo> inList = collectionService.getByContractIn(conditions);
        //支出
        List<ResStatisticsVo> outList = collectionService.getByContractOut(conditions);
        map.put("inList", inList);
        map.put("outList", outList);
        return success(AjaxResult.success(map));
    }


}
