package com.glxp.mipsdl.client.ptxhyy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.glxp.mipsdl.client.CommonHttpClient;
import com.glxp.mipsdl.client.ptxhyy.entity.HisProductEntity;
import com.glxp.mipsdl.client.ptxhyy.entity.OrderUploadResponse;
import com.glxp.mipsdl.client.ptxhyy.entity.ThrHslbEntity;
import com.glxp.mipsdl.client.ptxhyy.entity.ThrHslbService;
import com.glxp.mipsdl.config.ThirdSysConfig;
import com.glxp.mipsdl.constant.ConstantType;
import com.glxp.mipsdl.constant.Constants;
import com.glxp.mipsdl.dao.auth.AuthUserDao;
import com.glxp.mipsdl.dao.auth.AuthWarehouseDao;
import com.glxp.mipsdl.dao.auth.AuthWarehouseUserMapper;
import com.glxp.mipsdl.dao.basic.*;
import com.glxp.mipsdl.dao.inout.IoCodeDao;
import com.glxp.mipsdl.dao.inout.IoOrderDao;
import com.glxp.mipsdl.dao.inout.IoOrderDetailBizDao;
import com.glxp.mipsdl.dao.inout.IoOrderUploadLogDao;
import com.glxp.mipsdl.dao.thrsys.ThrDeptDao;
import com.glxp.mipsdl.dao.thrsys.ThrInvWarehouseDao;
import com.glxp.mipsdl.dao.thrsys.ThrProductsDao;
import com.glxp.mipsdl.dao.thrsys.ThrSystemBusApiDao;
import com.glxp.mipsdl.entity.auth.AuthUserEntity;
import com.glxp.mipsdl.entity.auth.AuthWarehouseEntity;
import com.glxp.mipsdl.entity.auth.AuthWarehouseUser;
import com.glxp.mipsdl.entity.basic.BasicBussinessTypeEntity;
import com.glxp.mipsdl.entity.basic.BasicCorpEntity;
import com.glxp.mipsdl.entity.basic.BasicSkProjectEntity;
import com.glxp.mipsdl.entity.inout.*;
import com.glxp.mipsdl.entity.ptxhyy.SickerEntity;
import com.glxp.mipsdl.entity.thrsys.ThrInvWarehouseEntity;
import com.glxp.mipsdl.entity.thrsys.ThrSystemBusApiEntity;
import com.glxp.mipsdl.http.HttpClient;
import com.glxp.mipsdl.req.base.UdiwmsInvProductsRequest;
import com.glxp.mipsdl.req.base.UdiwmsOrderDetailRequest;
import com.glxp.mipsdl.req.base.UdiwmsOrderRequest;
import com.glxp.mipsdl.req.ctqyy.DlThirdProjectRequest;
import com.glxp.mipsdl.req.ctqyy.GetSickRequest;
import com.glxp.mipsdl.req.ptxhyy.PtxhyyInvRequest;
import com.glxp.mipsdl.req.ptxhyy.PtxhyyOrderDetailRequest;
import com.glxp.mipsdl.req.ptxhyy.PtxhyyOrderRequest;
import com.glxp.mipsdl.res.BaseResponse;
import com.glxp.mipsdl.res.PageSimpleResponse;
import com.glxp.mipsdl.res.ptxhyy.PtxhInvResponse;
import com.glxp.mipsdl.res.udiwms.BasicSkSickerResponse;
import com.glxp.mipsdl.res.udiwms.ThrInvResultResponse;
import com.glxp.mipsdl.service.auth.AuthWarehouseService;
import com.glxp.mipsdl.service.order.OrderUploadLogService;
import com.glxp.mipsdl.service.thrsys.ThrCorpService;
import com.glxp.mipsdl.service.thrsys.ThrSystemDetailService;
import com.glxp.mipsdl.thirddao.ptxhyy.PtxhyySickerMapper;
import com.glxp.mipsdl.util.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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


/**
 * 平潭协和医院接口
 */
@Slf4j
@Service(value = "100008HttpClient")
@RequiredArgsConstructor
public class PtxhyyClient extends CommonHttpClient {


    private final ThirdSysConfig thirdSysConfig;
    private final IoOrderDao orderDao;
    private final ThrSystemBusApiDao thrSystemBusApiDao;
    private final BasicBussinessTypeDao basicBussinessTypeDao;
    private final BasicCorpDao basicCorpDao;
    private final AuthWarehouseDao authWarehouseDao;
    private final ThrInvWarehouseDao thrInvWarehouseDao;
    private final AuthWarehouseService authWarehouseService;
    private final IoCodeDao codeDao;
    private final IoOrderDetailBizDao orderDetailBizDao;
    private final SubmitOrderUtil submitOrderUtil;
    @Resource
    ThrHslbService thrHslbService;
    @Resource
    PtxhyySickerMapper ptxhyySickerMapper;

    @Override
    public BaseResponse submitOrders(UdiwmsOrderRequest udiwmsOrderRequest) {
        if (StrUtil.isBlank(udiwmsOrderRequest.getBillNo())) {
            return ResultVOUtils.error(500, "单据号不能为空");
        }
        //查询单据和详情信息，组装第三方系统接口参数
        IoOrderEntity orderEntity = orderDao.selectOne(new LambdaQueryWrapper<IoOrderEntity>().eq(IoOrderEntity::getBillNo, udiwmsOrderRequest.getBillNo()));

        Date billDate = orderEntity.getConfirmTime() == null ? orderEntity.getUpdateTime() : orderEntity.getConfirmTime();
        udiwmsOrderRequest.setBillDate(DateUtil.formatDateTime(billDate));
        //查询对应的第三方单据类型
        ThrSystemBusApiEntity thrSystemBusApiEntity = thrSystemBusApiDao.selectOne(new LambdaQueryWrapper<ThrSystemBusApiEntity>().eq(ThrSystemBusApiEntity::getCode, udiwmsOrderRequest.getBillType()));
        if (StrUtil.isBlank(thrSystemBusApiEntity.getUrl())) {
            String errMsg = "接口未配置，无法提交！";
            updateLocalErr(orderEntity, errMsg);
            return ResultVOUtils.error(500, errMsg);
        }
        udiwmsOrderRequest.setBillType(thrSystemBusApiEntity.getThirdBuyCode());
        //查询单据类型，设置往来单位信息
        BasicBussinessTypeEntity basicBussinessTypeEntity = basicBussinessTypeDao.selectByAction(orderEntity.getAction());
        if (basicBussinessTypeEntity.getCorpType().equals(Constants.CORP_HOSPTIAL)) {
            //医院客户
            udiwmsOrderRequest.setCorpId(orderEntity.getFromCorp());
            //查询客户名称
            String corpName = basicCorpDao.selectNameByErpId(orderEntity.getFromCorp());
            udiwmsOrderRequest.setCorpName(corpName);
        } else if (basicBussinessTypeEntity.getCorpType().equals(Constants.CORP_INTTERNAL)) {
            BasicCorpEntity basicCorpEntity = null;
            if (StrUtil.isNotEmpty(orderEntity.getFromCorp())) {
                basicCorpEntity = basicCorpDao.selectByErpId(orderEntity.getFromCorp());
                if (null != basicCorpEntity) {
                    udiwmsOrderRequest.setCorpId(basicCorpEntity.getThirdId());
                    udiwmsOrderRequest.setCorpName(basicCorpEntity.getName());
                } else {
                    String msg = "查询单据对应的第三方往来单位信息异常";
                    updateLocalErr(orderEntity, msg);
                    log.error("----单据提交-----" + orderEntity.getBillNo() + msg);
                    return ResultVOUtils.error(500, msg);
                }
            } else {
                //内部科室
                AuthWarehouseEntity warehouseEntity = authWarehouseDao.selectOne(new LambdaQueryWrapper<AuthWarehouseEntity>().eq(AuthWarehouseEntity::getCode, orderEntity.getFromInvCode()));
                try {
                    //根据第三方系统标识，获取对应字段的值
                    ThrInvWarehouseEntity thrInvWarehouseEntity = thrInvWarehouseDao.selectOne(new LambdaQueryWrapper<ThrInvWarehouseEntity>()
                            .eq(ThrInvWarehouseEntity::getCode, authWarehouseService.getThirdInvCode(warehouseEntity))
                            .eq(ThrInvWarehouseEntity::getThirdSysFk, thirdSysConfig.getThirdId()));
                    udiwmsOrderRequest.setCorpId(thrInvWarehouseEntity.getCode());
                    udiwmsOrderRequest.setCorpName(thrInvWarehouseEntity.getName());
                } catch (Exception e) {
                    String msg = "查询单据对应往来单位的第三方仓库信息异常";
                    updateLocalErr(orderEntity, msg);
                    log.error("----单据提交-----" + orderEntity.getBillNo() + msg + ExceptionUtil.stacktraceToString(e));
                    return ResultVOUtils.error(500, msg);
                }
            }
        } else if (basicBussinessTypeEntity.getCorpType().equals(Constants.CORP_SP)) {
            //供应商

            BasicCorpEntity basicCorpEntity = basicCorpDao.selectByErpId(orderEntity.getFromCorp());
            if (null != basicCorpEntity) {
                udiwmsOrderRequest.setCorpId(basicCorpEntity.getThirdId());
                udiwmsOrderRequest.setCorpName(basicCorpEntity.getName());
            } else {
                String msg = "查询单据对应的第三方往来单位信息异常";
                updateLocalErr(orderEntity, msg);
                log.error("----单据提交-----" + orderEntity.getBillNo() + msg);
                return ResultVOUtils.error(500, msg);
            }
        }

        //查询仓库信息
        AuthWarehouseEntity warehouseEntity = authWarehouseDao.selectOne(new LambdaQueryWrapper<AuthWarehouseEntity>().eq(AuthWarehouseEntity::getCode, orderEntity.getInvCode()));
        try {
            List<ThrInvWarehouseEntity> thrInvWarehouseEntitys = thrInvWarehouseDao.selectList(new LambdaQueryWrapper<ThrInvWarehouseEntity>()
                    .eq(ThrInvWarehouseEntity::getCode, authWarehouseService.getThirdInvCode(warehouseEntity))
                    .eq(ThrInvWarehouseEntity::getThirdSysFk, thirdSysConfig.getThirdId()));
            if (CollUtil.isNotEmpty(thrInvWarehouseEntitys)) {
                udiwmsOrderRequest.setLocInvCode(thrInvWarehouseEntitys.get(0).getCode());
                udiwmsOrderRequest.setLocInvName(thrInvWarehouseEntitys.get(0).getName());
            }
        } catch (Exception e) {
            log.error("查询第三方系统仓库信息异常", ExceptionUtil.stacktraceToString(e));
            updateLocalErr(orderEntity, "查询第三方系统仓库信息异常" + ExceptionUtil.stacktraceToString(e));
            return ResultVOUtils.error(500, "查询第三方系统仓库信息异常");
        }
        udiwmsOrderRequest.setBillFlag("1");
        //设置单据出入库类型
        if (basicBussinessTypeEntity.getMainAction().equals(ConstantType.TYPE_PUT)) {
            udiwmsOrderRequest.setInoutType(1); //入库
        } else if (basicBussinessTypeEntity.getMainAction().equals(ConstantType.TYPE_OUT)) {
            udiwmsOrderRequest.setInoutType(2); //出库
        }

        udiwmsOrderRequest.setRemark("udi管理系统提交单据:" + orderEntity.getBillNo());

        //组装单据明细数据
        List<IoCodeEntity> ioCodeEntities = codeDao.selectList(new LambdaQueryWrapper<IoCodeEntity>()
                .eq(IoCodeEntity::getOrderId, orderEntity.getBillNo())
                .ne(IoCodeEntity::getAction, "StockCheck")
        );

        List<UdiwmsOrderDetailRequest> items = new ArrayList<>();
        //查询业务单据详情
        List<IoOrderDetailBizEntity> detailBizEntities = orderDetailBizDao.selectList(new LambdaQueryWrapper<IoOrderDetailBizEntity>().eq(IoOrderDetailBizEntity::getOrderIdFk, orderEntity.getBillNo()));

        //单据金额
        BigDecimal djje = detailBizEntities.stream()
                .filter(x -> x.getPrice() != null).
                        map(IoOrderDetailBizEntity::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        List<IoOrderInvoiceEntity> ioOrderInvoiceEntities = IoOrderInvoiceEntity.builder().build()
                .selectList(Wrappers.lambdaQuery(IoOrderInvoiceEntity.class).eq(IoOrderInvoiceEntity::getOrderIdFk, orderEntity.getBillNo()).groupBy(IoOrderInvoiceEntity::getInvoiceEncode));
        int fbbz = 0;
        if (CollectionUtil.isNotEmpty(ioOrderInvoiceEntities) && ioOrderInvoiceEntities.size() > 0) {
            fbbz = 1;
        }
        String userName;
        try {
            userName = getUserName(orderEntity);
            if (StrUtil.isEmpty(userName)) {
                updateLocalErr(orderEntity, "该单据无创建人！");
                return ResultVOUtils.error(500, "该单据无创建人！");
            }
        } catch (Exception e) {
            log.error("----单据提交-----" + orderEntity.getBillNo() + "查询操作人异常", ExceptionUtil.stacktraceToString(e));
            userName = getUserName(orderEntity);
        }
        PtxhyyOrderRequest ptxhyyOrderRequest = PtxhyyOrderRequest
                .builder()
                .kfxh(udiwmsOrderRequest.getLocInvCode())
                .czgh(userName)
                .lzfs(udiwmsOrderRequest.getBillType())
                .dwxh(udiwmsOrderRequest.getCorpId())
                .rkrq(udiwmsOrderRequest.getBillDate())
                .djje(djje)
                .fpbz(fbbz)
                .zdrq(udiwmsOrderRequest.getBillDate())
                .lsje(djje)
                .fpzs(CollectionUtil.isNotEmpty(ioOrderInvoiceEntities) ? ioOrderInvoiceEntities.size() : 0)
                .udixh(udiwmsOrderRequest.getBillNo())
                .lzdh(udiwmsOrderRequest.getBillNo())
                .build();

        ptxhyyOrderRequest.setDetailList(new ArrayList<>());
        String errMs = setOrderDetailList(ioCodeEntities, items, detailBizEntities);
        if (errMs != null) {
            updateLocalErr(orderEntity, errMs);
            log.error(errMs);
            return ResultVOUtils.error(500, errMs);
        }
        Collections.reverse(items);
        for (UdiwmsOrderDetailRequest i : items) {
//            String udim = "";
//            if (CollectionUtil.isNotEmpty(i.getCodeList())) {
//                udim = i.getCodeList().stream().map(UdiwmsOrderDetailRequest.CodeDetailEntity::getCode).collect(Collectors.joining(","));
//            }
            String fphm = "";
            String fprq = null;
            List<IoOrderInvoiceEntity> invoiceList = IoOrderInvoiceEntity.builder().build()
                    .selectList(Wrappers.lambdaQuery(IoOrderInvoiceEntity.class).eq(IoOrderInvoiceEntity::getOrderIdFk, orderEntity.getBillNo())
                            .eq(IoOrderInvoiceEntity::getBindRlFk, i.getBindRlFk())
                            .eq(StrUtil.isNotEmpty(i.getBatchNo()), IoOrderInvoiceEntity::getBatchNo, i.getBatchNo()).
                                    groupBy(IoOrderInvoiceEntity::getInvoiceEncode));
            if (CollectionUtil.isNotEmpty(invoiceList)) {
                fphm = invoiceList.stream().map(IoOrderInvoiceEntity::getInvoiceEncode).collect(Collectors.joining(","));
                if (invoiceList.get(0).getInvoiceDate() != null)
                    fprq = DateUtil.formatDateTime(invoiceList.get(0).getInvoiceDate());
            }
            String hsfl = "";
            if (StrUtil.isNotEmpty(i.getHslb())) {
                ThrHslbEntity thrHslbEntity = thrHslbService.getOne(new QueryWrapper<ThrHslbEntity>().eq("hslb", i.getHslb()), false);
                if (thrHslbEntity != null) {
                    hsfl = thrHslbEntity.getHsbm();
                }
            }
//                  .udim(udim)
            BigDecimal wzje = null;
            if (i.getPrice() != null)
                wzje = i.getPrice().multiply(BigDecimal.valueOf(i.getCount().intValue()));
            PtxhyyOrderDetailRequest detailRequest = PtxhyyOrderDetailRequest.builder()
                    .wzxh(i.getProductId())
                    .cjxh(i.getManufactoryCode())
                    .bzdw(i.getMeasname())
                    .bzsl(i.getCount())
                    .wzjg(i.getPrice())
                    .lsjg(i.getPrice() + "")
                    .lsje(wzje)
                    .wzje(wzje + "")
                    .hsfl(i.getHslb())
//                    .hsfl(hsfl)
                    .wzph(i.getBatchNo())
                    .fphm(fphm)
                    .fprq(fprq)
                    .djrq(DateUtil.formatDate(orderEntity.getCreateTime(), "yyyy-MM-dd"))
                    .producedDate(i.getProductDate())
                    .expireDate(i.getExpireDate())
                    .registerNo(i.getRegisterNo())
                    .build();
            ptxhyyOrderRequest.getDetailList().add(detailRequest);
        }

        return submitOrder(orderEntity, ptxhyyOrderRequest);
    }


    /**
     * 本地提交错误
     *
     * @param orderEntity
     * @param errMsg
     */
    public void updateLocalErr(IoOrderEntity orderEntity, String errMsg) {
        IoOrderUploadLogEntity uploadLog = new IoOrderUploadLogEntity();
        uploadLog.setBillDate(orderEntity.getCreateTime());
        uploadLog.setBillType(orderEntity.getAction());
        uploadLog.setSubmitTime(new Date());
        uploadLog.setBillNo(orderEntity.getBillNo());
        uploadLog.setFromType(Constants.THIRD_ORDER_UPLOAD);
        orderDao.updateById(orderEntity);
        uploadLog.setStatus(4);
        uploadLog.setResult("单据数据异常：" + errMsg);
        orderUploadLogService.insertOrUpdate(uploadLog);
    }

    /**
     * 封装单据详情参数
     *
     * @param ioCodeEntities      单据码明细
     * @param orderDetailRequests 单据详情参数
     * @param detailBizEntities   单据业务详情
     */
    private String setOrderDetailList(List<IoCodeEntity> ioCodeEntities, List<UdiwmsOrderDetailRequest> orderDetailRequests, List<IoOrderDetailBizEntity> detailBizEntities) {
        for (IoOrderDetailBizEntity detailBizEntity : detailBizEntities) {
            UdiwmsOrderDetailRequest item = submitOrderUtil.buildProductInfo(detailBizEntity);
            if (item == null) {
                return detailBizEntity.getNameCode() + "第三方产品编码未关联";
            }
            //封装条码信息
            submitOrderUtil.setCodeList(ioCodeEntities, detailBizEntity, item);
            orderDetailRequests.add(item);
        }
        return null;
    }

    @Resource
    AuthUserDao authUserDao;
    @Resource
    AuthWarehouseUserMapper authWarehouseUserMapper;
    @Resource
    private HttpClient httpClient;
    @Resource
    private ThrSystemDetailService thrSystemDetailService;
    @Resource
    private OrderUploadLogService orderUploadLogService;


    public String getUserName(IoOrderEntity orderEntity) {

        //创建人非供应商

        if (StrUtil.isNotEmpty(orderEntity.getConfirmUser())) {
            AuthUserEntity authUserEntity = authUserDao.selectById(orderEntity.getConfirmUser());
            return authUserEntity.getUserName();
        } else if (StrUtil.isNotEmpty(orderEntity.getReviewUser())) {
            AuthUserEntity authUserEntity = authUserDao.selectById(orderEntity.getReviewUser());
            return authUserEntity.getUserName();
        } else {
            List<AuthWarehouseUser> authWarehouseUsers = authWarehouseUserMapper.selectList(new QueryWrapper<AuthWarehouseUser>().eq("code", orderEntity.getInvCode()));
            if (CollUtil.isNotEmpty(authWarehouseUsers)) {
                return authWarehouseUsers.get(0).getUserName();
            }
        }
        return null;
    }


    public String getDefaultUserName(IoOrderEntity orderEntity) {
        List<AuthWarehouseUser> authWarehouseUsers = authWarehouseUserMapper.selectList(new QueryWrapper<AuthWarehouseUser>().eq("code", orderEntity.getInvCode()));
        if (CollUtil.isNotEmpty(authWarehouseUsers)) {
            return authWarehouseUsers.get(0).getUserName();
        }
        return null;
    }


    /**
     * 提交单据
     *
     * @param orderEntity
     * @param udiwmsOrderRequest
     * @return
     */
    public BaseResponse submitOrder(IoOrderEntity orderEntity, Object udiwmsOrderRequest) {
        //记录日志
        IoOrderUploadLogEntity uploadLog = new IoOrderUploadLogEntity();
        uploadLog.setBillDate(orderEntity.getCreateTime());
        uploadLog.setBillType(orderEntity.getAction());
        uploadLog.setSubmitTime(new Date());
        uploadLog.setBillNo(orderEntity.getBillNo());
        uploadLog.setFromType(Constants.THIRD_ORDER_UPLOAD);
        String response = httpClient.postJson(thrSystemDetailService.getUrl(Constants.URL_NAME_ORDER_SUBMIT_URL), udiwmsOrderRequest);
        if (StrUtil.isNotBlank(response)) {
            try {
                BaseResponse<OrderUploadResponse> baseResponse =
                        JSONObject.parseObject(response, new TypeReference<BaseResponse<OrderUploadResponse>>() {
                        });
                if (baseResponse.getCode() == 20000) {
                    String thirdBillNo = baseResponse.getData().getDjxh();
                    orderEntity.setThirdBillNo(thirdBillNo);
                    orderEntity.setExportStatus(1); //上传成功
                    uploadLog.setStatus(2);
                    uploadLog.setThrBillNo(thirdBillNo);
                    uploadLog.setResult("提交成功");
                    orderDao.updateById(orderEntity);
                    orderUploadLogService.insertOrUpdate(uploadLog);
                    return ResultVOUtils.success("提交成功");
                }
                orderEntity.setExportStatus(2); //上传失败
                orderDao.updateById(orderEntity);
                uploadLog.setStatus(3);
                uploadLog.setResult("提交失败，错误信息：" + baseResponse.getMessage());
                orderUploadLogService.insertOrUpdate(uploadLog);
                return baseResponse;
            } catch (Exception e) {
                log.error("解析提交单据返回结果异常，结果信息：{}", response);
                log.error("异常信息：{}", e);
                uploadLog.setStatus(3);
                uploadLog.setResult("提交失败，错误信息：" + response);
                orderEntity.setExportStatus(2); //上传失败
                orderDao.updateById(orderEntity);
                orderUploadLogService.insertOrUpdate(uploadLog);
                return ResultVOUtils.error(500, "提交失败");
            }
        } else {
            uploadLog.setStatus(3);
            uploadLog.setResult("提交失败，调用接口返回为空");
            orderEntity.setExportStatus(2); //上传失败
            orderDao.updateById(orderEntity);
            orderUploadLogService.insertOrUpdate(uploadLog);
            return ResultVOUtils.error(500, "提交失败");
        }
    }


    /**
     * 获取库存/出入库明细信息
     */
    @Override
    public BaseResponse getInvFeeResult(UdiwmsInvProductsRequest udiwmsInvProductsRequest) {
        PtxhyyInvRequest ptxhyyInvRequest = new PtxhyyInvRequest();
        ptxhyyInvRequest.setKssj(DateUtil.formatDate(udiwmsInvProductsRequest.getStartDate(), "yyyy-MM-dd"));
        ptxhyyInvRequest.setJssj(DateUtil.formatDate(udiwmsInvProductsRequest.getEndDate(), "yyyy-MM-dd"));
        String response = null;
        try {
            response = FileUtils.getFileContent("D://UDI/response.json");
        } catch (IOException e) {
            e.printStackTrace();
        }
//        response = httpClient.postJson(thrSystemDetailService.getUrlExclude(null) + "/CKCX", ptxhyyInvRequest);
//        String response = "{\"code\": 20000,\"data\": {\"list\": [{\"zsl\": 1,\"fyxh\": 30274,\"dw\": \"根\",\"lb\": \"住院\",\"fymc\": \"一次性使用避光压力延长管/根\",\"fydj\": 13,\"rq\": 1709222400000,\"zxks\": \"新10区\"},{\"zsl\": 3,\"fyxh\": 35550,\"dw\": \"个\",\"lb\": \"住院\",\"fymc\": \"静脉林华留置针（苏州林华）/个\",\"fydj\": 3.12,\"rq\": 1709222400000,\"zxks\": \"精神科病区\"},{\"zsl\": 2,\"fyxh\": 29290,\"dw\": \"支\",\"lb\": \"住院\",\"fymc\": \"一次性采血针/支 (100.000%)\",\"fydj\": 0.28,\"rq\": 1709222400000,\"zxks\": \"精神科病区\"},{\"zsl\": 6,\"fyxh\": 29976,\"dw\": \"个\",\"lb\": \"住院\",\"fymc\": \"雾化面罩（口含式）/个 (100.000%)\",\"fydj\": 14.4,\"rq\": 1709222400000,\"zxks\": \"新11区\"},{\"zsl\": 1,\"fyxh\": 29298,\"dw\": \"支\",\"lb\": \"住院\",\"fymc\": \"一次性无菌注射器(1ml 带针)/支\",\"fydj\": 0.27,\"rq\": 1709222400000,\"zxks\": \"03区\"},{\"zsl\": 1,\"fyxh\": 29291,\"dw\": \"支\",\"lb\": \"住院\",\"fymc\": \"一次性使用静脉输液针（头皮针）/支 (100.000%)\",\"fydj\": 0.14,\"rq\": 1709222400000,\"zxks\": \"03区\"},{\"zsl\": 62,\"fyxh\": 29292,\"dw\": \"副\",\"lb\": \"住院\",\"fymc\": \"一次性使用代贴输液器（带针）/副 (100.000%)\",\"fydj\": 0.95,\"rq\": 1709222400000,\"zxks\": \"16区\"},{\"zsl\": 9,\"fyxh\": 30621,\"dw\": \"个\",\"lb\": \"住院\",\"fymc\": \"一次性使用真空采血管（促凝剂）/个\",\"fydj\": 0.58,\"rq\": 1709222400000,\"zxks\": \"05区\"},{\"zsl\": 66,\"fyxh\": 29294,\"dw\": \"支\",\"lb\": \"住院\",\"fymc\": \"一次性无菌注射器（5ml 带针)/支\",\"fydj\": 0.28,\"rq\": 1709222400000,\"zxks\": \"16区\"},{\"zsl\": 4,\"fyxh\": 29278,\"dw\": \"个\",\"lb\": \"住院\",\"fymc\": \"一次性使用负压引流袋/个\",\"fydj\": 5.8,\"rq\": 1709222400000,\"zxks\": \"04区\"}]}}";
        BaseResponse<PageSimpleResponse<PtxhInvResponse>> baseResponse =
                JSONObject.parseObject(response, new TypeReference<BaseResponse<PageSimpleResponse<PtxhInvResponse>>>() {
                });
        if (baseResponse.getCode() == 20000) {
            List<PtxhInvResponse> ptxhInvResponses = baseResponse.getData().getList();
            List<ThrInvResultResponse> thrInvResultResponses = new ArrayList<>();

            Set<String> seenNames = new HashSet<>();
            List<PtxhInvResponse> itemData = new ArrayList<>();

            if (CollUtil.isNotEmpty(ptxhInvResponses)) {
                for (PtxhInvResponse ptxhInvResponse : ptxhInvResponses) {

                    ThrInvResultResponse thrInvResultResponse = new ThrInvResultResponse();
                    thrInvResultResponse.setBillType("SC71021292871198");       //科室收费出库
                    thrInvResultResponse.setMainAction(ConstantType.TYPE_OUT);

                    List<ThrInvWarehouseEntity> thrInvWarehouseEntitys = thrInvWarehouseDao.selectList(new QueryWrapper<ThrInvWarehouseEntity>().eq("code", ptxhInvResponse.getZxksdm()));
                    if (CollUtil.isNotEmpty(thrInvWarehouseEntitys)) {
                        for (ThrInvWarehouseEntity thrInvWarehouseEntity : thrInvWarehouseEntitys) {
                            AuthWarehouseEntity authWarehouseEntity = authWarehouseDao.selectOne(new QueryWrapper<AuthWarehouseEntity>().eq("thirdId", thrInvWarehouseEntity.getCode()).last("limit 1"));
                            if (authWarehouseEntity != null) {
                                thrInvResultResponse.setInvCode(authWarehouseEntity.getCode());
                                thrInvResultResponse.setDeptCode(authWarehouseEntity.getParentId());
                                thrInvResultResponse.setDeptName(ptxhInvResponse.getZxks());
                                thrInvResultResponse.setInvName(ptxhInvResponse.getZxks());
                                thrInvResultResponse.setThrCode(ptxhInvResponse.getFyxh());
                                thrInvResultResponse.setCpmctymc(ptxhInvResponse.getFymc());
                                thrInvResultResponse.setPrice(BigDecimal.valueOf(Double.parseDouble(ptxhInvResponse.getFydj())));
                                thrInvResultResponse.setMeasname(ptxhInvResponse.getDw());
                                thrInvResultResponse.setType(ptxhInvResponse.getLb());
                                thrInvResultResponse.setOutCount(ptxhInvResponse.getZsl());
                                thrInvResultResponse.setReCount(ptxhInvResponse.getZsl());
                                thrInvResultResponse.setBatchNo(null);
                                thrInvResultResponse.setSickerName(ptxhInvResponse.getBrxm());
                                thrInvResultResponse.setSickerCode(ptxhInvResponse.getJzhm());
                                if (StrUtil.isNotEmpty(ptxhInvResponse.getRq())) {
                                    thrInvResultResponse.setChargeTime(ptxhInvResponse.getRq());
                                }
                                thrInvResultResponses.add(thrInvResultResponse);
                                if (seenNames.add(ptxhInvResponse.getFyxh())) {
                                    itemData.add(ptxhInvResponse);
                                    break;
                                }
                            } else {
//                            thrInvWarehouseEntity.setCode(CustomUtil.getId());
//                            thrInvWarehouseEntity.setName(ptxhInvResponse.getZxks());
//                            thrInvWarehouseEntity.setThirdSysFk("thirdId");
//                            thrInvWarehouseEntity.setId(IdUtil.getSnowflakeNextId() + "");
//                            thrInvWarehouseEntity.setParentId(thrInvWarehouseEntity.getCode());
//                            thrInvWarehouseEntity.setRemark("收费出库自动生成");
//                            thrInvWarehouseEntity.setUpdateTime(new Date());
//                            thrInvWarehouseDao.insert(thrInvWarehouseEntity);
//
//                            ThrDeptEntity thrDeptEntity = new ThrDeptEntity();
//                            thrDeptEntity.setCode(thrInvWarehouseEntity.getCode());
//                            thrDeptEntity.setName(thrInvWarehouseEntity.getName());
//                            thrDeptEntity.setPId(0);
//                            thrDeptEntity.setId(IdUtil.getSnowflakeNextId());
//                            thrDeptEntity.setStatus(1);
//                            thrDeptEntity.setRemark("收费出库自动生成");
//                            thrInvWarehouseEntity.setUpdateTime(new Date());
//                            thrDeptEntity.setThirdSysFk(thrDeptEntity.getThirdSysFk());
//                            thrDeptDao.insert(thrDeptEntity);
//                            return ResultVOUtils.error(500, ptxhInvResponse.getZxks() + "第三方科室仓库未创建！");
                                log.error(ptxhInvResponse.getZxks() + "--科室仓库未对照！");
                            }
                        }
                    } else {
                        log.error(ptxhInvResponse.getZxks() + "第三方科室仓库未创建！");
                    }
                }
            }

//            for (PtxhInvResponse invProjectResultEntity : itemData) {
//                if (!basicSkProjectMapper.exists(new QueryWrapper<BasicSkProjectEntity>().eq("code", invProjectResultEntity.getFyxh()))) {
//                    BasicSkProjectEntity basicSkProjectEntity = new BasicSkProjectEntity();
//                    basicSkProjectEntity.setCode(invProjectResultEntity.getFyxh());
//                    basicSkProjectEntity.setName(invProjectResultEntity.getFymc());
//                    basicSkProjectEntity.setType(2);
//                    basicSkProjectEntity.setCreateTime(new Date());
//                    basicSkProjectEntity.setUpdateTime(new Date());
//                    basicSkProjectEntity.setRemark("出入库明细自动生成");
//                    basicSkProjectEntity.setId(IdUtil.getSnowflakeNextId());
//                    basicSkProjectMapper.insert(basicSkProjectEntity);
//                }
//            }

            PageSimpleResponse<ThrInvResultResponse> pageSimpleResponse = new PageSimpleResponse<>();
            pageSimpleResponse.setTotal(thrInvResultResponses.size() + 0l);
            pageSimpleResponse.setList(thrInvResultResponses);
            return ResultVOUtils.success(pageSimpleResponse);
        }
        return baseResponse;
    }


//    public void getHslb() {
//        String response = httpClient.postJson(thrSystemDetailService.getUrl(null), udiwmsUnitRequest);
//        BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
//        return baseResponse;
//    }


    /**
     * 获取项目组套字典
     *
     * @param dlThirdProjectRequest
     * @return
     */
    @Override
    public BaseResponse getBasicProject(DlThirdProjectRequest dlThirdProjectRequest) {

        dlThirdProjectRequest.setFygb("14");
        dlThirdProjectRequest.setPage(1);
        dlThirdProjectRequest.setLimit(10000);
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(null) + "/YLSF", dlThirdProjectRequest);
        BaseResponse<PageSimpleResponse<HisProductEntity>> baseResponse =
                JSONObject.parseObject(response, new TypeReference<BaseResponse<PageSimpleResponse<HisProductEntity>>>() {
                });
        if (baseResponse.getCode() == 20000) {
            PageSimpleResponse<HisProductEntity> pageSimpleResponse = baseResponse.getData();
            List<HisProductEntity> list = pageSimpleResponse.getList();
            List<BasicSkProjectEntity> basicSkProjectEntities = new ArrayList<>();
            int index = 1;
            int index2 = 1;
            log.info("总数：" + list.size());
            for (HisProductEntity hisProductEntity : list) {
                BasicSkProjectEntity basicSkProjectEntity = new BasicSkProjectEntity();
                basicSkProjectEntity.setCode(hisProductEntity.getFyxh());
                basicSkProjectEntity.setName(hisProductEntity.getFymc());
                basicSkProjectEntity.setType(2);
                basicSkProjectEntity.setCreateTime(new Date());
                basicSkProjectEntity.setUpdateTime(new Date());
                basicSkProjectEntity.setRemark("自动下载");
                basicSkProjectEntity.setCategory(hisProductEntity.getFydw());
                basicSkProjectEntity.setGgxh(hisProductEntity.getSm());
                basicSkProjectEntity.setUnit(hisProductEntity.getFydw());
                basicSkProjectEntity.setPrice(hisProductEntity.getFydj());
                if (hisProductEntity.getZfpb().equals("0")) {
                    log.info("在用" + index++ + "");
                    basicSkProjectEntities.add(basicSkProjectEntity);
                } else {
                    log.info("作废" + index2++ + "");
                }
            }
            PageSimpleResponse<BasicSkProjectEntity> dataResponse = new PageSimpleResponse<>();
            dataResponse.setTotal(-666l);
            dataResponse.setList(basicSkProjectEntities);
            return ResultVOUtils.success(dataResponse);
        }
        return ResultVOUtils.error(500, "获取项目组套字典失败！");


    }

    @Override
    public BaseResponse getSickInfo(GetSickRequest getSickRequest) {
        IPage<SickerEntity> page = new Page<>(getSickRequest.getPage(), getSickRequest.getLimit());
        IPage<SickerEntity> productEntityIPage = ptxhyySickerMapper.selectPage(page, new QueryWrapper<SickerEntity>()
                .lambda()
                .like(StringUtils.isNotBlank(getSickRequest.getCode()), SickerEntity::getZYHM, getSickRequest.getCode())
                .like(StringUtils.isNotBlank(getSickRequest.getName()), SickerEntity::getBRXM, getSickRequest.getName()));
        List<BasicSkSickerResponse> basicSkSickerResponses = new ArrayList<>();
        productEntityIPage.getRecords().forEach(sickerEntity -> {
            basicSkSickerResponses.add(BasicSkSickerResponse.builder()
                    .sickerId(sickerEntity.getZYH())
                    .code(sickerEntity.getZYH())
                    .name(sickerEntity.getBRXM())
                    .adNum(sickerEntity.getZYHM())
                    .inHospTime(sickerEntity.getRYRQ())
                    .outHospTime(sickerEntity.getCYRQ())
                    .build());
        });

        PageSimpleResponse<BasicSkSickerResponse> pageSimpleResponse = new PageSimpleResponse<>();
        pageSimpleResponse.setTotal(productEntityIPage.getTotal());
        pageSimpleResponse.setList(basicSkSickerResponses);
        return ResultVOUtils.success(pageSimpleResponse);
    }
}
