package com.ruoyi.bst.fault.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.bst.device.domain.DeviceVO;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.bst.fault.domain.Fault;
import com.ruoyi.bst.fault.domain.FaultVO;
import com.ruoyi.bst.fault.domain.enums.FaultStatus;
import com.ruoyi.bst.fault.service.FaultConverter;
import com.ruoyi.bst.fault.service.FaultService;
import com.ruoyi.bst.order.domain.dto.OrderChangeDeviceDTO;
import com.ruoyi.bst.order.service.OrderService;
import com.ruoyi.bst.orderDevice.domain.OrderDeviceVO;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.system.user.service.UserService;

@Service
public class FaultConverterImpl implements FaultConverter {

    @Autowired
    private FaultService faultService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Override
    public Fault toPo(FaultVO fault) {
        DeviceVO device = deviceService.selectDeviceBySn(fault.getVehicleCode());
        ServiceUtil.assertion(device == null, "设备不存在");

        Fault po = new Fault();
        po.setFaultSite(fault.getFaultSite());
        po.setVehicleCode(fault.getVehicleCode());
        po.setPicture(fault.getPicture());
        po.setFaultDetail(fault.getFaultDetail());
        po.setCreateBy(fault.getCreateBy());
        po.setAppealStatus(FaultStatus.PENDING.getCode());
        po.setCreateTime(DateUtils.getNowDate());
        po.setUserName(fault.getCreateBy());
        po.setUserId(fault.getUserId());
        po.setAreaId(device.getAreaId());

        po.setStoreId(device.getMchId());
        if (device.getOrderId() != null && fault.getOrderId().equals(device.getOrderId())) {
            po.setOrderId(device.getOrderId());
        }

        String vehicleNum = device.getVehicleNum();
        if (vehicleNum != null) {
            po.setVehicleNum(vehicleNum);
        }
        return po;
    }

    @Override
    public boolean canEdit(Long faultId) {
        return false;
    }

    @Override
    public Fault toPo(OrderChangeDeviceDTO dto, OrderDeviceVO orderDevice) {
        if (dto == null) {
            return null;
        }
        Fault po = new Fault();
        po.setUserId(dto.getUserId());
        po.setUserName(dto.getUserName());
        po.setFaultDetail(dto.getFaultDetail());
        po.setPicture(dto.getFaultPicture());
        po.setAppealStatus(FaultStatus.PENDING.getCode());
        if (orderDevice != null) {
            po.setOrderId(orderDevice.getOrderId());
            po.setVehicleCode(orderDevice.getDeviceSn());
            po.setVehicleNum(orderDevice.getDeviceVehicleNum());
        }
        return po;
    }
}
