package com.testor.module.partner.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.util.CacheDicUtils;
import com.testor.common.constant.StatusEnum;
import com.testor.module.duty.util.PoiExcelUtils;
import com.testor.module.partner.dao.TPartnerOrgDao;
import com.testor.module.partner.model.domain.TPartnerCertificate;
import com.testor.module.partner.model.domain.TPartnerOrg;
import com.testor.module.partner.model.domain.TPartnerOrgRes;
import com.testor.module.partner.model.domain.TPartnerType;
import com.testor.module.partner.model.dto.TPartnerCertificateDTO;
import com.testor.module.partner.model.dto.TPartnerOrgDTO;
import com.testor.module.partner.model.dto.TPartnerOrgParam;
import com.testor.module.partner.model.dto.TPartnerOrgResDTO;
import com.testor.module.partner.model.excel.PartnerExp;
import com.testor.module.partner.model.excel.PartnerReport;
import com.testor.module.partner.model.vo.PartnerOrgBlacklistVO;
import com.testor.module.partner.model.vo.PartnerOrgDetailVO;
import com.testor.module.partner.model.vo.PartnerOrgVO;
import com.testor.module.partner.service.TPartnerCertificateService;
import com.testor.module.partner.service.TPartnerOrgResService;
import com.testor.module.partner.service.TPartnerOrgService;
import com.testor.module.partner.service.TPartnerTypeService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.exceptions.ApiException;
import com.tongtech.tfw.backend.common.models.response.ResponseInfo;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 相关方组织机构Service业务层处理
 *
 * @author testor-framework
 * @date 2022-06-01 14:16:53
 */
@Component("tPartnerOrgService")
public class TPartnerOrgServiceImpl extends SuperServiceImpl<TPartnerOrgDao, TPartnerOrg> implements TPartnerOrgService {
    @Autowired(required = false)
    private TPartnerOrgDao tPartnerOrgDao;
    @Autowired
    private SysOrgService orgService;
    @Resource
    private TPartnerCertificateService certificateService;

    @Autowired
    private TPartnerTypeService partnerTypeService;

    @Autowired
    private TPartnerCertificateService tPartnerCertificateService;

    @Autowired
    private TPartnerOrgResService tPartnerOrgResService;

    @Autowired
    private SysOrgService sysOrgService;

    /**
     * 编辑相关方机构
     *
     * @param partnerOrg .
     * @return .
     */
    @Override
    @Transactional
    public BaseResponse<TPartnerOrg> editPartnerOrg(TPartnerOrgDTO partnerOrg) {
        BaseResponse<TPartnerOrg> baseResponse = new BaseResponse<>();

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        // 组织机构id
        String curUserOrgId = curUser.getOrgId();
        String id = partnerOrg.getId();


        TPartnerOrg data = BeanHelper.beanToBean(partnerOrg, TPartnerOrg.class);
        data.setIsBlacklist("0");
        data.setCreateBy(curUser.getUserId());
        data.setUpdateDate(new Date());

        List<TPartnerCertificateDTO> certificateIdList = partnerOrg.getCertificateIdList();
        if (StrUtil.isEmpty(id)) {
            boolean checkResult = checkPartnerOrg(partnerOrg.getPartnerId(), partnerOrg.getCreditCode(), partnerOrg.getName());
            if (!checkResult) {
                baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
                baseResponse.setMsg("已存在相同的统一社会信用代码或名称的相关方");
                return baseResponse;
            }
            data.setOrgId(curUserOrgId);
            // 新增相关方信息
            int certificateCount = 0;
            if (ObjectUtil.isEmpty(partnerOrg.getPartnerId())) {
                this.save(data);
                for (TPartnerCertificateDTO tPartnerCertificateDTO : certificateIdList) {
                    tPartnerCertificateDTO.setBizId(data.getId());
                    tPartnerCertificateDTO.setUseType(1);
                    TPartnerCertificate tPartnerCertificate = tPartnerCertificateService.editCertificate(tPartnerCertificateDTO);
                    if (!ObjectUtils.isEmpty(tPartnerCertificate)) {
                        certificateCount++;
                    }
                }
            }

            // 新增资质信息
//            if (certificateCount != certificateIdList.size()) {
//                throw new RuntimeException("创建失败");
//            }
            TPartnerOrgResDTO tPartnerOrgResDTO = partnerOrg.getTPartnerOrgResDTO();
            if (ObjectUtil.isEmpty(data.getId())) {
                data.setId(partnerOrg.getPartnerId());
            }
            tPartnerOrgResDTO.setPartnerId(data.getId());
            if (!ObjectUtils.isEmpty(tPartnerOrgResDTO)) {

                BaseResponse<TPartnerOrgRes> tPartnerOrgResBaseResponse = tPartnerOrgResService.addOrdRes(tPartnerOrgResDTO);
                Integer code = tPartnerOrgResBaseResponse.getCode();
                String msg = tPartnerOrgResBaseResponse.getMsg();
                if (BaseStatusEnum.SUCCESS.code() != tPartnerOrgResBaseResponse.getCode()) {
                    throw new ApiException(new ResponseInfo(code, msg));
                }
            }
            baseResponse.setData(data);
            return baseResponse;
        } else {
            // 修改相关方 TODO 详情接口需要返回 res_id 资质 List<id>
            try {
                // 修改相关方信息
                tPartnerOrgDao.updateById(data);


                /*List<TPartnerCertificate> tPartnerCertificates = BeanHelper.listToList(certificateIdList, TPartnerCertificate.class);
                tPartnerCertificates.forEach(item -> {
                    item.setBizId(data.getId());
                    boolean check = tPartnerCertificateService.checkValidity(item.getValidEndDate());
                    String state = "1";
                    if (check) {
                        state = "0";
                    }
                    item.setState(state);
                });
                tPartnerCertificateService.updateBatchById(tPartnerCertificates);*/

                //删除新增资质信息
                UpdateWrapper<TPartnerCertificate> tPartnerCertificateUpdateWrapper = new UpdateWrapper<>();
                tPartnerCertificateUpdateWrapper.eq("biz_id", data.getId()).set("status", 1);
                tPartnerCertificateService.update(tPartnerCertificateUpdateWrapper);

                int certificateCount = 0;


                // 新增资质信息
                for (TPartnerCertificateDTO tPartnerCertificateDTO : certificateIdList) {
                    tPartnerCertificateDTO.setBizId(data.getId());
                    tPartnerCertificateDTO.setUseType(1);
                    TPartnerCertificate tPartnerCertificate = tPartnerCertificateService.editCertificate(tPartnerCertificateDTO);
                    if (!ObjectUtils.isEmpty(tPartnerCertificate)) {
                        certificateCount++;
                    }
                }

                if (certificateCount != certificateIdList.size()) {
                    throw new RuntimeException("创建失败");
                }

                TPartnerOrgResDTO tPartnerOrgResDTO = partnerOrg.getTPartnerOrgResDTO();
                if (!ObjectUtils.isEmpty(tPartnerOrgResDTO)) {
                    tPartnerOrgResDTO.setPartnerId(data.getId());
                    tPartnerOrgResDTO.setUpdateBy(curUser.getUserId());
                    tPartnerOrgResDTO.setUpdateDate(new Date());
                    BaseResponse<BizGeneralResponse> tPartnerOrgResBaseResponse = tPartnerOrgResService.update(tPartnerOrgResDTO);
                    Integer code = tPartnerOrgResBaseResponse.getCode();
                    String msg = tPartnerOrgResBaseResponse.getMsg();
                    if (BaseStatusEnum.SUCCESS.code() != tPartnerOrgResBaseResponse.getCode()) {
                        throw new ApiException(new ResponseInfo(code, msg));
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        baseResponse.setData(data);
        return baseResponse;
    }

    /**
     * 检测相关方在该企业下是否已经存在
     *
     * @param creditCode 信用代码
     * @param name       单位名称
     * @return false-检测不通过   true-检测通过
     */
    public Boolean checkPartnerOrg(String partnerOrgId, String creditCode, String name) {
        if (StrUtil.isBlank(name) || StrUtil.isBlank(creditCode)) {
            return false;
        }

        LambdaQueryWrapper<TPartnerOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(TPartnerOrg::getStatus, StatusEnum.USE.getCode())
                .and(wq -> wq
                        .eq(TPartnerOrg::getCreditCode, creditCode)
                        .or()
                        .eq(TPartnerOrg::getName, name))
        ;
        if (!StrUtil.isBlank(partnerOrgId)) {
            queryWrapper.ne(TPartnerOrg::getId, partnerOrgId);
        }
        List<TPartnerOrg> partnerOrgList = tPartnerOrgDao.selectList(queryWrapper);
        if (partnerOrgList != null && partnerOrgList.size() > 0) {
            if (!StrUtil.isBlank(partnerOrgId)) {
                return true;
            }
            return false;
        }

        return true;
    }

    /**
     * 检测当前用户是否有删除权限
     *
     * @param deleteType 删除类型：1-相关方机构删除； 2-黑名单相关方机构删除
     * @return false-检测不通过   true-检测通过
     */
    @Override
    public boolean checkDeleteAuthority(Integer deleteType) {
        if (deleteType == null || (deleteType != 1 && deleteType != 2)) {
            return false;
        }
        UserInfo user = ContextUtils.getLoginUser();
        // 只有黑名单删除
        SysOrg org = orgService.getById(user.getOrgId());
        if ("0".equals(org.getParentId())) {
            return true;
        }
        return false;
    }

    /**
     * 获取 导出相关方组织机构的 数据源
     *
     * @return
     */
    @Override
    public List<PartnerReport> exportPartnerOrg(String dsName, String datasetName, Map<String, Object> parameters) {


        String s = StringUtils.strip((String) parameters.get("ids"), "[]");

        List<String> ids = null;
        if (!StrUtil.isBlank(s)) {
            ids = new ArrayList<>(Arrays.asList(s.split(",")));
        } else {
            String orgId = ContextUtils.getLoginUser().getOrgId();
            List<SysOrg> list = sysOrgService.list(new QueryWrapper<SysOrg>()
                    .eq(SysOrg.IS_DEPT, "0")
                    .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                    .and(new Consumer<QueryWrapper<SysOrg>>() {
                        @Override
                        public void accept(QueryWrapper<SysOrg> sysOrgQueryWrapper) {
                            sysOrgQueryWrapper.apply("FIND_IN_SET ('" + orgId + "',parent_ids)").or()
                                    .eq(SysOrg.ORG_ID, orgId);
                        }
                    })
            );
            ids = new ArrayList<>();
            for (SysOrg sysOrg : list) {
                ids.add(sysOrg.getOrgId());
            }
        }

        List<PartnerReport> partnerExpList = tPartnerOrgDao.findPartnerExportData(ids);
        // 字典翻译
        partnerExpList.forEach(item -> {
            item.setCertificateName(CacheDicUtils.get("partnerCertificate", item.getCertificateName()));
        });
        if (partnerExpList == null || partnerExpList.size() == 0) {
            return partnerExpList;
        }
        Map<String, Integer> reportCountMap = new HashMap<>();
        // serialNumber 赋值
        int count = 0;
        for (PartnerReport partnerReport : partnerExpList) {
            String id = partnerReport.getId();

            if (reportCountMap.get(id) != null) {
                count = reportCountMap.get(id);
            } else {
                count = reportCountMap == null || reportCountMap.size() == 0 ? 1 : reportCountMap.size() + 1;
            }
            reportCountMap.put(id, count);
            partnerReport.setSerialNumber(count);
        }

        return partnerExpList;
    }

    @Override
    @Transactional
    public BaseResponse<String> importPartnerOrg(MultipartFile file) {
        BaseResponse<String> baseResponse = new BaseResponse<>();
        StringBuilder sbMsg = new StringBuilder();

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        String curUserOrgId = curUser.getOrgId();

        //判断是否为null
        if (file.equals("") || file.getSize() <= 0) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("上传文件数据错误");
            return baseResponse;
        }

        try {
            InputStream inputStream = file.getInputStream();
            inputStream = file.getInputStream();
            // 读取Excel⽂件⼯作表
            Workbook workbook = PoiExcelUtils.readFile(inputStream, file.getOriginalFilename());
            //取得第⼀个⼯作表
            Sheet sheet = workbook.getSheetAt(0);
            //报表上传的没条数据
            List<Map<Integer, Object>> dataList = PoiExcelUtils.getBody(sheet, 11, 2);
            System.out.println(JSON.toJSONString(dataList));
            if (dataList == null || dataList.size() == 0) {
                baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
                baseResponse.setMsg("请填写数据");
                return baseResponse;
            }

            PartnerExp partnerExp;
            List<PartnerExp> partnerExpList = new ArrayList<>();
            SimpleDateFormat timeDtf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Map<String, String> creditCodeMap = new HashMap<>();
            for (Map<Integer, Object> rowData : dataList) {
                if (rowData.get(0) == null || StrUtil.isBlank(rowData.get(0).toString())
                        || rowData.get(2) == null) {
                    continue;
                }
                String mapKey = rowData.get(2).toString().trim() + rowData.get(9).toString();
                if (creditCodeMap.get(mapKey) != null) {
                    baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
                    baseResponse.setMsg("存在相同的统一社会信用代码：" + rowData.get(2).toString());
                    return baseResponse;
                }

                boolean checkResult = checkPartnerOrg(null, rowData.get(2).toString().trim(), rowData.get(1).toString().trim());
                if (!checkResult) {
                    sbMsg.append("统一社会信用代码[" + rowData.get(2).toString().trim() + "]已存在未导入;");
                    continue;
                }

                creditCodeMap.put(mapKey, rowData.get(0).toString());
                partnerExp = new PartnerExp();
                partnerExp.setName(rowData.get(1).toString());
                partnerExp.setCreditCode(rowData.get(2).toString());
                partnerExp.setTypeName(rowData.get(3).toString());
                partnerExp.setLegalPerson(rowData.get(4).toString());
                partnerExp.setResponsiblePerson(rowData.get(5).toString());
                partnerExp.setPhone(rowData.get(6).toString());
                // //  DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                //   partnerExp.setContractStartDate(LocalDate.parse(rowData.get(7).toString(), timeDtf).atStartOfDay());
                partnerExp.setContractStartDate(timeDtf.parse(rowData.get(7).toString()));
                partnerExp.setContractEndDate(timeDtf.parse(rowData.get(8).toString()));
                partnerExp.setCertificateName(rowData.get(9).toString());
                partnerExp.setCertificateValidEndDate(timeDtf.parse(rowData.get(10).toString()));

                partnerExpList.add(partnerExp);
            }

            // 保存处理
            handleExcelData(partnerExpList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseResponse.setData(sbMsg == null ? "导入成功" : sbMsg.toString());
        return baseResponse;
    }

    @Override
    @Async
    @Transactional
    public void handleExcelData(List<PartnerExp> partnerExpList) {
        if (partnerExpList == null || partnerExpList.size() == 0) {
            return;
        }

        UserInfo curUser = ContextUtils.getLoginUser();

        // 相关方机构类型处理
        List<TPartnerType> tPartnerTypeList = partnerTypeService.list();
        Map<String, String> partnerTypeMap = new HashMap<>();
        if (tPartnerTypeList != null && tPartnerTypeList.size() > 0) {
            for (TPartnerType partnerType : tPartnerTypeList) {
                partnerTypeMap.put(partnerType.getName(), partnerType.getId());
            }
        }

        List<TPartnerOrg> tPartnerOrgList = new ArrayList<>();
        TPartnerOrg tPartnerOrg;
        List<TPartnerCertificate> tPartnerCertificateList = new ArrayList<>();
        TPartnerCertificate tPartnerCertificate;
        Map<String, List<TPartnerCertificate>> partnerCertificateMap = new HashMap<>();
        for (PartnerExp partnerExp : partnerExpList) {

            // 创建相关方机构证书
            tPartnerCertificate = new TPartnerCertificate();
            tPartnerCertificate.setName(partnerExp.getCertificateName());
            tPartnerCertificate.setType("1");
            tPartnerCertificate.setValidEndDate(partnerExp.getCertificateValidEndDate());
            boolean certificateCheckResult = certificateService.checkValidity(partnerExp.getCertificateValidEndDate());
            tPartnerCertificate.setState(certificateCheckResult ? "0" : "1");

            tPartnerCertificate.setCreateBy(curUser.getUserId());
            tPartnerCertificateList.add(tPartnerCertificate);

            String creditCode = partnerExp.getCreditCode();
            // 此 社会信用代码已存在，不进行创建相关方机构
            if (partnerCertificateMap.get(partnerExp.getCreditCode()) != null) {
                List<TPartnerCertificate> tPartnerCertificateMapList = partnerCertificateMap.get(creditCode);
                tPartnerCertificateMapList.add(tPartnerCertificate);
                partnerCertificateMap.put(creditCode, tPartnerCertificateMapList);
                continue;
            }

            List<TPartnerCertificate> tPartnerCertificateMapList = new ArrayList<>();
            tPartnerCertificateMapList.add(tPartnerCertificate);
            partnerCertificateMap.put(creditCode, tPartnerCertificateMapList);

            // 创建相关方机构
            tPartnerOrg = new TPartnerOrg();
            tPartnerOrg.setName(partnerExp.getName());
            tPartnerOrg.setCreditCode(partnerExp.getCreditCode());
            // 相关方类型id
            /*String typeId = partnerTypeMap.get(partnerExp.getTypeName().trim());
            if (!StrUtil.isBlank(typeId)) {
                tPartnerOrg.setTypeId(typeId);
            }*/
            tPartnerOrg.setLegalPerson(partnerExp.getLegalPerson());
           /* tPartnerOrg.setResponsiblePerson(partnerExp.getResponsiblePerson());
            tPartnerOrg.setPhone(partnerExp.getPhone());
            tPartnerOrg.setContractStartDate(partnerExp.getContractStartDate());
            tPartnerOrg.setContractEndDate(partnerExp.getContractEndDate());*/

            tPartnerOrg.setCreateBy(curUser.getUserId());
            tPartnerOrgList.add(tPartnerOrg);
        }

        if (tPartnerCertificateList != null && tPartnerCertificateList.size() > 0) {
            certificateService.saveBatch(tPartnerCertificateList);
        }

        if (tPartnerOrgList == null || tPartnerOrgList.size() == 0) {
            return;
        }

        // 保存相关方机构
        for (TPartnerOrg partnerOrg : tPartnerOrgList) {
            List<TPartnerCertificate> partnerCertificateList = partnerCertificateMap.get(partnerOrg.getCreditCode());
            List<String> certificateIdList = new ArrayList<>();
            if (partnerCertificateList != null && partnerCertificateList.size() > 0) {
                for (TPartnerCertificate certificate : partnerCertificateList) {
                    certificateIdList.add(certificate.getId());
                }
                /*boolean certificateStatue = certificateService.checkCertificateValidity(null, certificateIdList);
                partnerOrg.setCertificateStatus(certificateStatue ? 1 : 0);*/
            }

            save(partnerOrg);
            boolean certificateResult = certificateService.bindBizId(partnerOrg.getId(), certificateIdList);
        }
    }

    @Override
    public IPage<PartnerOrgVO> listByPage(TPartnerOrgParam param) {
        List<String> condOrgIdList = param.getCondOrgIdList();
        if (null == condOrgIdList || condOrgIdList.size() == 0) {
            param.setCondOrgIdList(null);
        }
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<PartnerOrgVO> resultPage = new Page<>(page, limit);
        String orgId = ContextUtils.getLoginUser().getOrgId();
        param.setOrgId(orgId);
        return tPartnerOrgDao.list(resultPage, param);
    }

    @Override
    public PartnerOrgDetailVO getDetail(String resId) {
        PartnerOrgDetailVO detail = tPartnerOrgDao.detail(resId);
        if (!ObjectUtils.isEmpty(detail)) {
            QueryWrapper<TPartnerCertificate> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("biz_id", detail.getPartnerId());
            queryWrapper.eq("status", StatusEnum.USE.getCode());
            detail.setTPartnerCertificates(tPartnerCertificateService.list(queryWrapper));
        }
        return detail;
    }

    @Override
    public IPage<PartnerOrgBlacklistVO> blacklist(TPartnerOrgParam param) {
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<PartnerOrgBlacklistVO> resultPage = new Page<>(page, limit);
        return tPartnerOrgDao.blacklist(resultPage, param);
    }

    @Override
    public List<TPartnerOrg> getResid(TPartnerOrgDTO tPartnerOrgDTO) {
        List<TPartnerOrgDTO> resid = tPartnerOrgDao.getResid(tPartnerOrgDTO);
        Map<String, List<TPartnerOrgDTO>> orgMap = resid.stream().filter(dto -> dto != null && dto.getPartnerId() != null).collect(Collectors.groupingBy(TPartnerOrgDTO::getPartnerId));
        List<TPartnerOrg> torgList = orgMap.values().stream().map(tPartnerOrgDTOS -> {
            TPartnerOrgDTO tPartnerOrgDTO1 = tPartnerOrgDTOS.get(0);
            return BeanUtil.copyProperties(tPartnerOrgDTO1, TPartnerOrg.class);
        }).collect(Collectors.toList());
        return torgList;
    }

    @Override
    public List<TPartnerOrg> getOrgId(TPartnerOrgDTO tPartnerOrgDTO) {
        String orgId = ContextUtils.getLoginUser().getOrgId();
        tPartnerOrgDTO.setId(orgId);
        List<TPartnerOrgDTO> resid = tPartnerOrgDao.getOrgId(tPartnerOrgDTO);
        Map<String, List<TPartnerOrgDTO>> orgMap = resid.stream().filter(dto -> dto != null && dto.getPartnerId() != null).collect(Collectors.groupingBy(TPartnerOrgDTO::getPartnerId));
        List<TPartnerOrg> torgList = orgMap.values().stream().map(tPartnerOrgDTOS -> {
            TPartnerOrgDTO tPartnerOrgDTO1 = tPartnerOrgDTOS.get(0);
            return BeanUtil.copyProperties(tPartnerOrgDTO1, TPartnerOrg.class);
        }).collect(Collectors.toList());
        return torgList;
    }
}
