package com.glxp.mipsdl.client.ptxhyy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
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.glxp.mipsdl.client.CommonHttpClient;
import com.glxp.mipsdl.client.ptxhyy.entity.HisFyRequest;
import com.glxp.mipsdl.client.ptxhyy.entity.HisProductEntity;
import com.glxp.mipsdl.client.ptxhyy.entity.PostHisDetailRequest;
import com.glxp.mipsdl.client.ptxhyy.entity.PostHisRequest;
import com.glxp.mipsdl.config.ThirdSysConfig;
import com.glxp.mipsdl.constant.Constants;
import com.glxp.mipsdl.dao.basic.BasicBussinessTypeDao;
import com.glxp.mipsdl.dao.basic.BasicProductsDao;
import com.glxp.mipsdl.dao.basic.BasicUdirelDao;
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.thrsys.ThrSystemBusApiDao;
import com.glxp.mipsdl.entity.basic.BasicBussinessTypeEntity;
import com.glxp.mipsdl.entity.basic.BasicProductsEntity;
import com.glxp.mipsdl.entity.basic.BasicUdirelEntity;
import com.glxp.mipsdl.entity.inout.IoCodeEntity;
import com.glxp.mipsdl.entity.inout.IoOrderDetailBizEntity;
import com.glxp.mipsdl.entity.inout.IoOrderEntity;
import com.glxp.mipsdl.entity.thrsys.ThrSystemBusApiEntity;
import com.glxp.mipsdl.http.HttpClient;
import com.glxp.mipsdl.req.base.UdiwmsOrderRequest;
import com.glxp.mipsdl.req.base.UdiwmsProductRequest;
import com.glxp.mipsdl.res.BaseResponse;
import com.glxp.mipsdl.res.PageSimpleResponse;
import com.glxp.mipsdl.res.udiwms.ThrProductsResponse;
import com.glxp.mipsdl.service.thrsys.ThrSystemDetailService;
import com.glxp.mipsdl.util.DateUtil;
import com.glxp.mipsdl.util.ResultVOUtils;
import com.glxp.mipsdl.util.SubmitOrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 平潭协和医院HIS系统接口
 */
@Slf4j
@Service(value = "100009HttpClient")
public class PtxhyyHisClient extends CommonHttpClient {

    @Resource
    private HttpClient httpClient;
    @Resource
    private ThirdSysConfig thirdSysConfig;
    @Autowired
    private ThrSystemDetailService thrSystemDetailService;

    @Override
    public BaseResponse getProducts(UdiwmsProductRequest udiwmsProductRequest) {

        HisFyRequest hisFyRequest = new HisFyRequest();
        hisFyRequest.setFyxh(udiwmsProductRequest.getCode());
        hisFyRequest.setFymc(udiwmsProductRequest.getName());
        String response = httpClient.postJson(thrSystemDetailService.getUrl(Constants.URL_NAME_PI_QUERY_URL), hisFyRequest);
        BaseResponse<PageSimpleResponse<HisProductEntity>> baseResponse = JSONObject.parseObject(response, new TypeReference<BaseResponse<PageSimpleResponse<HisProductEntity>>>() {
        });
        List<ThrProductsResponse> thrProductsResponses = new ArrayList<>();
        List<HisProductEntity> hisProductEntities = baseResponse.getData().getList();
        if (CollUtil.isNotEmpty(hisProductEntities)) {
            for (HisProductEntity hisProductEntity : hisProductEntities) {
                ThrProductsResponse thrProductsResponse = new ThrProductsResponse();
                thrProductsResponse.setCode(hisProductEntity.getFyxh());
                thrProductsResponse.setName(hisProductEntity.getFymc());
                thrProductsResponse.setFlbm(hisProductEntity.getFygb());
                thrProductsResponse.setPrice(hisProductEntity.getFydj());
                thrProductsResponse.setQtbm(hisProductEntity.getSm());
                thrProductsResponse.setCpms(hisProductEntity.getSfmc());
                thrProductsResponse.setMeasname(hisProductEntity.getFydw());
                thrProductsResponses.add(thrProductsResponse);
            }
        }
        PageSimpleResponse<ThrProductsResponse> pageSimpleResponse = new PageSimpleResponse<>();
        pageSimpleResponse.setList(thrProductsResponses);
        pageSimpleResponse.setTotal(-666l);           //表示全量下载
        return ResultVOUtils.success(pageSimpleResponse);
    }

    @Resource
    private IoOrderDao orderDao;
    @Resource
    private ThrSystemBusApiDao thrSystemBusApiDao;
    @Resource
    private BasicBussinessTypeDao basicBussinessTypeDao;
    @Resource
    private IoCodeDao codeDao;
    @Resource
    private IoOrderDetailBizDao orderDetailBizDao;
    @Resource
    private BasicUdirelDao basicUdirelDao;
    @Resource
    private BasicProductsDao basicProductsDao;
    @Resource
    private SubmitOrderUtil submitOrderUtil;

    @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()));
        udiwmsOrderRequest.setBillDate(DateUtil.formatDateTime(orderEntity.getCreateTime()));
        //查询对应的第三方单据类型
        ThrSystemBusApiEntity thrSystemBusApiEntity = thrSystemBusApiDao.selectOne(new LambdaQueryWrapper<ThrSystemBusApiEntity>().eq(ThrSystemBusApiEntity::getCode, udiwmsOrderRequest.getBillType()));
        if (StrUtil.isBlank(thrSystemBusApiEntity.getUrl())) {
            return ResultVOUtils.error(500, "接口未配置，无法提交！");
        }

        PostHisRequest postHisRequest = new PostHisRequest();

        //查询单据类型，设置往来单位信息
        BasicBussinessTypeEntity basicBussinessTypeEntity = basicBussinessTypeDao.selectByAction(orderEntity.getAction());
        if (basicBussinessTypeEntity.getCorpType().equals(Constants.CORP_HOSPTIAL)) {
            //医院客户
            postHisRequest.setZyh(orderEntity.getFromCorp());
        } else {
            return ResultVOUtils.error(500, "非使用出库单据");
        }

        //组装单据明细数据
        List<IoCodeEntity> ioCodeEntities = codeDao.selectList(new LambdaQueryWrapper<IoCodeEntity>()
                .eq(IoCodeEntity::getOrderId, orderEntity.getBillNo())
        );
        List<PostHisDetailRequest> items = new ArrayList<>();
        //查询业务单据详情
        List<IoOrderDetailBizEntity> detailBizEntities = orderDetailBizDao.selectList(new LambdaQueryWrapper<IoOrderDetailBizEntity>().eq(IoOrderDetailBizEntity::getOrderIdFk, orderEntity.getBillNo()));
        for (IoOrderDetailBizEntity orderDetailBizEntity : detailBizEntities) {
            List<IoCodeEntity> codeEntities = filterCodes(orderDetailBizEntity, ioCodeEntities);
            String udibm = codeEntities.stream().map(IoCodeEntity::getCode).collect(Collectors.joining(","));
            PostHisDetailRequest postHisDetailRequest = new PostHisDetailRequest();
            postHisDetailRequest.setUdibm(udibm);
            BasicUdirelEntity basicUdirel = basicUdirelDao.selectById(orderDetailBizEntity.getBindRlFk());
            BasicProductsEntity basicProducts = basicProductsDao.selectOne(new LambdaQueryWrapper<BasicProductsEntity>().eq(BasicProductsEntity::getUuid, basicUdirel.getUuid()));
            String thirdProductId = (String) ReflectUtil.getFieldValue(basicUdirel, thirdSysConfig.getThirdId());
            postHisDetailRequest.setYldj(basicProducts.getPrice() + "");
            postHisDetailRequest.setYlsl(orderDetailBizEntity.getReCount() + "");
            postHisDetailRequest.setYlxh(thirdProductId);
            items.add(postHisDetailRequest);
        }
        postHisRequest.setDetailList(items);
        return submitOrderUtil.submitOrder(orderEntity, postHisRequest);
    }


    public List<IoCodeEntity> filterCodes(IoOrderDetailBizEntity orderDetailBizEntity, List<IoCodeEntity> codeEntities) {
        List<IoCodeEntity> result = new ArrayList<>();
        if (CollUtil.isNotEmpty(codeEntities)) {
            for (IoCodeEntity codeEntity : codeEntities) {
                if ((codeEntity.getRelId() + "").equals(orderDetailBizEntity.getBindRlFk())
                        && StrUtil.trimToEmpty(codeEntity.getBatchNo()).equals(StrUtil.trimToEmpty(orderDetailBizEntity.getBatchNo()))) {
                    result.add(codeEntity);
                }
            }
        }
        return result;
    }
}
