package com.ho.business.controller;

import com.ho.business.entity.DeviceTypeConfig;
import com.ho.business.entity.ModelDevice;
import com.ho.business.entity.ModelDeviceCol;
import com.ho.business.entity.ModelType;
import com.ho.business.service.DeviceTypeConfigService;
import com.ho.business.service.ModelDeviceColService;
import com.ho.business.vo.req.device.DeviceTypeQuery;
import com.ho.business.vo.req.deviceModel.*;
import com.ho.business.vo.resp.deviceModel.DeviceModelRespVo;
import com.ho.business.vo.resp.deviceModel.ModelDeviceColRespVo;
import com.ho.common.tools.annotation.HzPermission;
import com.ho.common.tools.annotation.LogAnnotation;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.constant.PermissionConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gyan
 * @desc: 模型设备字段关联表
 * @DateTime: 2023/3/7 16:44
 */
@RestController
@RequestMapping(ContextConstant.BUSINESS + "ModelAndDevice")
@Api(tags = "业务模块-设备_模型设备字段关联管理")
public class ModelDeviceColController {
    @Autowired
    ModelDeviceColService modelDeviceColService;

    @Autowired
    DeviceTypeConfigService deviceTypeConfigService;

    @Autowired
    RedisService redisService;

    @Autowired
    RedissonClient redissonClient;


    @PostMapping("add")
    @ApiOperation(value = "新增设备模型关联字段接口")
    @LogAnnotation(title = "设备模型关联管理", action = "新增设备模型关联字段信息")
    @HzPermission(PermissionConstant.SYS_EMSDEVICE_ASSOCIATED)
    public DataResult<ModelDeviceCol> add(@RequestBody @Valid ModelDeviceColAddVo vo) {
        //增加分布式锁
        //定义锁
        RLock lock = null;
        try {
            lock = redissonClient.getLock(RedisKeyConstant.LOCK_KEY_MODEL_EQUIPMENT_ASSOCIATION);
            //获取锁,没有获取到锁的阻塞在lock.lock() 这行
            lock.lock();
            modelDeviceColService.add(vo);
        } finally {
            if (lock != null && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return DataResult.success();
    }

    @PostMapping("update")
    @ApiOperation(value = "修改设备模型关联字段接口")
    @LogAnnotation(title = "设备模型关联管理", action = "修改设备模型关联字段信息")
    public DataResult<ModelDeviceCol> update(@RequestBody @Valid ModelDeviceColAddVo vo) {
        //modelDeviceColService.update(vo);
        return DataResult.success();
    }

    @PostMapping("deleteBatch")
    @ApiOperation(value = "批量删除设备模型关联字段")
    @LogAnnotation(title = "设备模型关联管理", action = "批量删除设备模型关联字段")
    @HzPermission(PermissionConstant.SYS_MODELDEVICE_DELETE)
    public DataResult deleteBatch(@RequestBody @Valid DeviceModelDeleteReqVo vo) {
        modelDeviceColService.deleteBatch(vo);
        return DataResult.success();

    }

    @PostMapping("/page")
    @ApiOperation(value = "分页查询设备模型关联字段接口")
    //deviceType
    public DataResult<PageResult<ModelDeviceColRespVo>> page(@RequestBody DeviceColSelectReqVo vo) {
        List<ModelDeviceColRespVo> modelDeviceColList = modelDeviceColService.page(vo);
        /*//java内存分页
        PageResult pageResult = new PageResult<>();
        if (!modelDeviceColList.isEmpty()) {
            List list = PageUtils.dealList(modelDeviceColList, vo.getPageNum(), vo.getPageSize());
            pageResult = PageUtils.getPageResult(new PageInfo<>(list));
            pageResult.setTotalRows(modelDeviceColList.size());
            pageResult.setTotalPages(modelDeviceColList.size() / vo.getPageSize() + 1);
        }else{
            pageResult = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }*/
        return DataResult.success(modelDeviceColList);
    }

    @PostMapping("/selectDevice")
    @ApiOperation(value = "查询未被使用的设备字段")
    public DataResult<List<DeviceModelRespVo>> selectDevice(@RequestBody DeviceColSelectReqVo vo) {
        List<DeviceModelRespVo> modelDeviceColList = modelDeviceColService.selectDevice(vo);
        return DataResult.success(modelDeviceColList);
    }

    @PostMapping("/selectModel")
    @ApiOperation(value = "查询当前设备未被使用的模型字段")
    //deviceType
    public DataResult<List<DeviceModelRespVo>> selectModel(@RequestBody ModelDeviceColAddReqVo vo) {
        List<DeviceModelRespVo> modelDeviceColList = modelDeviceColService.selectModel(vo.getDeviceType(), vo.getModelType());
        return DataResult.success(modelDeviceColList);
    }

    //查询modelType类型
    @PostMapping("/getModelType")
    @ApiOperation(value = "查询模型类型")
    //deviceType
    public DataResult<List<ModelType>> getModelType() {
        List<ModelType> modelTypeList = modelDeviceColService.getModelType();
        return DataResult.success(modelTypeList);
    }

    //查询deviceType类型
    @PostMapping("/getDeviceType")
    @ApiOperation(value = "查询设备类型")
    //deviceType
    public DataResult<List<ModelDevice>> getDeviceType(@RequestBody DeviceColSelectReqVo vo, HttpServletRequest request) {
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser user = redisService.getSimpleUserByToken(token);
        List<ModelDevice> modelTypeList = modelDeviceColService.getDeviceType(vo.getType());
        List<String> deviceTypes = modelTypeList.stream().map(ModelDevice::getDeviceType)
                .collect(Collectors.toList());
        if(deviceTypes==null ||deviceTypes.isEmpty()){
            return DataResult.success(new ArrayList<>());
        }
        //改为从设备类型配置表中查询
        DeviceTypeQuery deviceTypeQuery = new DeviceTypeQuery();
        deviceTypeQuery.setGroupId(user.getGroupId());
        deviceTypeQuery.setDeviceTypeList(deviceTypes);
        List<DeviceTypeConfig> deviceTypeConfigs = deviceTypeConfigService.queryListByCondition(deviceTypeQuery);
        for (ModelDevice modelDevice : modelTypeList) {
            for (DeviceTypeConfig deviceType : deviceTypeConfigs) {
                if(modelDevice.getDeviceType().equals(deviceType.getDeviceType())){
                    modelDevice.setDeviceTypeName(deviceType.getName());
                }
            }
        }
        return DataResult.success(modelTypeList);
    }


    //一键同步功能
    @PostMapping("/getSynchronousM")
    @ApiOperation(value = "一键同步设备关联模型功能")
    @LogAnnotation(title = "设备模型关联管理", action = "一键同步设备关联模型功能")
    //deviceType
    public DataResult getSynchronousM(@RequestBody SynchronousReqVo vo) {
        modelDeviceColService.synchronousAdd(vo);
        return DataResult.success();
    }

    @PostMapping("/getSynchronousMNew")
    @ApiOperation(value = "一键同步设备关联模型功能（不区分设备）")
    @LogAnnotation(title = "设备模型关联管理", action = "一键同步设备关联模型功能（不区分设备）")
    //deviceType
    public DataResult getSynchronousMNew(@RequestBody SynchronousReqVo vo) {
        if (vo.getStationId() == null) {
            //请选择同步的设备类型
            throw new BusinessException(BaseResponseCode.PLEASE_CHECK_SRC_STATION);
        }
        if (vo.getModelStationId() == null) {
            //请选择同步的模型类型
            throw new BusinessException(BaseResponseCode.PLEASE_CHECK_MODEL_STATION);
        }
        modelDeviceColService.synchronousAddNew(vo);
        return DataResult.success();
    }
}
