package thyyxxk.webserver.service.medicine;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.medicine.TaoBaoEnum;
import thyyxxk.webserver.entity.medicine.YpPartYljg;
import thyyxxk.webserver.entity.medicine.YpTableYljg;
import thyyxxk.webserver.entity.medicine.YpTopYljg;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.*;

/**
 * @ClassName YpTaoBaoService
 * @Author hsh
 * @Date 2025/5/21 0021 16:44
 * @Version 1.0
 * @Description 淘宝接口实现
 **/
@Slf4j
@Service
public class YpTaoBaoService {

    private final TaobaoClient client = TaoBaoEnum.getClient();

    private final String refEntId = TaoBaoEnum.REF_ENT_ID.getValue("ref_ent_id");

    public ResultVo<Map<String,Object>> queryUpBillCode(String code) {
        if(StringUtils.isBlank(code)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "通过追溯码查询对应的上游企业出库单的单据号失败，code参数为空");
        }
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgQueryUpbillcodeRequest req = new AlibabaAlihealthDrugtraceTopYljgQueryUpbillcodeRequest();
            req.setCode(code);
            req.setRefEntId(refEntId);
            AlibabaAlihealthDrugtraceTopYljgQueryUpbillcodeResponse rsp = client.execute(req);
            if(rsp.getResult().getSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "查询上游企业出库单的单据号信息成功");
            } else {
                log.error("查询上游企业出库单的单据号信息，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询上游企业出库单的单据号信息，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModelList());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("查询上游企业出库单的单据号信息，系统错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询上游企业出库单的单据号信息失败:" + e.getMessage());
        }
    }

    public ResultVo<Map<String, Object>> queryCodeDetail(String codes) {
        if(StringUtils.isBlank(codes)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "根据追溯码查询码信息失败，codes为空");
        }
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgQueryCodedetailResponse rsp = queryCodeDetailItem(codes);
            if(rsp.getResult().getResponseSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "根据追溯码查询码信息成功");
            } else {
                log.error("根据追溯码查询码信息，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "根据追溯码查询码信息，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModels());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("根据追溯码查询码信息，错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "根据追溯码查询码信息，错误信息: " + e.getMessage());
        }
    }

    private AlibabaAlihealthDrugtraceTopYljgQueryCodedetailResponse queryCodeDetailItem(String codes) {
        AlibabaAlihealthDrugtraceTopYljgQueryCodedetailResponse rsp = null;
        try{
            AlibabaAlihealthDrugtraceTopYljgQueryCodedetailRequest req = new AlibabaAlihealthDrugtraceTopYljgQueryCodedetailRequest();
            req.setRefEntId(refEntId);
            req.setCodes(codes);
            rsp = client.execute(req);
        } catch(Exception e){
            log.error("根据追溯码查询码信息，错误信息{}", e.getMessage());
        }
        return rsp;
    }

    public ResultVo<Map<String, Object>> queryYljgListUpOut(YpTopYljg yljg) {
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgListupoutRequest req = new AlibabaAlihealthDrugtraceTopYljgListupoutRequest();
            BeanUtils.copyProperties(yljg, req, AlibabaAlihealthDrugtraceTopYljgListupoutRequest.class);
            req.setRefEntId(refEntId);
            if (req.getPageSize() == null) {
                req.setPageSize(20L);
            }
            if (req.getPage() == null) {
                req.setPage(1L);
            }
            AlibabaAlihealthDrugtraceTopYljgListupoutResponse rsp = client.execute(req);
            if(rsp.getResult().getResponseSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "医疗机构查询本企业上游企业出库单据信息成功");
            } else {
                log.error("医疗机构查询本企业上游企业出库单据信息，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医疗机构查询本企业上游企业出库单据信息，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModel().getResultList());
            resultMap.put("totalNum", rsp.getResult().getModel().getTotalNum());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("医疗机构查询本企业上游企业出库单据信息，系统错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医疗机构查询本企业上游企业出库单据信息，系统错误信息: " + e.getMessage());
        }
    }

    public ResultVo<Map<String, Object>> queryYljgListUpOutDetail(String billCode, String fromRefUserId, String toRefUserId) {
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgListupoutDetailRequest req = new AlibabaAlihealthDrugtraceTopYljgListupoutDetailRequest();
            req.setRefEntId(refEntId);
            req.setBillCode(billCode);
            req.setFromRefUserId(fromRefUserId);
            req.setToRefUserId(toRefUserId);
            AlibabaAlihealthDrugtraceTopYljgListupoutDetailResponse rsp = client.execute(req);
            if(rsp.getResult().getSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "医疗机构查询上游出库单明细(带追溯码信息)成功");
            } else {
                log.error("医疗机构查询上游出库单明细(带追溯码信息)，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医疗机构查询上游出库单明细(带追溯码信息)，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModel());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("医疗机构查询上游出库单明细(带追溯码信息)，错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医疗机构查询上游出库单明细(带追溯码信息)，错误信息: " + e.getMessage());
        }
    }

    public ResultVo<Map<String, Object>> queryGetByRefEntId(String destRefEntId) {
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgQueryGetbyrefentidRequest req = new AlibabaAlihealthDrugtraceTopYljgQueryGetbyrefentidRequest();
            req.setRefEntId(refEntId);
            req.setDestRefEntId(destRefEntId);
            AlibabaAlihealthDrugtraceTopYljgQueryGetbyrefentidResponse rsp = client.execute(req);
            if(rsp.getResult().getResponseSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "根据企业唯一标识查看企业详细信息成功");
            } else {
                log.error("根据企业唯一标识查看企业详细信息，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "根据企业唯一标识查看企业详细信息，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModel());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("根据企业唯一标识查看企业详细信息，错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "根据企业唯一标识查看企业详细信息，错误信息: " + e.getMessage());
        }
    }

    public ResultVo<Map<String, Object>> queryYljgDrugTable(YpTableYljg yljg) {
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgDrugtableRequest req = new AlibabaAlihealthDrugtraceTopYljgDrugtableRequest();
            BeanUtils.copyProperties(yljg, req, AlibabaAlihealthDrugtraceTopYljgDrugtableRequest.class);
            req.setRefEntId(refEntId);
            if (req.getPageSize() == null) {
                req.setPageSize(20L);
            }
            if (req.getPage() == null) {
                req.setPage(1L);
            }
            AlibabaAlihealthDrugtraceTopYljgDrugtableResponse rsp = client.execute(req);
            if(rsp.getResult().getResponseSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "查询药品目录信息成功");
            } else {
                log.error("查询药品目录信息，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询药品目录信息，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModel().getResultList());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("查询药品目录信息，错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询药品目录信息，错误信息: " + e.getMessage());
        }
    }

    public ResultVo<Map<String, Object>> queryGetDrugList(YpTableYljg yljg) {
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgGetdruglistRequest req = new AlibabaAlihealthDrugtraceTopYljgGetdruglistRequest();
            BeanUtils.copyProperties(yljg, req, AlibabaAlihealthDrugtraceTopYljgGetdruglistRequest.class);
            req.setRefEntId(refEntId);
            if (req.getPageSize() == null) {
                req.setPageSize(20L);
            }
            if (req.getPage() == null) {
                req.setPage(1L);
            }
            AlibabaAlihealthDrugtraceTopYljgGetdruglistResponse rsp = client.execute(req);
            if("true".equals(rsp.getResult().getResponseSuccess())){
                resultMap.put("code", 0);
                resultMap.put("message", "查询药品信息成功");
            } else {
                log.error("查询药品信息，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询药品信息，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModel().getResultList());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("查询药品信息，错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询药品信息，错误信息: " + e.getMessage());
        }
    }

    public ResultVo<Map<String, Object>> queryListParts(YpPartYljg yljg) {
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgQueryListpartsRequest req = new AlibabaAlihealthDrugtraceTopYljgQueryListpartsRequest();
            BeanUtils.copyProperties(yljg, req, AlibabaAlihealthDrugtraceTopYljgQueryListpartsRequest.class);
            req.setRefEntId(refEntId);
            if (req.getPageSize() == null) {
                req.setPageSize(20L);
            }
            if (req.getPage() == null) {
                req.setPage(1L);
            }
            AlibabaAlihealthDrugtraceTopYljgQueryListpartsResponse rsp = client.execute(req);
            if(rsp.getResult().getResponseSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "查询往来单位列表成功");
            } else {
                log.error("查询往来单位列表，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询往来单位列表，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModel().getResultList());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("查询往来单位列表，错误信息{}", e.getMessage());
            resultMap.put("code", -1);
            resultMap.put("message", "查询往来单位列表失败: " + e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询往来单位列表，错误信息: " + e.getMessage());
        }
    }

    public ResultVo<Map<String, Object>> uploadinoutbill(String fromEndId, String traceCodes) {
        Map<String, Object> resultMap = new HashMap<>();
        AlibabaAlihealthDrugtraceTopYljgUploadinoutbillResponse rsp = uploadinoutbillItem(fromEndId, traceCodes);
        if(rsp.getResponseSuccess()){
            resultMap.put("code", 0);
            resultMap.put("message", "出入库单据上传成功");
        } else {
            log.error("出入库单据上传，淘宝开放平台错误信息{}", rsp.getMsgInfo());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "出入库单据上传，淘宝开放平台错误信息: " + rsp.getMsgInfo());
        }
        resultMap.put("msgCode", rsp.getMsgCode());
        resultMap.put("data", rsp.getBody());
        return ResultVoUtil.success(resultMap);
    }

    public ResultVo<Map<String, Object>> queryRelation(String code, String desRefEntId) {
        if(StringUtils.isBlank(code)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "单码(一般是大包装码)关联关系查询失败，code参数为空");
        }
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgQueryRelationResponse rsp = queryRelationItem(code, desRefEntId);
            if(rsp.getResult().getResponseSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "查询单码关联关系成功");
            } else {
                log.error("查询单码关联关系信息，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询单码关联关系信息，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModelList());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            e.printStackTrace();
            log.error("查询单码关联关系，系统错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询单码关联关系，系统错误信息: " + e.getMessage());
        }
    }

    private AlibabaAlihealthDrugtraceTopYljgUploadinoutbillResponse uploadinoutbillItem(String fromEndId, String traceCodes) {
        AlibabaAlihealthDrugtraceTopYljgUploadinoutbillResponse rsp = null;
        try{
            AlibabaAlihealthDrugtraceTopYljgUploadinoutbillRequest req = new AlibabaAlihealthDrugtraceTopYljgUploadinoutbillRequest();

            req.setBillCode("BC001_" + System.currentTimeMillis());
            req.setBillTime(new Date());
            req.setBillType(102L);
            req.setPhysicType(3L);
            req.setRefUserId(refEntId);
            req.setFromUserId(fromEndId);
            req.setToUserId(refEntId);
            req.setTraceCodes(traceCodes);
            req.setClientType("2");
            rsp = client.execute(req);
        } catch(Exception e){
            log.error("出入库单据上传，错误信息{}", e.getMessage());
        }
        return rsp;
    }

    private AlibabaAlihealthDrugtraceTopYljgQueryRelationResponse queryRelationItem(String code, String desRefEntId) {
        AlibabaAlihealthDrugtraceTopYljgQueryRelationResponse rsp = null;
        try{
            AlibabaAlihealthDrugtraceTopYljgQueryRelationRequest req = new AlibabaAlihealthDrugtraceTopYljgQueryRelationRequest();
            req.setRefEntId(refEntId);
            req.setCode(code);
            req.setDesRefEntId(desRefEntId);
            rsp = client.execute(req);
        } catch(Exception e){
            log.error("查询单码关联关系信息，错误信息{}", e.getMessage());
        }
        return rsp;
    }

    public ResultVo<Map<String, Object>> queryGetEntInfo(String entName) {
        if(StringUtils.isBlank(entName)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "通过企业名得到唯一标识查询失败，企业名为空");
        }
        Map<String, Object> resultMap = new HashMap<>();
        try{
            AlibabaAlihealthDrugtraceTopYljgQueryGetentinfoResponse rsp = queryGetEntInfoItem(entName);
            if(rsp.getResult().getResponseSuccess()){
                resultMap.put("code", 0);
                resultMap.put("message", "根据企业名查询企业id成功");
            } else {
                log.error("根据企业名查询企业id，淘宝开放平台错误信息{}", rsp.getResult().getMsgInfo());
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "根据企业名查询企业id，淘宝开放平台错误信息: " + rsp.getResult().getMsgInfo());
            }
            resultMap.put("msgCode", rsp.getResult().getMsgCode());
            resultMap.put("data", rsp.getResult().getModel());
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.error("根据企业名查询企业id，系统错误信息{}", e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "根据企业名查询企业id，系统错误信息: " + e.getMessage());
        }
    }

    private AlibabaAlihealthDrugtraceTopYljgQueryGetentinfoResponse queryGetEntInfoItem(String entName) {
        AlibabaAlihealthDrugtraceTopYljgQueryGetentinfoResponse rsp = null;
        try {
            AlibabaAlihealthDrugtraceTopYljgQueryGetentinfoRequest req = new AlibabaAlihealthDrugtraceTopYljgQueryGetentinfoRequest();
            req.setEntName(entName);
            rsp = client.execute(req);
        } catch (Exception e) {
            log.error("查询单码关联关系信息，错误信息{}", e.getMessage());
        }

        return rsp;
    }

    /**
     * 通过大包装追溯码和发货厂商id查询大包装里的小追溯码
     * @param parentCode
     * @return
     */
    public ResultVo<Map<String, Object>> getCodeByParent(String parentCode) {
        Map<String, Object> resultMap = new HashMap<>();
        // 1、通过追溯码查询厂商企业id
        AlibabaAlihealthDrugtraceTopYljgQueryCodedetailResponse entRsp = queryCodeDetailItem(parentCode);
        if(entRsp.getResult().getResponseSuccess()){
            List<AlibabaAlihealthDrugtraceTopYljgQueryCodedetailResponse.CodeFullInfoDto> models = entRsp.getResult().getModels();
            if(models != null && models.size() > 0){
                String entId = models.get(0).getpUserEntDTO().getRefEntId();
                // 2、通过大包装追溯码和发货厂商企业id进行出入库单据上传
                uploadinoutbillItem(entId, parentCode);
                // 3、查询大包装码对应的子码信息；注意：入参的大包装码必须在本企业的码上放心平台上传入库单后再调用接口，才会返回子码信息。
                AlibabaAlihealthDrugtraceTopYljgQueryRelationResponse relationRsp = queryRelationItem(parentCode, refEntId);
                if(relationRsp.getResult().getResponseSuccess()){
                    resultMap.put("code", 0);
                    resultMap.put("message", "查询单码关联关系成功");
                    resultMap.put("msgCode", relationRsp.getResult().getMsgCode());
                    resultMap.put("data", relationRsp.getResult().getModelList());
                } else {
                    return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询单码关联关系信息，淘宝开放平台错误信息: " + relationRsp.getResult().getMsgInfo());
                }
            }

        }
        return ResultVoUtil.success(resultMap);
    }
}
