package cn.iocoder.yudao.module.pms.service.yanfan.thingsmodel;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.product.vo.ImportThingsModelInput;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.thingsmodel.vo.IotYfThingsModelPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.thingsmodel.vo.IotYfThingsModelSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.things.IotYfThingsModelDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.thingsmodeltemplate.IotYfThingsModelTemplateDO;
import cn.iocoder.yudao.module.pms.dal.mysql.yanfan.things.IotYfThingsModelMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.yanfan.thingsmodel.IotYfThingsModelTemplateMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * yf物模型 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class IotYfThingsModelServiceImpl implements IotYfThingsModelService {

    @Resource
    private IotYfThingsModelMapper iotYfThingsModelMapper;
    @Autowired
    private IotYfThingsModelTemplateMapper iotYfThingsModelTemplateMapper;

    @Override
    public Long createIotThingsModel(IotYfThingsModelSaveReqVO createReqVO) {
        // 插入
        IotYfThingsModelDO iotThingsModel = BeanUtils.toBean(createReqVO, IotYfThingsModelDO.class);
        iotYfThingsModelMapper.insert(iotThingsModel);
        // 返回
        return iotThingsModel.getModelId();
    }

    @Override
    public void updateIotThingsModel(IotYfThingsModelSaveReqVO updateReqVO) {
        // 校验存在
        validateIotThingsModelExists(updateReqVO.getModelId());
        // 更新
        IotYfThingsModelDO updateObj = BeanUtils.toBean(updateReqVO, IotYfThingsModelDO.class);
        iotYfThingsModelMapper.updateById(updateObj);
    }

    @Override
    public void deleteIotThingsModel(Long id) {
        // 校验存在
        validateIotThingsModelExists(id);
        // 删除
        iotYfThingsModelMapper.deleteById(id);
    }

    private void validateIotThingsModelExists(Long id) {
        if (iotYfThingsModelMapper.selectById(id) == null) {
            throw exception(new ErrorCode(222,"不存在物模型"));
        }
    }

    @Override
    public IotYfThingsModelDO getIotThingsModel(Long id) {
        return iotYfThingsModelMapper.selectById(id);
    }

    @Override
    public PageResult<IotYfThingsModelDO> getIotThingsModelPage(IotYfThingsModelPageReqVO pageReqVO) {
        return iotYfThingsModelMapper.selectPage(pageReqVO);
    }

    @Override
    public int importByTemplateIds(ImportThingsModelInput input) {
        IotYfThingsModelPageReqVO inputParameter = new IotYfThingsModelPageReqVO();
        inputParameter.setLanguage("zh-CN");
        inputParameter.setProductId(input.getProductId());
        List<IotYfThingsModelDO> dbList = iotYfThingsModelMapper.selectThingsModelList(inputParameter);

        //SysUser user = getLoginUser().getUser();
        // 根据ID集合获取通用物模型列表
        List<IotYfThingsModelTemplateDO> templateList = iotYfThingsModelTemplateMapper.selectThingsModelTemplateByTemplateIds(input.getTemplateIds(), "zh-CN");
        //转换为产品物模型，并批量插入
        List<IotYfThingsModelDO> list = new ArrayList<>();
        int repeatCount = 0;
        for (IotYfThingsModelTemplateDO template : templateList) {
            IotYfThingsModelDO thingsModel = new IotYfThingsModelDO();
            org.springframework.beans.BeanUtils.copyProperties(template, thingsModel);
            thingsModel.setTenantId(1L);
//            thingsModel.setTenantName(user.getUserName());
            thingsModel.setCreateTime(LocalDateTime.now());
            thingsModel.setProductId(input.getProductId());
            thingsModel.setProductName(input.getProductName());
            thingsModel.setModelId(template.getTemplateId());
            thingsModel.setModelName(template.getTemplateName());
            thingsModel.setIsReadonly(template.getIsReadonly());
            thingsModel.setIsMonitor(template.getIsMonitor());
            thingsModel.setIsChart(template.getIsChart());
            thingsModel.setIsHistory(template.getIsHistory());
            thingsModel.setModelOrder(template.getModelOrder());
            thingsModel.setParseType(template.getParseType());
            //兼容modbsu
            if (StringUtils.isNotEmpty(template.getTempSlaveId()) && template.getTempSlaveId().contains("#")) {
                thingsModel.setTempSlaveId(Integer.parseInt(template.getTempSlaveId().split("#")[1]));
            }
            Boolean isRepeat = dbList.stream().anyMatch(x -> x.getIdentifier().equals(thingsModel.getIdentifier()));
            if (isRepeat) {
                repeatCount = repeatCount + 1;
            } else {
                list.add(thingsModel);
            }
        }
        //todo
//        if (list.size() > 0) {
//            Boolean result = iotYfThingsModelMapper.insertBatch(list);
//            if (result) {
//                // 更新场景管理变量
//                List<SceneModelDevice> sceneModelDeviceList = sceneModelDeviceMapper.listDeviceByProductId(input.getProductId());
//                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(sceneModelDeviceList)) {
//                    List<SceneModelData> sceneModelDataList = new ArrayList<>();
//                    for (ThingsModel thingsModel : list) {
//                        List<ThingsModelDTO> thingsModelDTOList = this.changeObjectOrArray(thingsModel);
//                        for (SceneModelDevice sceneModelDevice : sceneModelDeviceList) {
//                            sceneModelDataList.addAll(getSceneModelData(sceneModelDevice, thingsModelDTOList));
//                        }
//                    }
//                    sceneModelDataMapper.insertBatchSceneModelData(sceneModelDataList);
//                }
//            }
//            //更新redis缓存
//            itslCache.setCacheThingsModelByProductId(input.getProductId());
//        }
        return repeatCount;
    }

}
