package com.clx.performance.job;

import com.clx.performance.config.PerformanceSmartCompanyNoConfig;
import com.clx.performance.dao.AppDao;
import com.clx.performance.dao.OrderChildDao;
import com.clx.performance.dao.OrderChildWeighPictureDao;
import com.clx.performance.enums.AppEnum;
import com.clx.performance.enums.OrderChildEnum;
import com.clx.performance.enums.PerformanceResultEnum;
import com.clx.performance.model.App;
import com.clx.performance.model.OrderChild;
import com.clx.performance.model.OrderChildWeighPicture;
import com.clx.performance.struct.OrderChildWeighPictureStruct;
import com.msl.common.job.JobLog;
import com.msl.common.open.OpenClient;
import com.msl.common.open.RequestConfig;
import com.msl.common.result.Result;
import com.smart.weight.action.WeighingSignatureAction;
import com.smart.weight.dto.WeighingSignatureDto;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
public class WeighingOderPictureJob implements InitializingBean {


    @Autowired
    private OrderChildDao orderChildDao;

    @Autowired
    private OrderChildWeighPictureStruct pictureStruct;

    @Autowired
    private OrderChildWeighPictureDao pictureDao;

    @Autowired
    private PerformanceSmartCompanyNoConfig companyNoConfig;

    @Autowired
    private AppDao appDao;
    private App app;


    /**
     * 定时拉取过磅磅单图片
     */
    @XxlJob("weighingOderPicture")
    @Transactional(rollbackFor = Exception.class)
    public void weighingOderPicture() {
        try {
            getWeighingOderPicture();
        } catch (Exception e) {
            log.warn("定时任务获取磅单图片信息失败，异常原因:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("定时任务获取磅单图片信息失败，异常原因=====================", e);
        }
    }

    /**
     * 定时拉取过磅磅单图片
     **/
    public void getWeighingOderPicture(){
        //运单状态集合
        List<Integer> status = new ArrayList<>();
        status.add(OrderChildEnum.Status.UNLOAD.getCode());
        status.add(OrderChildEnum.Status.UNSETTLE.getCode());
        //查询指定运单数据
        List<OrderChild> orderChilds = orderChildDao.listChidNosByStatus(status);
        log.info("查询运单数据返回：{}",orderChilds);

        //查询运单下的电子磅单数据
        if(CollectionUtils.isNotEmpty(orderChilds)){
            //空判断
            if(Objects.isNull(app)){
                //重新赋值
                app= appDao.getOneByField(App::getUniqueIdentifier, AppEnum.UniqueIdentifier.SMART_WEIGHT.getCode()).orElseThrow(
                        PerformanceResultEnum.DATA_NOT_FIND);
            }
            //组装配置信息
            RequestConfig config = new RequestConfig()
                    .setAppId(app.getAppNo())
                    .setAppKey(app.getAppKey())
                    .setGatewayUrl(app.getCallback());

            //集合对象
            List<OrderChildWeighPicture> pictures = new ArrayList<>();
            for(OrderChild orderChild:orderChilds){
                //通过运单号码查询电子磅单图片
                WeighingSignatureAction weightAction = new WeighingSignatureAction();
                weightAction.setChildNo(orderChild.getChildNo());
                weightAction.setCompanyNo(companyNoConfig.getCompanyNo());
                log.info("请求电子磅单参数,{}",weightAction);
                Result<List<WeighingSignatureDto>> weighSignature = OpenClient.doAction(config, weightAction);
                log.info("请求电子磅单返回结果,{}",weighSignature);
                //数据处理
                if(!Objects.equals(weighSignature.getCode(),0)){
                    continue;
                }
                List<WeighingSignatureDto> weighSignatures = weighSignature.getData();
                if (CollectionUtils.isNotEmpty(weighSignatures)) {
                    for(WeighingSignatureDto weighingSignatureDto:weighSignatures){
                        OrderChildWeighPicture picture = pictureStruct.convert(weighingSignatureDto);
                        picture.setChildNo(orderChild.getChildNo());//对象转换
                        pictures.add(picture);
                    }
                }

            }

            log.info("电子磅单图片,{}",pictures);
            //保存电子磅单图片
            if(CollectionUtils.isNotEmpty(pictures)){
                List<String> childNos = pictures.stream().map(OrderChildWeighPicture::getChildNo).distinct().collect(Collectors.toList());
                pictureDao.deleteInField(OrderChildWeighPicture::getChildNo,childNos);
                pictureDao.saveBatchList(pictures);
            }

        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        app= appDao.getOneByField(App::getUniqueIdentifier, AppEnum.UniqueIdentifier.SMART_WEIGHT.getCode()).orElseThrow(
                PerformanceResultEnum.DATA_NOT_FIND);

    }

}
