package com.junmp.jyzb.jyzbthirdparty.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.junmp.jyzb.jyzbthirdparty.api.SyncOrderApi;
import com.junmp.jyzb.jyzbthirdparty.bean.dto.*;
import com.junmp.jyzb.jyzbthirdparty.bean.req.*;
import com.junmp.jyzb.jyzbthirdparty.bean.res.PlatformResult;
import com.junmp.jyzb.jyzbthirdparty.entity.*;
import com.junmp.jyzb.jyzbthirdparty.exception.ThirdPartyException;
import com.junmp.jyzb.jyzbthirdparty.exception.enums.ErrorExceptionEnum;
import com.junmp.jyzb.jyzbthirdparty.expander.ThirdPartyExpander;
import com.junmp.jyzb.jyzbthirdparty.mapper.TPCabinetBoxPoliceMapper;
import com.junmp.jyzb.jyzbthirdparty.mapper.TPInvSummaryMapper;
import com.junmp.jyzb.jyzbthirdparty.mapper.TPInventoryMapper;
import com.junmp.jyzb.jyzbthirdparty.mapper.ThirdPartyMapper;
import com.junmp.jyzb.jyzbthirdparty.service.*;
import com.junmp.v2.auth.api.context.LoginContext;
import com.junmp.v2.auth.api.password.IStoredEncryptApi;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.dict.entity.SysDictItem;
import com.junmp.v2.dict.service.SysDictItemService;
import com.junmp.v2.sys.api.bean.role.dto.SysRoleDto;
import com.junmp.v2.sys.api.expander.SystemConfigExpander;
import com.junmp.v2.sys.user.entity.SysUser;
import com.junmp.v2.sys.user.entity.SysUserRole;
import com.junmp.v2.sys.user.service.SysUserOrgService;
import com.junmp.v2.sys.user.service.SysUserRoleService;
import com.junmp.v2.sys.user.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ThirdServiceImpl implements ThirdPartyService{

    @Resource
    private ThirdPartyMapper thirdPartyMapper;

    @Resource
    private TPInvSummaryService tpInvSummaryService;

    @Resource
    private TPOrderDetailService tpOrderDetailService;

    @Resource
    private TPOrderMainService tpOrderMainService;

    @Resource
    private TPLogSummaryService tpLogSummaryService;

    @Resource
    private SyncOrderApi syncOrderApi;

    @Resource
    private TPWarehouseInvService tpWarehouseInvService;

    @Resource
    private TPInventoryService tpInventoryService;

    @Resource
    private TPInventoryMapper tpInventoryMapper;

    @Resource
    private TPInvSummaryMapper tpInvSummaryMapper;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysUserOrgService sysUserOrgService;

    @Resource
    private TPPolicemanService tpPolicemanService;

    @Resource
    private TPCabinetBoxService tpCabinetBoxService;

    @Resource
    private TPCabinetService tpCabinetService;

    @Resource
    private IStoredEncryptApi iStoredEncryptApi;

    @Resource
    private TPCabinetBoxPoliceService tpCabinetBoxPoliceService;

    @Resource
    private TPCabinetBoxPoliceMapper tpCabinetBoxPoliceMapper;

    @Resource
    private SysDictItemService sysDictItemService;


    /**
     * 组织机构信息同步
     * @param req
     * @return
     */
    @Override
    public List<TPPubOrgDto> SyncPubOrg(TPPubOrgReq req) {
        List<TPPubOrgDto> pubList=thirdPartyMapper.SyncPubOrg(req.getOrgId(), req.getOrgCode(), req.getUpdateTime());
        if (CollectionUtil.isNotEmpty(pubList)){
            for (TPPubOrgDto org:pubList){
                String[] ids = org.getOrgParentIds().split(",");

                // 构建新字符串列表
                List<String> newList = new ArrayList<>();
                for (int i=0;i<ids.length;i++) {
                    if ((i+1)<ids.length){
                        newList.add("[" + ids[i] + "],");
                    }else {
                        newList.add("[" + ids[i] + "]");
                    }
                }
                // 构建最终字符串
                String finalString = String.join("", newList);
                org.setOrgParentIds(finalString);
            }
            return pubList;
        }else {
            return new ArrayList<>();
        }
    }


    /**
     * 仓库信息同步
     * @param req
     * @return
     */
    @Override
    public List<TPWarehouseDto> SyncWarehouse(TPWarehouseReq req) {
        if (ObjectUtil.isNull(req.getOrgId()) && ObjectUtil.isEmpty(req.getOrgCode()) && StrUtil.isEmpty(req.getOrgCode())){
            throw new ServiceException(ErrorExceptionEnum.ORG_ERROR);
        }

        List<TPWarehouseDto> warehouseList=thirdPartyMapper.SyncWarehouse(req.getOrgId(),req.getOrgCode(),req.getUpdateTime());
        return ObjectUtil.isNotEmpty(warehouseList)?warehouseList:new ArrayList<>();
    }


    /**
     * 装备基础信息同步
     * @param req
     * @return
     */
    @Override
    public List<TPTypeDto> SyncType(TPTypeReq req) {
        List<TPTypeDto> typeList=thirdPartyMapper.SyncType(req.getType(),req.getUpdateTime());
        return ObjectUtil.isNotEmpty(typeList)?typeList:new ArrayList<>();
    }


    /**
     * 装备号型基础信息同步
     * @param req
     * @return
     */
    @Override
    public List<TPSizeDto> SyncSize(TPSizeReq req) {
        List<TPSizeDto> sizeList=thirdPartyMapper.SyncSize(req.getTypeCode(),req.getUpdateTime());
        return ObjectUtil.isNotEmpty(sizeList)?sizeList:new ArrayList<>();
    }


    /**
     * 供应商基础信息同步
     * @param req
     * @return
     */
    @Override
    public List<TPSupplierDto> SyncSupplier(TPSupplierReq req) {
        List<TPSupplierDto> supplierList=thirdPartyMapper.SyncSupplier(req.getUpdateTime());
        return ObjectUtil.isNotEmpty(supplierList)?supplierList:new ArrayList<>();
    }

    /**
     * 用户信息同步(除去警员的账号，警员的账号另外接口进行同步)
     * @param req
     * @return
     */
    @Override
    public List<TPUserDto> SyncUser(TPUserReq req) {
        List<TPUserDto> userList=thirdPartyMapper.SyncUser(req.getOrgId(),req.getUpdateTime());
        if (CollectionUtil.isNotEmpty(userList)){
            List<Long> userIdsList = userList.stream().map(TPUserDto::getUserId).collect(Collectors.toList());
            List<SysUserRole> list1=thirdPartyMapper.getRoleIdsByUserIds(userIdsList);
            Map<Long, List<Long>> userIdToRoleIds = list1.stream()
                    .collect(Collectors.groupingBy(
                            SysUserRole::getUserId,      // 使用 SysUserRole 的 getUserId 方法
                            Collectors.mapping(SysUserRole::getRoleId, Collectors.toList())
                    ));
            userList.forEach(item2 -> {
                List<Long> roleIds = userIdToRoleIds.getOrDefault(item2.getUserId(), new ArrayList<>());
                item2.setRolesIdList(roleIds);
            });
            return userList;
        }else {
            return new ArrayList<>();
        }
    }

    @Override
    public TPBaseInfoDto syncBaseInfo(TPBaseInfoReq req) {
        TPBaseInfoDto tpBaseInfoDto = new TPBaseInfoDto();
        List<TPBaseInfoDto.goodsDto> goodsList=thirdPartyMapper.getGoodList(req.getUpdateTime());
        List<TPBaseInfoDto.sizeDto> sizeList=thirdPartyMapper.getSizeList(req.getUpdateTime());
        List<TPBaseInfoDto.typeDto> typeList=thirdPartyMapper.getTypeList(req.getUpdateTime());
        tpBaseInfoDto.setGoodsList(CollectionUtil.isNotEmpty(goodsList)?goodsList:new ArrayList<>());
        tpBaseInfoDto.setTypeList(CollectionUtil.isNotEmpty(typeList)?typeList:new ArrayList<>());
        tpBaseInfoDto.setSizeList(CollectionUtil.isNotEmpty(sizeList)?sizeList:new ArrayList<>());
        return tpBaseInfoDto;
    }

    /**
     * 同步警柜信息
     * @param req
     * @return
     */
    @Override
    public List<TPCabinetDto> syncCabinet(TPCabinetReq req) {
        //先获取所有组织机构下面的警柜
        List<TPCabinetDto> cabDtoList=thirdPartyMapper.getCabinetList(req.getCabinetId(),req.getOrgId(),req.getUpdateTime());
        //在通过所有的警柜id获取到所有的箱门信息
        if (CollectionUtil.isNotEmpty(cabDtoList)){
            List<String> cabinetIdList = cabDtoList.stream().map(TPCabinetDto::getCabinetId)
                    .collect(Collectors.toList());
            List<TPCabinetDto.TPCabinetBoxDto> boxDtoList=thirdPartyMapper.getBoxList(cabinetIdList);
            Map<String,List<TPCabinetDto.TPCabinetBoxDto>> cabMap=new HashMap<>();
            for (TPCabinetDto.TPCabinetBoxDto boxDto:boxDtoList) {
                if (cabMap.containsKey(boxDto.getCabinetId())){
                    List<TPCabinetDto.TPCabinetBoxDto> boxList = cabMap.get(boxDto.getCabinetId());
                    boxList.add(boxDto);
                    cabMap.put(boxDto.getCabinetId(),boxList);
                }else {
                    List<TPCabinetDto.TPCabinetBoxDto> boxList=new ArrayList<>();
                    boxList.add(boxDto);
                    cabMap.put(boxDto.getCabinetId(),boxList);
                }
            }
            for (TPCabinetDto cabinetDto:cabDtoList) {
                if (cabMap.containsKey(cabinetDto.getCabinetId())){
                    cabinetDto.setBoxList(cabMap.get(cabinetDto.getCabinetId()));
                }else {
                    cabinetDto.setBoxList(new ArrayList<>());
                }
            }
            return cabDtoList;
        }else {
            return new ArrayList<>();
        }
        //最后通过遍历，将对应箱门信息放入对应的单警柜中去并且返回list
    }

    @Override
    public List<TPInOrderDto> syncInOrder(TPInOrderReq req) {
        //主单据List
        List<TPInOrderDto> dtoList=thirdPartyMapper.getInOrderList(req.getOrgId(),req.getUpdateTime());
        if (CollectionUtil.isNotEmpty(dtoList)){
            List<String> orderIdList = dtoList.stream().map(TPInOrderDto::getBillId).collect(Collectors.toList());
            List<TPInOrderDto.TPInOrderDetailDto> detailDtoList=thirdPartyMapper.getInOrderDetailList(orderIdList);
            Map<String, List<TPInOrderDto.TPInOrderDetailDto>> orderIdMap = detailDtoList.stream()
                    .collect(Collectors.groupingBy(TPInOrderDto.TPInOrderDetailDto::getRefBillId));
            dtoList.forEach(tpInOrderDto -> tpInOrderDto.setDetailList(orderIdMap.get(tpInOrderDto.getBillId())));
        }
        //子单据list
        return CollectionUtil.isNotEmpty(dtoList)?dtoList:new ArrayList<>();
    }

    @Override
    public List<TPOutOrderDto> syncOutOrder(TPOutOrderReq req) {
        List<TPOutOrderDto> dtoList=thirdPartyMapper.getOutOrderList(req.getOrgId(),req.getUpdateTime());
        if (CollectionUtil.isNotEmpty(dtoList)){
            List<String> orderIdList = dtoList.stream().map(TPOutOrderDto::getBillId).collect(Collectors.toList());
            List<TPOutOrderDto.TPOutOrderDetailDto> detailDtoList=thirdPartyMapper.getOutOrderDetailList(orderIdList);
            Map<String, List<TPOutOrderDto.TPOutOrderDetailDto>> orderIdMap = detailDtoList.stream()
                    .collect(Collectors.groupingBy(TPOutOrderDto.TPOutOrderDetailDto::getRefBillId));
            dtoList.forEach(tpOutOrderDto -> tpOutOrderDto.setDetailList(orderIdMap.get(tpOutOrderDto.getBillId())));
        }
        return CollectionUtil.isNotEmpty(dtoList)?dtoList:new ArrayList<>();
    }

    @Override
    public boolean syncInvSummary(TPSummaryReq req) {
        Long orgId = req.getOrgId();
        List<TPSummaryReq.SummaryListReq> summaryList = req.getSummaryList();
        TPOrgInfoDto orgInfoDto = thirdPartyMapper.getOrgInfo(orgId);
        //删除全部
        List<TPInvSummary> list = tpInvSummaryService.list(new LambdaQueryWrapper<TPInvSummary>()
                .eq(TPInvSummary::getOrgId, orgId));
        //需要先判断是否存在装备，如果不存在则直接插入即可
        boolean removeResult=false;
        if (CollectionUtil.isNotEmpty(list)){
            removeResult = tpInvSummaryService.removeBatchByIds(list);
        }else {
            removeResult=true;
        }


        if (!removeResult){
            throw new ServiceException(ErrorExceptionEnum.INV_SUMMARY_SYNC_ERROR);
        }
        if (CollectionUtil.isNotEmpty(summaryList)){

            List<TPInvSummary> invSummaryList = summaryList.stream().map(summaryReq -> {
                TPInvSummary invSummary = new TPInvSummary();
                BeanPlusUtil.copyProperties(summaryReq, invSummary);
                String valueKey = createValueKey(orgInfoDto.getOrgCode(), summaryReq.getLocationId(), summaryReq.getGoodsCode(), summaryReq.getSpecId(), null, "0");
                invSummary.setValuekey(valueKey);
                invSummary.setOrgCode(orgInfoDto.getOrgCode());
                invSummary.setOrgName(orgInfoDto.getOrgName());
                invSummary.setTypeId(summaryReq.getGoodsCode());
                invSummary.setTypeName(summaryReq.getGoodsName());
                invSummary.setSizeId(summaryReq.getSpecId());
                invSummary.setSizeName(summaryReq.getModelName());
                invSummary.setCreateTime(new Date());
                invSummary.setUpdateTime(new Date());
                return invSummary;
            }).collect(Collectors.toList());
            return tpInvSummaryService.saveBatch(invSummaryList);
        }
        return true;
    }

    /**
     * 出库记账
     * @param req
     * @return
     */
    @Override
    @Transactional
    public boolean syncOutOrderAccounting(TPOutOrderAccountReq req) {

        if (CollectionUtil.isNotEmpty(req.getOrderList())){
            new Thread(()->{
                List<String> orderIdList = req.getOrderList().stream().map(TPOutOrderAccountReq.OutReq::getBillId).collect(Collectors.toList());

                //获取主单据
                List<TPOrderMain> orderlist = tpOrderMainService.list(new LambdaQueryWrapper<TPOrderMain>().in(TPOrderMain::getId, orderIdList));
                Long orgId = orderlist.get(0).getStartOrgId();
                String storeId=req.getOrderList().get(0).getStoreId();
                String storeName=req.getOrderList().get(0).getStoreName();
                TPOrgInfoDto orgInfo = thirdPartyMapper.getOrgInfo(orgId);
//            TPWarehouseDto warehouseDto=thirdPartyMapper.getOneWarehouse(orgId);
                //获取详情
                List<TPOutOrderAccountReq.OutDetailReq> orderDetailList = req.getOrderList().stream()
                        .flatMap(outReq -> outReq.getDetailList().stream())
                        .collect(Collectors.toList());

                for (TPOutOrderAccountReq.OutReq outReq:req.getOrderList()){
                    for (TPOrderMain orderMain:orderlist){
                        if (outReq.getBillId().equals(orderMain.getId())){
                            orderMain.setActualQuantity(outReq.getActualQty());
                            orderMain.setManualState(1);
                            orderMain.setOrderState("finished");
                            orderMain.setUpdateTime(new Date());
                        }
                    }
                }
                //更新主单据
                tpOrderMainService.updateBatchById(orderlist);
                //查询出子单据
                List<TPOrderDetail> detailList = tpOrderDetailService.list(new LambdaQueryWrapper<TPOrderDetail>()
                        .in(TPOrderDetail::getOrderId, orderIdList));
                Map<String,Object[]> invMap=new HashMap<>();
                Map<String,Object[]> searchMap=new HashMap<>();
                for (TPOutOrderAccountReq.OutDetailReq detailReq:orderDetailList) {
                    for (TPOrderDetail orderDetail:detailList) {
                        if (detailReq.getDetailId().equals(orderDetail.getId().toString())){
                            orderDetail.setActualNum(detailReq.getActualQty());
                            orderDetail.setModifyQuantity(detailReq.getModifyQty());
                            orderDetail.setWarehouseId(storeId);
                            orderDetail.setWarehouseName(storeName);

                            //存入map为了方便查询InvList（进行统计数量）
                            if (ObjectUtil.isNotNull(detailReq.getModifyQty()) && ObjectUtil.isNotNull(detailReq.getActualQty()) && detailReq.getActualQty()>0 && detailReq.getModifyQty()>0){
                                BigDecimal price=BigDecimal.ZERO;
                                if (!orderDetail.getPrice().contains("/")){
                                    price=new BigDecimal(orderDetail.getPrice());
                                }
                                String valuekey=createValueKey(orgInfo.getOrgCode(), orderDetail.getWarehouseId(), detailReq.getGoodsCode(), detailReq.getSpecId(), price.toString(), "0");
                                if (invMap.containsKey(valuekey)){
                                    Object[] objects = invMap.get(valuekey);
                                    objects[4]=(int)objects[4]+detailReq.getModifyQty();
                                    invMap.put(valuekey,objects);
                                }else {
                                    Object[] item=new Object[]{orgInfo.getOrgId(),orderDetail.getWarehouseId(),orderDetail.getTypeId(),orderDetail.getSizeId(),price.toString(),detailReq.getModifyQty()};
                                    invMap.put(valuekey,item);
                                }
                            }
                        }
                    }

                }

                tpOrderDetailService.updateBatchById(detailList);
                //创建logSummary

                Map<String, List<TPOrderMain>> orderMap = orderlist.stream()
                        .collect(Collectors.groupingBy(TPOrderMain::getId));
                Map<String, List<TPOutOrderAccountReq.OutDetailReq>> orderDetailMap = orderDetailList.stream()
                        .collect(Collectors.groupingBy(TPOutOrderAccountReq.OutDetailReq::getRefBillId));

                List<TPLogSummary> addLogSummaryList=new ArrayList<>();
                for (String orderId:orderDetailMap.keySet()) {
                    TPLogSummary tpLogSummary = new TPLogSummary();
                    tpLogSummary.setOrgId(orgInfo.getOrgId());
                    tpLogSummary.setOrgName(orgInfo.getOrgName());
                    tpLogSummary.setOrderMainId(orderId);
                    tpLogSummary.setOrderCode(orderMap.get(orderId).get(0).getOrderCode());
                    tpLogSummary.setDeviceType(0);
                    tpLogSummary.setLocationId(storeId);
                    tpLogSummary.setLocationName(storeName);
                    tpLogSummary.setLocationType(0);
                    tpLogSummary.setEquipmentList(orderDetailMap.get(orderId).stream()
                            .map(TPOutOrderAccountReq.OutDetailReq::getGoodsName).collect(Collectors.joining(",")));
                    tpLogSummary.setOutInState("out");
                    tpLogSummary.setNumber(orderMap.get(orderId).get(0).getActualQuantity());
                    tpLogSummary.setCreateTime(new Date());
                    tpLogSummary.setUpdateTime(new Date());
                    tpLogSummary.setUseTime(new Date());
                    addLogSummaryList.add(tpLogSummary);

                }
                tpLogSummaryService.saveBatch(addLogSummaryList);

                //获取到InvList
                List<TPInventory> invList=new ArrayList<>();

                if (!invMap.isEmpty()){
                    List<Object[]> itemList=new ArrayList<>(invMap.values());
                    invList=tpInventoryMapper.getInfoList(itemList);
                    for (TPInventory inventory:invList) {
                        String key=inventory.getOrgId()+inventory.getLocationId()+inventory.getTypeId()+inventory.getSizeId()+inventory.getPrice();
                        if (searchMap.containsKey(key)){
                            Object[] objects = searchMap.get(key);
                            objects[5]=(Integer)objects[5]+1;
                            searchMap.put(key,objects);
                        }else {
                            Object[] item=new Object[]{inventory.getOrgId(),inventory.getLocationId(),inventory.getTypeId(),inventory.getSizeId(),inventory.getPrice(),1};
                            searchMap.put(key,item);
                        }

                    }
                }
                //更新库存汇总
                List<TPInvSummary> delList=new ArrayList<>();
                List<TPInvSummary> inventorySummaryList = tpInventoryMapper.selectSum(new ArrayList<>(searchMap.values()));
                for (String key:searchMap.keySet()) {
                    for (TPInvSummary invSummary:inventorySummaryList) {
                        String sumKey=invSummary.getOrgId()+invSummary.getLocationId()+invSummary.getTypeId()+invSummary.getSizeId()+invSummary.getUnitPrice();
                        if (key.equals(sumKey)){
                            Object[] objects = searchMap.get(key);
                            invSummary.setNumber(Math.max(invSummary.getNumber()-(int)objects[5],0));
                            invSummary.setStockNumber(Math.max(invSummary.getStockNumber()-(int)objects[5],0));
                            if (invSummary.getNumber()==0 && invSummary.getStockNumber()==0){
                                delList.add(invSummary);
                            }
                        }
                    }
                }
                if (CollectionUtil.isNotEmpty(delList)){
                    tpInvSummaryService.removeBatchByIds(delList);
                }
                tpInvSummaryService.updateBatchById(inventorySummaryList);
                //修改删除数据库Inventory和warehouseInventory中的数据
                List<String> epcList = invList.stream().map(TPInventory::getEpc).collect(Collectors.toList());
                tpInventoryService.removeBatchByIds(invList);
                tpWarehouseInvService.remove(new LambdaQueryWrapper<TPWarehouseInv>().in(TPWarehouseInv::getEpc,epcList));

            }).start();
            return true;

        }
        return false;
    }


    /**
     * 任务完成后上报一次单据出库数据
     * @param req
     * @return
     */
    @Override
    public Boolean syncOutOrderLastInfo(TPOutOrderAccountReq req) {
        if (CollectionUtil.isNotEmpty(req.getOrderList())){
            new Thread(()->{
                List<String> orderIdList = req.getOrderList().stream().map(TPOutOrderAccountReq.OutReq::getBillId).collect(Collectors.toList());

                //获取主单据
                List<TPOrderMain> orderlist = tpOrderMainService.list(new LambdaQueryWrapper<TPOrderMain>().in(TPOrderMain::getId, orderIdList));
                Long orgId = orderlist.get(0).getStartOrgId();
                String storeId=req.getOrderList().get(0).getStoreId();
                String storeName=req.getOrderList().get(0).getStoreName();
                TPOrgInfoDto orgInfo = thirdPartyMapper.getOrgInfo(orgId);
                //获取详情
                List<TPOutOrderAccountReq.OutDetailReq> orderDetailList = req.getOrderList().stream()
                        .flatMap(outReq -> outReq.getDetailList().stream())
                        .collect(Collectors.toList());

                for (TPOutOrderAccountReq.OutReq outReq:req.getOrderList()){
                    for (TPOrderMain orderMain:orderlist){
                        if (outReq.getBillId().equals(orderMain.getId())){
                            orderMain.setActualQuantity(outReq.getActualQty());
                            orderMain.setOrderState("finished");
                            orderMain.setUpdateTime(new Date());
                        }
                    }
                }
                //更新主单据
                tpOrderMainService.updateBatchById(orderlist);
                //查询出子单据
                List<TPOrderDetail> detailList = tpOrderDetailService.list(new LambdaQueryWrapper<TPOrderDetail>()
                        .in(TPOrderDetail::getOrderId, orderIdList));
                for (TPOutOrderAccountReq.OutDetailReq detailReq:orderDetailList) {
                    for (TPOrderDetail orderDetail:detailList) {
                        if (detailReq.getDetailId().equals(orderDetail.getId().toString())){
                            orderDetail.setActualNum(detailReq.getActualQty());
                            orderDetail.setModifyQuantity(detailReq.getModifyQty());
                            orderDetail.setWarehouseId(storeId);
                            orderDetail.setWarehouseName(storeName);
                        }
                    }

                }

                tpOrderDetailService.updateBatchById(detailList);
                //创建logSummary
                Map<String, List<TPOrderMain>> orderMap = orderlist.stream()
                        .collect(Collectors.groupingBy(TPOrderMain::getId));
                Map<String, List<TPOutOrderAccountReq.OutDetailReq>> orderDetailMap = orderDetailList.stream()
                        .collect(Collectors.groupingBy(TPOutOrderAccountReq.OutDetailReq::getRefBillId));

                //将出库记录删除
                tpLogSummaryService.remove(new LambdaQueryWrapper<TPLogSummary>()
                        .in(TPLogSummary::getOrderMainId, orderIdList)
                        .eq(TPLogSummary::getDeviceType,0));

                List<TPLogSummary> addLogSummaryList=new ArrayList<>();
                for (String orderId:orderDetailMap.keySet()) {
                    TPLogSummary tpLogSummary = new TPLogSummary();
                    tpLogSummary.setOrgId(orgInfo.getOrgId());
                    tpLogSummary.setOrgName(orgInfo.getOrgName());
                    tpLogSummary.setOrderMainId(orderId);
                    tpLogSummary.setOrderCode(orderMap.get(orderId).get(0).getOrderCode());
                    tpLogSummary.setDeviceType(0);
                    tpLogSummary.setLocationId(storeId);
                    tpLogSummary.setLocationName(storeName);
                    tpLogSummary.setLocationType(0);
                    tpLogSummary.setEquipmentList(orderDetailMap.get(orderId).stream()
                            .map(TPOutOrderAccountReq.OutDetailReq::getGoodsName).collect(Collectors.joining(",")));
                    tpLogSummary.setOutInState("out");
                    tpLogSummary.setNumber(orderMap.get(orderId).get(0).getActualQuantity());
                    tpLogSummary.setCreateTime(new Date());
                    tpLogSummary.setUpdateTime(new Date());
                    tpLogSummary.setUseTime(new Date());
                    tpLogSummary.setBussinessType(orderMap.get(orderId).get(0).getBussinessType());
                    tpLogSummary.setUserName(LoginContext.getContext().getLoginUser().getUserInfo().getRealName());
                    addLogSummaryList.add(tpLogSummary);

                }
                tpLogSummaryService.saveBatch(addLogSummaryList);

            }).start();
            return true;

        }
        return false;
    }


    /**
     * 入库记账
     * @param req
     * @return
     */
    @Override
    public boolean syncInOrderAccounting(TPInOrderAccountReq req) {

        if (CollectionUtil.isNotEmpty(req.getOrderList())){
            new Thread(()->{
                List<String> orderIdList = req.getOrderList().stream().map(TPInOrderAccountReq.InReq::getBillId).collect(Collectors.toList());

                //获取主单据
                List<TPOrderMain> orderlist = tpOrderMainService.list(new LambdaQueryWrapper<TPOrderMain>().in(TPOrderMain::getId, orderIdList));
                Long orgId = orderlist.get(0).getEndOrgId();
                String storeId=req.getOrderList().get(0).getStoreId();
                String storeName=req.getOrderList().get(0).getStoreName();
                TPOrgInfoDto orgInfo = thirdPartyMapper.getOrgInfo(orgId);
//                TPWarehouseDto warehouseDto=thirdPartyMapper.getOneWarehouse(orgId);
                //获取详情
                List<TPInOrderAccountReq.InDetailReq> orderDetailList = req.getOrderList().stream()
                        .flatMap(outReq -> outReq.getDetailList().stream())
                        .collect(Collectors.toList());
                for (TPInOrderAccountReq.InReq inReq:req.getOrderList()){
                    for (TPOrderMain orderMain:orderlist){
                        if (inReq.getBillId().equals(orderMain.getId())){
                            orderMain.setActualQuantity(inReq.getActualQty());
                            orderMain.setManualState(1);
                            orderMain.setOrderState("finished");
                            orderMain.setUpdateTime(new Date());
                        }
                    }
                }
                tpOrderMainService.updateBatchById(orderlist);
                List<TPOrderDetail> detailList = tpOrderDetailService.list(new LambdaQueryWrapper<TPOrderDetail>()
                        .in(TPOrderDetail::getOrderId, orderIdList));
                Map<String,TPOrderDetail> summaryMap=new HashMap<>();
                for (TPInOrderAccountReq.InDetailReq detailReq:orderDetailList) {
                    for (TPOrderDetail orderDetail:detailList) {
                        if (detailReq.getDetailId().equals(orderDetail.getId().toString())){
                            orderDetail.setActualNum(detailReq.getActualQty());
                            orderDetail.setModifyQuantity(detailReq.getModifyQty());
                            orderDetail.setWarehouseId(storeId);
                            orderDetail.setWarehouseName(storeName);

                            //存入list为了方便查询summaryList
                            String valuekey=createValueKey(orgInfo.getOrgCode(), orderDetail.getWarehouseId(), orderDetail.getTypeId(), orderDetail.getSizeId(), orderDetail.getPrice(),"0");
                            if (summaryMap.containsKey(valuekey)){
                                TPOrderDetail detail = summaryMap.get(valuekey);
                                Integer modifyQty = detail.getModifyQuantity()+detailReq.getModifyQty();
                                detail.setModifyQuantity(modifyQty);
                                summaryMap.put(valuekey,detail);
                            }else {
                                summaryMap.put(valuekey,orderDetail);
                            }
                        }
                    }
                }
                tpOrderDetailService.updateBatchById(detailList);
                //创建logSummary

                Map<String, List<TPOrderMain>> orderMap = orderlist.stream()
                        .collect(Collectors.groupingBy(TPOrderMain::getId));
                Map<String, List<TPInOrderAccountReq.InDetailReq>> orderDetailMap = orderDetailList.stream()
                        .collect(Collectors.groupingBy(TPInOrderAccountReq.InDetailReq::getRefBillId));

                List<TPLogSummary> addLogSummaryList=new ArrayList<>();
                for (String orderId:orderDetailMap.keySet()) {
                    TPLogSummary tpLogSummary = new TPLogSummary();
                    tpLogSummary.setOrgId(orgInfo.getOrgId());
                    tpLogSummary.setOrgName(orgInfo.getOrgName());
                    tpLogSummary.setOrderMainId(orderId);
                    tpLogSummary.setOrderCode(orderMap.get(orderId).get(0).getOrderCode());
                    tpLogSummary.setDeviceType(0);
                    tpLogSummary.setLocationId(storeId);
                    tpLogSummary.setLocationName(storeName);
                    tpLogSummary.setLocationType(0);
                    tpLogSummary.setEquipmentList(orderDetailMap.get(orderId).stream()
                            .map(TPInOrderAccountReq.InDetailReq::getGoodsName).collect(Collectors.joining(",")));
                    tpLogSummary.setOutInState("in");
                    tpLogSummary.setNumber(orderMap.get(orderId).get(0).getActualQuantity());
                    tpLogSummary.setCreateTime(new Date());
                    tpLogSummary.setUseTime(new Date());
                    tpLogSummary.setUpdateTime(new Date());
                    addLogSummaryList.add(tpLogSummary);

                }
                tpLogSummaryService.saveBatch(addLogSummaryList);
                List<TPInventory> addInvList=new ArrayList<>();
                List<TPWarehouseInv> addWareInvList=new ArrayList<>();
                Random random = new Random();
                //如果新增，添加新的虚拟epc入库
                for (TPOrderDetail orderDetail:summaryMap.values()) {
                    int num = orderDetail.getModifyQuantity(); // 获取 num 字段的值

                    // 根据 num 的值重复创建 Inventory 对象并添加到列表中
                    for (int i = 0; i < num; i++) {
                        //随机生成一个epc
                        Date date = new Date();
                        String epc="000000"+date.getTime()+(random.nextInt(900000) + 100000);

                        TPInventory tpInventory = createInvInfo( orderDetail.getWarehouseId(),
                                orderDetail.getTypeId(), orderDetail.getSizeId(), orgInfo.getOrgId(), orderDetail.getProductionDate(),
                                orderDetail.getMaintenancePeriod(), orderDetail.getWarrantyPeriod(), epc, orderlist.get(0).getSupplierId(), new BigDecimal(orderDetail.getPrice()) );
                        addInvList.add(tpInventory);

                        TPWarehouseInv tpWarehouseInv=createWareInvInfo(orgInfo.getOrgId(),orgInfo.getOrgName(),
                                orderDetail.getWarehouseId(),orderDetail.getWarehouseName(),epc,orderDetail.getTypeId(),
                                orderDetail.getTypeName(),orderDetail.getSizeId(), orderDetail.getSizeName());
                        addWareInvList.add(tpWarehouseInv);
                    }
                }
                if (CollectionUtil.isNotEmpty(addInvList)){
                    tpInventoryService.saveBatch(addInvList);
                }
                if (CollectionUtil.isNotEmpty(addWareInvList)){
                    tpWarehouseInvService.saveBatch(addWareInvList);
                }

                //更新库存汇总
                List<String> valuekeyList = new ArrayList<>(summaryMap.keySet());
                List<TPInvSummary> list = tpInvSummaryService.list(new LambdaQueryWrapper<TPInvSummary>().in(TPInvSummary::getValuekey, valuekeyList));
                List<TPInvSummary> addList=new ArrayList<>();
                for (TPInvSummary invSummary : list) {
                    Integer integer = summaryMap.get(invSummary.getValuekey()).getModifyQuantity();
                    invSummary.setStockNumber(invSummary.getStockNumber() + integer);
                    invSummary.setNumber(invSummary.getNumber() + integer);
                    summaryMap.remove(invSummary.getValuekey());
                }
                if (!summaryMap.isEmpty()){
                    //添加新的装备
                    for (String valuekey:summaryMap.keySet()) {
                        TPOrderDetail orderDetail = summaryMap.get(valuekey);
                        if (ObjectUtil.isNotNull(orderDetail.getModifyQuantity()) || orderDetail.getModifyQuantity()!=0){

                            TPInvSummary inventorySummary = createInventorySummary(orgInfo.getOrgId(),orgInfo.getOrgName(),orgInfo.getOrgCode(),
                                    orderDetail.getTypeId(),orderDetail.getTypeName(),orderDetail.getSizeId(),orderDetail.getSizeName(),
                                    orderDetail.getWarehouseId(),orderDetail.getWarehouseName(),orderDetail.getModifyQuantity(),
                                    orderDetail.getModifyQuantity(),valuekey,new BigDecimal(orderDetail.getPrice()));
                            addList.add(inventorySummary);
                        }
                    }
                }
                if (CollectionUtil.isNotEmpty(addList)){
                    tpInvSummaryService.saveBatch(addList);
                }
                tpInvSummaryService.updateBatchById(list);

            }).start();
            return true;

        }
        return false;
    }


    /**
     * 上报完成的入库单据（最后一次任务单据结束后上报）
     * @param req
     * @return
     */
    @Override
    public Boolean syncInOrderLastInfo(TPInOrderAccountReq req) {
        if (CollectionUtil.isNotEmpty(req.getOrderList())){
            new Thread(()->{
                List<String> orderIdList = req.getOrderList().stream().map(TPInOrderAccountReq.InReq::getBillId).collect(Collectors.toList());

                //获取主单据
                List<TPOrderMain> orderlist = tpOrderMainService.list(new LambdaQueryWrapper<TPOrderMain>().in(TPOrderMain::getId, orderIdList));
                Long orgId = orderlist.get(0).getEndOrgId();
                String storeId=req.getOrderList().get(0).getStoreId();
                String storeName=req.getOrderList().get(0).getStoreName();
                TPOrgInfoDto orgInfo = thirdPartyMapper.getOrgInfo(orgId);
                //获取详情
                List<TPInOrderAccountReq.InDetailReq> orderDetailList = req.getOrderList().stream()
                        .flatMap(outReq -> outReq.getDetailList().stream())
                        .collect(Collectors.toList());
                for (TPInOrderAccountReq.InReq inReq:req.getOrderList()){
                    for (TPOrderMain orderMain:orderlist){
                        if (inReq.getBillId().equals(orderMain.getId())){
                            orderMain.setActualQuantity(inReq.getActualQty());
                            orderMain.setOrderState("finished");
                            orderMain.setUpdateTime(new Date());
                        }
                    }
                }
                tpOrderMainService.updateBatchById(orderlist);
                List<TPOrderDetail> detailList = tpOrderDetailService.list(new LambdaQueryWrapper<TPOrderDetail>()
                        .in(TPOrderDetail::getOrderId, orderIdList));
                for (TPInOrderAccountReq.InDetailReq detailReq:orderDetailList) {
                    for (TPOrderDetail orderDetail:detailList) {
                        if (detailReq.getDetailId().equals(orderDetail.getId().toString())){
                            orderDetail.setActualNum(detailReq.getActualQty());
                            orderDetail.setModifyQuantity(detailReq.getModifyQty());
                            orderDetail.setWarehouseId(storeId);
                            orderDetail.setWarehouseName(storeName);
                        }
                    }
                }
                tpOrderDetailService.updateBatchById(detailList);
                //创建logSummary
                tpLogSummaryService.remove(new LambdaQueryWrapper<TPLogSummary>()
                        .in(TPLogSummary::getOrderMainId, orderIdList)
                        .eq(TPLogSummary::getDeviceType,0));

                Map<String, List<TPOrderMain>> orderMap = orderlist.stream()
                        .collect(Collectors.groupingBy(TPOrderMain::getId));
                Map<String, List<TPInOrderAccountReq.InDetailReq>> orderDetailMap = orderDetailList.stream()
                        .collect(Collectors.groupingBy(TPInOrderAccountReq.InDetailReq::getRefBillId));

                List<TPLogSummary> addLogSummaryList=new ArrayList<>();
                for (String orderId:orderDetailMap.keySet()) {
                    TPLogSummary tpLogSummary = new TPLogSummary();
                    tpLogSummary.setOrgId(orgInfo.getOrgId());
                    tpLogSummary.setOrgName(orgInfo.getOrgName());
                    tpLogSummary.setOrderMainId(orderId);
                    tpLogSummary.setOrderCode(orderMap.get(orderId).get(0).getOrderCode());
                    tpLogSummary.setDeviceType(0);
                    tpLogSummary.setLocationId(storeId);
                    tpLogSummary.setLocationName(storeName);
                    tpLogSummary.setLocationType(0);
                    tpLogSummary.setEquipmentList(orderDetailMap.get(orderId).stream()
                            .map(TPInOrderAccountReq.InDetailReq::getGoodsName).collect(Collectors.joining(",")));
                    tpLogSummary.setOutInState("in");
                    tpLogSummary.setNumber(orderMap.get(orderId).get(0).getActualQuantity());
                    tpLogSummary.setCreateTime(new Date());
                    tpLogSummary.setUpdateTime(new Date());
                    tpLogSummary.setUseTime(new Date());
                    tpLogSummary.setBussinessType(orderMap.get(orderId).get(0).getBussinessType());
                    tpLogSummary.setUserName(LoginContext.getContext().getLoginUser().getUserInfo().getRealName());
                    addLogSummaryList.add(tpLogSummary);

                }
                tpLogSummaryService.saveBatch(addLogSummaryList);
            }).start();
            return true;

        }
        return false;
    }

    public TPInvSummary createInventorySummary(Long orgId, String orgName, String orgCode, String typeId, String typeName,
                                               String sizeId, String sizeName, String locationId, String locationName,
                                               Integer stockNumber, Integer number, String valueKey,BigDecimal unitPrice) {
        TPInvSummary inventorySummary = new TPInvSummary();
        inventorySummary.setOrgId(orgId);
        inventorySummary.setTypeId(typeId);
        inventorySummary.setTypeName(typeName);
        inventorySummary.setSizeId(sizeId);
        inventorySummary.setSizeName(sizeName);
        inventorySummary.setLocationId(locationId);
        inventorySummary.setLocationName(locationName);
        inventorySummary.setValuekey(valueKey);
        inventorySummary.setOrgName(orgName);
        inventorySummary.setLocationName(locationName);
        inventorySummary.setOrgCode(orgCode);
        inventorySummary.setStockNumber(stockNumber);
        inventorySummary.setOutboundNumber(0);
        inventorySummary.setNumber(number);
        inventorySummary.setLocationType("0");
        inventorySummary.setUnitPrice(unitPrice);
        inventorySummary.setPrice(inventorySummary.getUnitPrice().multiply(BigDecimal.valueOf(inventorySummary.getNumber())));
        inventorySummary.setDestructionNumber(0);
        inventorySummary.setDestructionPrice(BigDecimal.ZERO);
        inventorySummary.setBrokenNumber(0);
        inventorySummary.setExpireNumber(0);
        inventorySummary.setUseNumber(0);
        inventorySummary.setUseCount(0);
        inventorySummary.setFixNumber(0);
        inventorySummary.setProperty(0);
        inventorySummary.setCreateTime(new Date());
        inventorySummary.setUpdateTime(new Date());
        return inventorySummary;
    }

    private TPInventory createInvInfo( String warehouseId,String typeId,String sizeId,Long orgId,
                                          Date productTime,Integer repairCycle,Integer warrantyCycle,String epc,String supplierId,BigDecimal price){
        TPInventory inventory = new TPInventory();
        inventory.setLocationType(0);
        inventory.setLocationId(warehouseId);
        inventory.setTypeId(typeId);
        inventory.setSizeId(sizeId);
        inventory.setOrgId(orgId);
        inventory.setBussinessState("normal");
        inventory.setState("normal");
        inventory.setLocationState("in");
        inventory.setProductionDate(productTime);
        inventory.setMaintenancePeriod(repairCycle);
        inventory.setWarrantyPeriod(warrantyCycle);
        inventory.setCreateTime(new Date());
        inventory.setUpdateTime(new Date());
        inventory.setCreateUser("internal");
        inventory.setUpdateUser("internal");
        inventory.setPrice(price);
        inventory.setEpc(epc);
        inventory.setSupplierId(supplierId);
        inventory.setProperty(0);
        return inventory;
    }


    private TPWarehouseInv createWareInvInfo(Long orgId,String orgName,String locationId,String locationName,String epc,
                                             String typeId,String typeName,String sizeId,String sizeName){
        TPWarehouseInv warehouseInventory = new TPWarehouseInv();
        warehouseInventory.setOrgId(orgId);
        warehouseInventory.setOrgName(orgName);
        warehouseInventory.setEpc(epc);
        warehouseInventory.setLocationId(locationId);
        warehouseInventory.setLocationName(locationName);
        warehouseInventory.setTypeId(typeId);
        warehouseInventory.setTypeName(typeName);
        warehouseInventory.setSizeId(sizeId);
        warehouseInventory.setSizeName(sizeName);
        warehouseInventory.setLocationType(0);
        warehouseInventory.setLocationState("in");
        warehouseInventory.setCreateTime(new Date());
        warehouseInventory.setUpdateTime(new Date());
        warehouseInventory.setEpcType(1);
        return warehouseInventory;
    }

    /**
     * 下发单据
     * @return
     */
    @Override
    public boolean dispatchOrder(TPDispatchOrderReq req) {

        Long orgId = req.getOrgId();
        String orderType = req.getOrderType();
        //先获取组织机构是否配置全局地址，如果有配则说明有下级平台
        SysDictItem one = sysDictItemService.getOne(new LambdaQueryWrapper<SysDictItem>()
                .eq(SysDictItem::getItemText, orgId.toString()));
        if (ObjectUtil.isNull(one)){
            throw new ThirdPartyException(ErrorExceptionEnum.SEND_ORDER_ERROR);
        }
        String itemValue = one.getItemValue();

        //根据组织机构取查询出出库或者入库单子
        boolean result=true;
        if (orderType.equals("in")) {
            List<TPInOrderDto> dtoList=thirdPartyMapper.getInOrderList(orgId,null);
            if (CollectionUtil.isNotEmpty(dtoList)){
                List<String> orderIdList = dtoList.stream().map(TPInOrderDto::getBillId).collect(Collectors.toList());
                List<TPInOrderDto.TPInOrderDetailDto> detailDtoList=thirdPartyMapper.getInOrderDetailList(orderIdList);
                Map<String, List<TPInOrderDto.TPInOrderDetailDto>> orderIdMap = detailDtoList.stream()
                        .collect(Collectors.groupingBy(TPInOrderDto.TPInOrderDetailDto::getRefBillId));
                dtoList.forEach(tpInOrderDto -> tpInOrderDto.setDetailList(orderIdMap.get(tpInOrderDto.getBillId())));
            }
            //调用下发接口进行数据下发
            String errorList = syncOrderApi.syncInOrder(ThirdPartyExpander.syncInOrder(itemValue), dtoList);
            PlatformResult platformResult = JSONObject.parseObject(errorList, PlatformResult.class);
            List<String> stringList = JSONObject.parseArray(platformResult.getData(), String.class);
            if (CollectionUtil.isNotEmpty(stringList)){
                new Thread(() -> {
                    List<String> errorsList = stringList; // 初始失败的列表
                    while (!errorsList.isEmpty()) {
                        // 使用失败的列表作为参数调用 syncOrderApi.syncInOrder 方法
                        List<String> allBillIdList = dtoList.stream().map(TPInOrderDto::getBillId).collect(Collectors.toList());

                        List<String> finalErrorsList = errorsList;
                        List<TPInOrderDto> errorDtoList = dtoList.stream().filter(tpInOrderDto -> (
                                allBillIdList.stream().filter(finalErrorsList::contains).collect(Collectors.toList())
                        ).contains(tpInOrderDto.getBillId())).collect(Collectors.toList());
                        String newErrorList = syncOrderApi.syncInOrder(ThirdPartyExpander.syncInOrder(itemValue), errorDtoList);
                        PlatformResult newPlatformResult = JSONObject.parseObject(newErrorList, PlatformResult.class);
                        // 更新失败的列表为新的失败列表
                        errorsList = JSONObject.parseArray(newPlatformResult.getData(), String.class);
                    }
                }).start();

            }
            List<String> successList = dtoList.stream().map(TPInOrderDto::getBillId).collect(Collectors.toList());

            result=thirdPartyMapper.updateSyncFlagByOrderIds(successList);

            return result;
        }else {

            List<TPOutOrderDto> dtoList=thirdPartyMapper.getOutOrderList(orgId,null);
            if (CollectionUtil.isNotEmpty(dtoList)){
                List<String> orderIdList = dtoList.stream().map(TPOutOrderDto::getBillId).collect(Collectors.toList());
                List<TPOutOrderDto.TPOutOrderDetailDto> detailDtoList=thirdPartyMapper.getOutOrderDetailList(orderIdList);
                Map<String, List<TPOutOrderDto.TPOutOrderDetailDto>> orderIdMap = detailDtoList.stream()
                        .collect(Collectors.groupingBy(TPOutOrderDto.TPOutOrderDetailDto::getRefBillId));
                dtoList.forEach(tpOutOrderDto -> tpOutOrderDto.setDetailList(orderIdMap.get(tpOutOrderDto.getBillId())));
            }
            //调用下发接口进行数据下发
            String errorList = syncOrderApi.syncOutOrder(ThirdPartyExpander.syncOutOrder(itemValue), dtoList);
            PlatformResult platformResult = JSONObject.parseObject(errorList, PlatformResult.class);
            List<String> stringList = JSONObject.parseArray(platformResult.getData(), String.class);
            if (CollectionUtil.isNotEmpty(stringList)){
                new Thread(() -> {
                    List<String> errorsList = stringList; // 初始失败的列表
                    while (!errorsList.isEmpty()) {
                        // 使用失败的列表作为参数调用 syncOrderApi.syncInOrder 方法
                        List<String> allBillIdList = dtoList.stream().map(TPOutOrderDto::getBillId).collect(Collectors.toList());

                        List<String> finalErrorsList = errorsList;
                        List<TPOutOrderDto> errorDtoList = dtoList.stream().filter(tpOutOrderDto -> (
                                allBillIdList.stream().filter(finalErrorsList::contains).collect(Collectors.toList())
                        ).contains(tpOutOrderDto.getBillId())).collect(Collectors.toList());
                        String newErrorList = syncOrderApi.syncOutOrder(ThirdPartyExpander.syncOutOrder(itemValue), errorDtoList);
                        PlatformResult newPlatformResult = JSONObject.parseObject(newErrorList, PlatformResult.class);
                        // 更新失败的列表为新的失败列表
                        errorsList = JSONObject.parseArray(newPlatformResult.getData(), String.class);
                    }
                }).start();

            }
            List<String> successList = dtoList.stream().map(TPOutOrderDto::getBillId).collect(Collectors.toList());

            result=thirdPartyMapper.updateSyncFlagByOrderIds(successList);

            return result;
        }



    }

    @Override
    public TPPoliceDto syncPoliceInfo(TPPoliceReq req) {
        if (ObjectUtil.isNull(req.getOrgId())){
            throw new ThirdPartyException(ErrorExceptionEnum.PARAM_ERROR);
        }
        TPPoliceDto tpPoliceDto = new TPPoliceDto();
        List<TPPoliceDto.PoliceDto> policeList=thirdPartyMapper.getPoliceList(req.getOrgId(),req.getUpdateTime());
        //需要判断警员照片是否存在，如果存在则需要调用大华的上传图片，并且将返回值进行保存后存储，用于半山同步用户时获取警员照片并添加成功
        if (CollectionUtil.isNotEmpty(policeList)){
            //添加角色信息
            List<Long> userIdsList = policeList.stream().map(TPPoliceDto.PoliceDto::getUserId).collect(Collectors.toList());
            List<SysUserRole> list1=thirdPartyMapper.getRoleIdsByUserIds(userIdsList);
            Map<Long, List<Long>> userIdToRoleIds = list1.stream()
                    .collect(Collectors.groupingBy(
                            SysUserRole::getUserId,      // 使用 SysUserRole 的 getUserId 方法
                            Collectors.mapping(SysUserRole::getRoleId, Collectors.toList())
                    ));
            policeList.forEach(item2 -> {
                List<Long> roleIds = userIdToRoleIds.getOrDefault(item2.getUserId(), new ArrayList<>());
                item2.setRolesIdList(roleIds);
            });

            //添加指纹信息
            List<String> policeIdList = policeList.stream().map(TPPoliceDto.PoliceDto::getId).collect(Collectors.toList());
            List<TPPoliceDto.FingerDto> fingerDtoList=thirdPartyMapper.getFingerList(policeIdList,req.getUpdateTime());
            tpPoliceDto.setFingerList(fingerDtoList);

        }
        tpPoliceDto.setPoliceList(policeList);
        return tpPoliceDto;
    }

    /**
     * 创建库存valueKey
     */
    public String createValueKey(String orgCode,String locationId,String typeId,String sizeId,String unitPrice,String property){
        orgCode = (orgCode != null) ? orgCode : "--0000";
        locationId = (locationId != null) ? locationId : "--0000";
        typeId = (typeId != null) ? typeId : "--0000";
        sizeId = (sizeId != null) ? sizeId : "--0000";
        unitPrice = (unitPrice != null) ? unitPrice : "--0000";
        property = (property != null) ? property : "--0";
        String key=orgCode+locationId+typeId+sizeId+unitPrice+property;
        return key;
    }

    @Override
    @Transactional
    public boolean pushAddPoliceInfo(TPUpdatePoliceReq req) {
        //拿到人员信息进行直接插入
        //判断人员是否插入，如果已经插入则直接返回true
        List<TPPoliceman> list = tpPolicemanService.list(new LambdaQueryWrapper<TPPoliceman>()
                .eq(TPPoliceman::getUserId, req.getUserId()));
        if (CollectionUtil.isNotEmpty(list)){
            return true;
        }
        TPPoliceman tpPoliceman = BeanPlusUtil.copyProperties(req, TPPoliceman.class);
        //设置密码
        String defaultPassword = SystemConfigExpander.getDefaultPassWord();
        String password = iStoredEncryptApi.encrypt(defaultPassword);
        tpPoliceman.setPassword(password);
        tpPolicemanService.save(tpPoliceman);
        //添加账号信息
        SysUser sysUser = BeanPlusUtil.copyProperties(req.getSysUser(), SysUser.class);
        //需要设置一下密码，默认123456
        sysUser.setPassword(password);
        sysUser.setNickName(tpPoliceman.getName());
        sysUserService.save(sysUser);
        //添加角色
        if (CollectionUtil.isNotEmpty(req.getRolesList())){
            List<SysUserRole> sysUserRoleList=new ArrayList<>() ;
            if (req.getRolesList().size()>0 ){
                for (Long roleId: req.getRolesList()) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(roleId);
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setCreateTime(new Date());
                    sysUserRole.setCreateUser(req.getCreateUser());
                    sysUserRoleList.add(sysUserRole);
                }
            }
            sysUserRoleService.saveBatch(sysUserRoleList);
        }

        //添加组织机构
        sysUserOrgService.add(sysUser.getUserId(), req.getOrgId(), null);

        return true;
    }

    /**
     * 同步警柜数据
     * @param req
     * @return
     */
    @Override
    @Transactional
    public boolean pushAddCabinetInfo(TPCabDto req) {
        List<TPCabinetDto> cabList = req.getCabinetList();
        if (CollectionUtil.isNotEmpty(cabList)) {
            Long orgIdInt = cabList.get(0).getOrgId();
            List<TPCabinet> cabinetList = new ArrayList<>();
            cabList.forEach(cabinet->{
                TPCabinet tpCabinet = new TPCabinet();
                BeanPlusUtil.copyProperties(cabinet,tpCabinet);
                tpCabinet.setDepartmentId(1);
                tpCabinet.setOrgIdInt(orgIdInt);
                tpCabinet.setId(cabinet.getCabinetId());
                cabinetList.add(tpCabinet);
            });
            List<String> cabinetIdsList = tpCabinetService.list(new LambdaQueryWrapper<TPCabinet>()
                    .eq(TPCabinet::getDepartmentId, 1))
                    .stream()
                    .map(TPCabinet::getId)
                    .collect(Collectors.toList());
            boolean remove = tpCabinetService.remove(new LambdaQueryWrapper<TPCabinet>().eq(TPCabinet::getDepartmentId, 1));
            boolean b = tpCabinetService.saveBatch(cabinetList);

            //提取list中的boxList集合
            List<TPCabinetDto.TPCabinetBoxDto> boxList = cabList.stream().map(TPCabinetDto::getBoxList)
                    .flatMap(Collection::stream).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(boxList)){
                List<TPCabinetBox> cabinetBoxList = new ArrayList<>();

                boxList.forEach(cabinetbox->{
                    TPCabinetBox tpCabinetBox = new TPCabinetBox();
                    BeanPlusUtil.copyProperties(cabinetbox, tpCabinetBox);
                    tpCabinetBox.setId(cabinetbox.getBoxId());
                    cabinetBoxList.add(tpCabinetBox);
                });
                if (CollectionUtil.isNotEmpty(cabinetIdsList)){
                    boolean remove1 = tpCabinetBoxService.remove(new LambdaQueryWrapper<TPCabinetBox>().in(TPCabinetBox::getCabinetId, cabinetIdsList));
                }
                boolean b1 = tpCabinetBoxService.saveBatch(cabinetBoxList);
            }
        }
        return true;
    }

    /**
     * 警员绑定箱门
     * @param req
     * @return
     */
    @Override
    @Transactional
    public boolean bindBoxToPolice(TPUpdatePoliceReq req) {
        TPPoliceman policeman = tpPolicemanService.policeExist(req.getUserId());
        //判断警员绑定的单警柜是否存在
        boolean result=false;
        if (req.getBoxList().size()>0){
            List<TPCabinetBoxPolice> cabinetBoxPoliceList=new ArrayList<>();
            List<String> boxList = req.getBoxList();

            //将箱门清除（需要排除哪些不是半山推送过来的绑定关系，不能全部remove）
//            tpCabinetBoxPoliceService.remove(new LambdaQueryWrapper<TPCabinetBoxPolice>()
//                    .eq(TPCabinetBoxPolice::getPoliceId, policeman.getId()));
            tpCabinetBoxPoliceMapper.deleteBykfBoxList(policeman.getId(), policeman.getOrgId());
            //公共柜和单警柜一起批量绑定
            for (String boxId:boxList ) {
                TPCabinetBoxPolice cabinetBoxPolice = new TPCabinetBoxPolice();
                cabinetBoxPolice.setPoliceId(policeman.getId());
                cabinetBoxPolice.setCabinetBoxId(boxId);
                cabinetBoxPolice.setCreateTime(new Date());
                cabinetBoxPoliceList.add(cabinetBoxPolice);
            }
            if (cabinetBoxPoliceList.size()>0){
                result = tpCabinetBoxPoliceService.saveBatch(cabinetBoxPoliceList);
            }
        }else {

            result = tpCabinetBoxPoliceService.remove(new LambdaQueryWrapper<TPCabinetBoxPolice>()
                    .eq(TPCabinetBoxPolice::getPoliceId, policeman.getId()));


        }
        return result;
    }

    @Override
    @Transactional
    public List<TPCabinetBoxPolice> syncBoxBindPoliceInfo(TPUpdatePoliceReq req) {
        //获取组织机构下的人员的绑定关系
        List<TPCabinetBoxPolice> list = tpCabinetBoxPoliceMapper.getBindListByOrgId(req.getOrgId());
        if (CollectionUtil.isNotEmpty(list)){
            return list;
        }
        return new ArrayList<>();
    }

    @Override
    public List<SysRoleDto> syncRoles() {
        return thirdPartyMapper.syncRoles();
    }

    /**
     * 获取任务执行状态
     * @param orderCode
     * @param config
     * @return
     */
    @Override
    public Boolean getTaskWokingState(String orderCode,String config) {
        TPOrderNoReq tpOrderNoReq = new TPOrderNoReq(orderCode);
        try {
            String taskWokingState = syncOrderApi.getTaskWokingState(ThirdPartyExpander.getTaskWokingState(config), tpOrderNoReq);
            Api3Res api3Res = JSONObject.parseObject(taskWokingState, Api3Res.class);
            if (api3Res.getData() instanceof Boolean){
                return (Boolean) api3Res.getData();
            }else {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取最新的单据info出入库信息
     * @param orderCode
     * @param config
     * @return
     */
    @Override
    public Boolean getLasterOrderInfo(String orderId,String orderType,String orderCode, String config) {
        TPOrderNoReq tpOrderNoReq = new TPOrderNoReq(orderCode);
        try {
            String taskWokingState = syncOrderApi.getLasterOrderInfo(ThirdPartyExpander.getLasterOrderInfo(config), tpOrderNoReq);
            Api3Res api3Res = JSONObject.parseObject(taskWokingState, Api3Res.class);
            Boolean result=false;
            if (orderType.equals("in")){
                TPInOrderAccountReq tpInOrderAccountReq = BeanPlusUtil.copyProperties(api3Res.getData(), TPInOrderAccountReq.class);
                if (tpInOrderAccountReq != null){
                    //直接调用最新接口获取最新的订单信息后进行更新处理
                    result = syncInOrderLastInfo(tpInOrderAccountReq);
                }
            }else {
                TPOutOrderAccountReq tpOutOrderAccountReq = BeanPlusUtil.copyProperties(api3Res.getData(), TPOutOrderAccountReq.class);
                if (tpOutOrderAccountReq != null){
                    //直接调用最新接口获取最新的订单信息后进行更新处理
                    result = syncOutOrderLastInfo(tpOutOrderAccountReq);
                }
            }
            return result;

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

    @Override
    public Boolean editOrderStatus(String orderCode, String config) {
        TPOrderNoReq tpOrderNoReq = new TPOrderNoReq(orderCode);
        try {
            String editOrderStatus = syncOrderApi.editOrderStatus(ThirdPartyExpander.editOrderStatus(config), tpOrderNoReq);
            Api3Res api3Res = JSONObject.parseObject(editOrderStatus, Api3Res.class);
            if (api3Res.getData() instanceof Boolean){
                return(Boolean) api3Res.getData();
            }else {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


}
