package com.heyu.api.listener.delay.handler;


import com.alibaba.fastjson.JSONObject;
import com.heyu.api.data.dao.vv.VvPackageDao;
import com.heyu.api.data.dao.vv.VvTradeOrderLineDao;
import com.heyu.api.data.dto.PackageDelivedDelayDTO;
import com.heyu.api.data.entity.vv.VvPackageEntity;
import com.heyu.api.data.entity.vv.VvTradeOrderLineEntity;
import com.heyu.api.data.enums.OrderStatusEnums;
import com.heyu.api.data.enums.RoleEnums;
import com.heyu.api.data.service.vv.VvTradeOrderConvertService;
import com.heyu.api.data.utils.R;
import com.heyu.api.listener.BaseDelayedHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


@Component("deliveredHandler")
@Slf4j
public class DeliveredHandler extends BaseDelayedHandler {

    @Autowired
    private VvPackageDao vvPackageDao;

    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;


    @Autowired
    private VvTradeOrderConvertService vvTradeOrderConvertService;


    @Override
    public R handler(String message) {
        log.info("DeliveredHandler receive message:{}", message);
        PackageDelivedDelayDTO packageDelivedDelayDTO = JSONObject.parseObject(message, PackageDelivedDelayDTO.class);


        // 更新包信息
        VvPackageEntity vvPackage = vvPackageDao.selectVvPackageById(packageDelivedDelayDTO.getPackageId());
        vvPackage.setIscheck("3");
        vvPackage.setGmtDelivered(new Date());
        vvPackage.setDeliveredBy(RoleEnums.system.getRole());
        vvPackageDao.updateVvPackageById(vvPackage);

        // 更新子单信息
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTrackNumber(vvPackage.getTrackNumber());
        for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntityList) {
            vvTradeOrderLineEntity.setDeliveredUser(RoleEnums.job.getRole());
            vvTradeOrderLineEntity.setGmtDelivered(new Date());
            vvTradeOrderLineEntity.setStatus(OrderStatusEnums.delivered.getStatus());
            vvTradeOrderLineDao.updateVvTradeOrderLineById(vvTradeOrderLineEntity);

            vvTradeOrderConvertService.addOrderLineStatusLog(vvTradeOrderLineEntity.getId(),
                    OrderStatusEnums.delivered,
                    RoleEnums.system.getRole()
            );




        }


        return R.ok();
    }
}
