package com.yihu.jw.base.service.device;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.base.dao.device.DeviceDetailDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * Created by Bing on 2021/9/23.
 */
@Service
public class DmDeviceService extends BaseJpaService<Device, DeviceDao> {

    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private ObjectMapper objectMapper;

    public static void findDmDeviceDict(String deviceName, String deviceModel) {
    }

    public JSONObject saveDmDevice(String json) throws IOException {
        JSONObject result = new JSONObject();
        Device device = objectMapper.readValue(json,Device.class);
        Integer deviceType = device.getDeviceType();
        String categoryCode = device.getCategoryCode();
        String name = device.getName();
        String model = device.getCategoryCode();
        String brands = device.getBrands();
        String photo =device.getPhoto();
        String isMultiUser = device.getIsMultiUser();
        if (null==deviceType||StringUtils.isBlank(categoryCode)||StringUtils.isBlank(name)||StringUtils.isBlank(model)||
                StringUtils.isBlank(brands)||StringUtils.isBlank(photo)||StringUtils.isBlank(isMultiUser)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"数据数据错误,必填字段为空");
            return result;
        }

        //判断型号是否重复
        Device deviceTmp = deviceDao.findByModel(device.getModel());
        if (null!=deviceTmp){
            if (null==device.getId()){
                result.put(ResponseContant.resultFlag,ResponseContant.fail);
                result.put(ResponseContant.resultMsg,"设备型号已存在");
                return result;
            }else if (deviceTmp.getId().longValue()!=device.getId().longValue()){//
                result.put(ResponseContant.resultFlag,ResponseContant.fail);
                result.put(ResponseContant.resultMsg,"设备型号已存在");
                return result;
            }
        }
        if (null==device.getId()){
            device.setDel("1");
        }
        deviceDao.save(device);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,"success");
        return result;
    }
}
