package com.glxp.mipsdl.util;

import cn.hutool.core.bean.BeanUtil;
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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.glxp.mipsdl.config.ThirdSysConfig;
import com.glxp.mipsdl.constant.Constants;
import com.glxp.mipsdl.dao.basic.BasicProductsDao;
import com.glxp.mipsdl.dao.basic.BasicUdirelDao;
import com.glxp.mipsdl.dao.inout.IoOrderDao;
import com.glxp.mipsdl.dao.inout.IoOrderUploadLogDao;
import com.glxp.mipsdl.dao.thrsys.ThrProductsDao;
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.inout.IoOrderUploadLogEntity;
import com.glxp.mipsdl.entity.thrsys.ThrProductsEntity;
import com.glxp.mipsdl.http.HttpClient;
import com.glxp.mipsdl.req.base.UdiwmsOrderDetailRequest;
import com.glxp.mipsdl.res.BaseResponse;
import com.glxp.mipsdl.service.thrsys.ThrSystemDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 提交单据工具类
 */
@Slf4j
@Component
public class SubmitOrderUtil {

    @Resource
    private BasicUdirelDao basicUdirelDao;
    @Resource
    private BasicProductsDao basicProductsDao;
    @Resource
    private ThirdSysConfig thirdSysConfig;
    @Resource
    private ThrProductsDao thrProductsDao;
    @Resource
    private HttpClient httpClient;
    @Resource
    private ThrSystemDetailService thrSystemDetailService;
    @Resource
    private IoOrderUploadLogDao orderUploadLogDao;
    @Resource
    private IoOrderDao orderDao;

    /**
     * 查找产品对应的条码详情
     *
     * @param orderDetailBizEntity
     * @param codeEntities
     * @return
     */
    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;
    }

    /**
     * 封装码参数
     *
     * @param ioCodeEntities
     * @param detailBizEntity
     * @param item
     */
    public void setCodeList(List<IoCodeEntity> ioCodeEntities, IoOrderDetailBizEntity detailBizEntity, UdiwmsOrderDetailRequest item) {
        List<IoCodeEntity> codeList = filterCodes(detailBizEntity, ioCodeEntities);
        if (CollUtil.isNotEmpty(codeList)) {
            List<UdiwmsOrderDetailRequest.CodeDetailEntity> codes = new ArrayList<>();
            codeList.forEach(ioCodeEntity -> {
                UdiwmsOrderDetailRequest.CodeDetailEntity codeDetailEntity = new UdiwmsOrderDetailRequest.CodeDetailEntity();
                BeanUtil.copyProperties(ioCodeEntity, codeDetailEntity);
                codes.add(codeDetailEntity);
            });
            item.setCodeList(codes);
        }
    }

    /**
     * 构造提交单据参数的产品信息参数
     *
     * @param detailBizEntity
     * @return
     */
    public UdiwmsOrderDetailRequest buildProductInfo(IoOrderDetailBizEntity detailBizEntity) {
        //查询产品信息
        BasicUdirelEntity basicUdirel = basicUdirelDao.selectById(detailBizEntity.getBindRlFk());
        BasicProductsEntity basicProducts = basicProductsDao.selectOne(new LambdaQueryWrapper<BasicProductsEntity>().eq(BasicProductsEntity::getUuid, basicUdirel.getUuid()).last("limit 1"));

        UdiwmsOrderDetailRequest item = new UdiwmsOrderDetailRequest();
        BeanUtil.copyProperties(detailBizEntity, item);

        item.setProductDate(DateUtil.formatExpireTime(StrUtil.isBlank(detailBizEntity.getProductDate()) ? null : "20" + detailBizEntity.getProductDate()));
        item.setExpireDate(DateUtil.formatExpireTime(StrUtil.isBlank(detailBizEntity.getExpireDate()) ? null : "20" + detailBizEntity.getExpireDate()));

        String thirdProductId = (String) ReflectUtil.getFieldValue(basicUdirel, thirdSysConfig.getThirdId());
        item.setProductId(thirdProductId); //产品ID
        //查询第三方产品名称
        ThrProductsEntity thrProductsEntity = thrProductsDao.selectOne(new LambdaQueryWrapper<ThrProductsEntity>()
                .eq(ThrProductsEntity::getCode, thirdProductId).last("limit 1"));
        if (thrProductsEntity == null) {
            log.error("第三方产品编码未关联");
            return null;
        }
        item.setProductName(thrProductsEntity.getName()); //产品名称
        item.setBindRlFk(detailBizEntity.getBindRlFk());
        item.setStandard(detailBizEntity.getSpec()); //规格型号
        item.setBillNo(detailBizEntity.getOrderIdFk()); //单据号
        item.setRegisterNo(detailBizEntity.getCertCode()); //注册/备案证号
        item.setManufactory(basicProducts.getManufactory()); //生产厂家
        item.setMeasname(basicProducts.getMeasname()); //计量单位
        item.setAllowNoBatch(IntUtil.value(basicProducts.getAllowNoBatch())); //是否允许无批次号
        item.setManufactoryCode(thrProductsEntity.getManufactoryCode());
        item.setSupCode(thrProductsEntity.getSupCode());
        item.setCplb(thrProductsEntity.getFlbm());
        item.setHslb(thrProductsEntity.getCplb());
        item.setCount(detailBizEntity.getCount());
        return item;
    }

    /**
     * 处理提交单据，记录日志，解析结果逻辑
     *
     * @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 baseResponse = JSONObject.parseObject(response, BaseResponse.class);
                if (baseResponse.getCode() == 20000) {
                    String thirdBillNo = String.valueOf(baseResponse.getData());
                    orderEntity.setThirdBillNo(thirdBillNo);
                    orderEntity.setExportStatus(1); //上传成功
                    uploadLog.setStatus(2);
                    uploadLog.setThrBillNo(thirdBillNo);
                    uploadLog.setResult("提交成功");
                    orderDao.updateById(orderEntity);
                    orderUploadLogDao.insert(uploadLog);
                    return ResultVOUtils.success("提交成功");
                }
                orderEntity.setExportStatus(2); //上传失败
                uploadLog.setStatus(3);
                uploadLog.setResult("提交失败，错误信息：" + baseResponse.getMessage());
                orderUploadLogDao.insert(uploadLog);
                return baseResponse;
            } catch (Exception e) {
                log.error("解析提交单据返回结果异常，结果信息：{}", response);
                log.error("异常信息：{}", e);
                uploadLog.setStatus(3);
                uploadLog.setResult("提交失败，错误信息：" + response);
                orderEntity.setExportStatus(2); //上传失败
                orderDao.updateById(orderEntity);
                orderUploadLogDao.insert(uploadLog);
                return ResultVOUtils.error(500, "提交失败");
            }
        } else {
            uploadLog.setStatus(3);
            uploadLog.setResult("提交失败，调用接口返回为空");
            orderEntity.setExportStatus(2); //上传失败
            orderDao.updateById(orderEntity);
            orderUploadLogDao.insert(uploadLog);
            return ResultVOUtils.error(500, "提交失败");
        }
    }

}
