package com.zhongshu.card.server.core.service.school;

import com.github.microservice.auth.security.type.AuthType;
import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.zhongshu.card.client.model.devices.DeviceBindModel;
import com.zhongshu.card.client.model.devices.DeviceBindParam;
import com.zhongshu.card.client.model.devices.DeviceBindSearch;
import com.github.microservice.net.ResultContent;
import com.github.microservice.net.ResultMessage;
import com.zhongshu.card.client.service.school.DeviceBindService;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.dao.school.AreaDao;
import com.zhongshu.card.server.core.dao.devices.DeviceBindDao;
import com.zhongshu.card.server.core.dao.devices.DeviceInfoDao;
import com.zhongshu.card.server.core.domain.devices.DeviceInfo;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.school.Area;
import com.zhongshu.card.server.core.domain.devices.DeviceBind;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.devices.DeviceInfoServiceImpl;
import com.zhongshu.card.server.core.service.org.OrganizationServiceImpl;
import com.zhongshu.card.server.core.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TRX
 * @date 2024/7/2
 */
@Slf4j
@Service
public class DeviceBindServiceImpl extends SuperService implements DeviceBindService {

    @Autowired
    DeviceBindDao deviceBindDao;

    @Autowired
    DeviceInfoDao deviceInfoDao;

    @Autowired
    OrganizationDao organizationDao;

    @Autowired
    OrganizationServiceImpl organizationService;

    @Autowired
    DeviceInfoServiceImpl deviceInfoService;

    @Autowired
    AreaDao areaDao;

    @Autowired
    AreaServiceImpl areaService;

    @Override
    public ResultContent addDeviceBind(DeviceBindParam param) {
        initDefaultUserAndOid(param);
        param.setOid(getCurrentOid());

        param.setSchoolInfoOid(param.getOid());
        Assert.hasText("deviceId不能为空", param.getDeviceId());
        Assert.hasText("schoolInfoOid不能为空", param.getSchoolInfoOid());
        Assert.hasText("shopInfoOid不能为空", param.getShopInfoOid());

        String oid = param.getOid();
        String deviceId = param.getDeviceId();
        DeviceBind deviceBind = null;

        DeviceInfo deviceInfo = deviceInfoDao.findTopByDeviceId(deviceId);
        if (ObjectUtils.isEmpty(deviceInfo)) {
            return ResultContent.buildFail(String.format("设备不存在：%s", deviceId));
        }

        // 一个设备是否可以绑定到多个学校?!
        DeviceBind temp = deviceBindDao.findTopByDeviceId(deviceId);
        if (StringUtils.isNotEmpty(param.getId())) {
            deviceBind = deviceBindDao.findTopById(param.getId());
            if (ObjectUtils.isEmpty(deviceBind)) {
                return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, param.getId()));
            }
            if (ObjectUtils.isNotEmpty(temp) && !temp.getId().equals(deviceBind.getId())) {
                return ResultContent.buildFail(String.format("设备已添加：%s", deviceId));
            }
        } else {
            deviceBind = new DeviceBind();
            if (ObjectUtils.isNotEmpty(temp) && ObjectUtils.isNotEmpty(temp.getDeviceInfo())) {
                return ResultContent.buildFail(String.format("设备已添加：%s", deviceId));
            }
            if (ObjectUtils.isNotEmpty(temp)) {
                deviceBind = temp;
            }
        }
        BeanUtils.copyProperties(param, deviceBind);
        // 设备信息
        deviceBind.setDeviceId(deviceId);
        deviceBind.setDeviceName(deviceInfo.getDeviceName());
        deviceBind.setDeviceInfo(deviceInfo);
        deviceBind.setOnLineState(deviceInfo.getOnLineState());
        deviceBind.setState(deviceInfo.getState());
        deviceBind.setProjectInfoCode(deviceInfo.getProjectInfoCode());
        deviceBind.setGateWayId(deviceInfo.getGateWayId());
        deviceBind.setDeviceType(deviceInfo.getDeviceType());

        // 所属学校
        String schoolInfoOid = param.getSchoolInfoOid();
        Organization schoolInfo = organizationDao.findTopByOid(schoolInfoOid);
        deviceBind.setSchoolInfo(schoolInfo);

        // 所属商户
        String shopInfoOid = param.getShopInfoOid();
        Organization shopInfo = organizationDao.findTopByOid(shopInfoOid);
        deviceBind.setShopInfo(shopInfo);

        // 所属区域
        String areaId = param.getAreaId();
        Area area = areaDao.findTopById(areaId);
        deviceBind.setArea(area);

        deviceBindDao.save(deviceBind);
        return ResultContent.buildSuccess();
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @Override
    public ResultContent deleteById(String id) {
        DeviceBind deviceBind = deviceBindDao.findTopById(id);
        if (ObjectUtils.isEmpty(deviceBind)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        deviceBindDao.delete(deviceBind);
        return ResultContent.buildSuccess();
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @Override
    public ResultContent<DeviceBindModel> getDetailById(String id) {
        DeviceBind deviceBind = deviceBindDao.findTopById(id);
        if (ObjectUtils.isEmpty(deviceBind)) {
            return ResultContent.buildFail(String.format(ResultMessage.DATA_NOT_EXIST, id));
        }
        DeviceBindModel model = toModel(deviceBind);
        return ResultContent.buildSuccess(model);
    }

    /**
     * 设备分页列表
     *
     * @param param
     * @param pageable
     * @return
     */
    @Override
    public ResultContent<Page<DeviceBindModel>> page(DeviceBindSearch param, Pageable pageable) {
        // 找出用户所有商户oid集合
        List<String> shopOids = new ArrayList<String>();
        // 前端传入的筛选商户oid
        if (StringUtils.isNotEmpty(param.getShopInfoOid())) {
            shopOids.add(param.getShopInfoOid());
        }
        String oid = getCurrentOid();
        Organization organization = organizationDao.findTopByOid(oid);
        if (ObjectUtils.isNotEmpty(organization)) {
            if (organization.getAuthType() == AuthType.School) {
                // 查询这个学校绑定的设备
                param.setSchoolInfoOid(oid);
            } else if (organization.getAuthType() == AuthType.BusinessMain) {
                // 如果是商户
                shopOids.add(oid);
            }
        }
        param.setShopInfoOids(shopOids);
        Page<DeviceBind> page = deviceBindDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    @Override
    public ResultContent<Page<DeviceBindModel>> busDevicePage(DeviceBindSearch param, Pageable pageable) {
        initOidSearchParam(param);
        Page<DeviceBind> page = deviceBindDao.page(pageable, param);
        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    public DeviceBindModel toModel(DeviceBind entity) {
        DeviceBindModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new DeviceBindModel();
            BeanUtils.copyProperties(entity, model);

            model.setDeviceInfo(deviceInfoService.toModel(entity.getDeviceInfo()));
            model.setSchoolInfo(organizationService.toSimpleModel(entity.getSchoolInfo()));
            model.setShopInfo(organizationService.toSimpleModel(entity.getShopInfo()));
            model.setArea(areaService.toModel(entity.getArea()));

        }
        return model;
    }

}
