package iot.lidee.controller.deviceConfig;

import iot.lidee.common.annotation.Log;
import iot.lidee.common.core.controller.BaseController;
import iot.lidee.common.core.domain.AjaxResult;
import iot.lidee.common.core.page.TableDataInfo;
import iot.lidee.common.enums.BusinessType;
import iot.lidee.common.utils.MessageUtils;
import iot.lidee.common.utils.StringUtils;
import iot.lidee.common.utils.poi.ExcelUtil;
import iot.lidee.iot.cache.ITSLCache;
import iot.lidee.iot.domain.ThingsModel;
import iot.lidee.iot.model.ImportThingsModelInput;
import iot.lidee.iot.model.ThingsModelPerm;
import iot.lidee.iot.model.modbus.ModbusAndThingsVO;
import iot.lidee.iot.service.IThingsModelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.util.List;

/**
 * 物模型Controller
 *
 * @author kerwincui
 * @date 2021-12-16
 */
@RestController
@RequestMapping("/iot/model")
@Api(tags="产品物模型")
public class ThingsModelController extends BaseController
{
    @Autowired
    private IThingsModelService thingsModelService;
    @Resource
    private ITSLCache itslCache;

    /**
     * 查询物模型列表
     */
    @PreAuthorize("@ss.hasPermi('iot:model:list')")
    @GetMapping("/list")
    @ApiOperation("产品物模型分页列表")
    public TableDataInfo list(ThingsModel thingsModel)
    {
        startPage();
        List<ThingsModel> list = thingsModelService.selectThingsModelList(thingsModel);
        return getDataTable(list);
    }

    /**
     * 查询物模型对应设备分享权限
     */
    @PreAuthorize("@ss.hasPermi('iot:device:list')")
    @GetMapping("/permList/{productId}")
    @ApiOperation("查询物模型对应设备分享权限")
    public AjaxResult permList(@PathVariable Long productId)
    {
        List<ThingsModelPerm> list = thingsModelService.selectThingsModelPermList(productId);
        return AjaxResult.success(list);
    }

    /**
     * 获取物模型详细信息
     */
    @PreAuthorize("@ss.hasPermi('iot:model:query')")
    @GetMapping(value = "/{modelId}")
    @ApiOperation("获取产品物模型详情")
    public AjaxResult getInfo(@PathVariable("modelId") Long modelId)
    {
        return AjaxResult.success(thingsModelService.selectThingsModelByModelId(modelId));
    }

    /**
     * 新增物模型
     */
    @PreAuthorize("@ss.hasPermi('iot:model:add')")
    @Log(title = "物模型", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("添加产品物模型")
    public AjaxResult add(@RequestBody ThingsModel thingsModel)
    {
        int result=thingsModelService.insertThingsModel(thingsModel);
        if(result==1){
            return AjaxResult.success();
        }else if(result==2){
            return AjaxResult.error(MessageUtils.message("things.model.identifier.repeat"));
        }else{
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPermi('iot:model:import')")
    @Log(title = "导入物模型",businessType = BusinessType.INSERT)
    @PostMapping("/import")
    @ApiOperation("导入通用物模型")
    public AjaxResult ImportByTemplateIds(@RequestBody ImportThingsModelInput input){
        int repeatCount=thingsModelService.importByTemplateIds(input);
        if(repeatCount==0){
            return AjaxResult.success(MessageUtils.message("import.success"));
        }else{
            return AjaxResult.success(StringUtils.format(MessageUtils.message("things.model.import.failed.identifier.repeat"), repeatCount));
        }
    }

    /**
     * 修改物模型
     */
    @PreAuthorize("@ss.hasPermi('iot:model:edit')")
    @Log(title = "物模型", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改产品物模型")
    public AjaxResult edit(@RequestBody ThingsModel thingsModel)
    {
        int result=thingsModelService.updateThingsModel(thingsModel);
        if(result==1){
            return AjaxResult.success();
        }else if(result==2){
            return AjaxResult.error(MessageUtils.message("things.model.identifier.repeat"));
        }else{
            return AjaxResult.error();
        }
    }

    /**
     * 删除物模型
     */
    @PreAuthorize("@ss.hasPermi('iot:model:remove')")
    @Log(title = "物模型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{modelIds}")
    @ApiOperation("批量删除产品物模型")
    public AjaxResult remove(@PathVariable Long[] modelIds)
    {
        return toAjax(thingsModelService.deleteThingsModelByModelIds(modelIds));
    }

    /**
     * 获取缓存的JSON物模型
     */
    @PreAuthorize("@ss.hasPermi('iot:model:query')")
    @GetMapping(value = "/cache/{productId}")
    @ApiOperation("获取缓存的JSON物模型")
    public AjaxResult getCacheThingsModelByProductId(@PathVariable("productId") Long productId)
    {
        return AjaxResult.success(MessageUtils.message("operate.success"),itslCache.getCacheThingsModelByProductId(productId));
    }

    @ApiOperation(value = "物模型导入模板")
    @PostMapping("/temp")
    public void temp(HttpServletResponse response){
        ExcelUtil<ThingsModel> excelUtil = new ExcelUtil<>(ThingsModel.class);
        excelUtil.importTemplateExcel(response,"采集点");
    }


    /**
     * 导入采集点
     */
    @PreAuthorize("@ss.hasPermi('iot:point:import')")
    @ApiOperation(value = "采集点导入")
    @PostMapping(value = "/importData")
    public AjaxResult importData(MultipartFile file,Long productId) throws Exception{
        ExcelUtil<ThingsModel> excelUtil = new ExcelUtil<>(ThingsModel.class);
        byte[] bytes = file.getBytes();

        Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(bytes));
        Sheet sheet = wb.getSheetAt(0);


        List<ThingsModel> list = excelUtil.importExcelCopy(new ByteArrayInputStream(bytes));
        if (!CollectionUtils.isEmpty( list)){
            this.parseList(list);
        }
        String result = thingsModelService.importData(list, productId,sheet.getSheetName());
        return AjaxResult.success(result);
    }

    private void parseList(List<ThingsModel> list) {
        if (list == null || list.isEmpty()) {
            return;
        }

        for (ThingsModel thingsModel : list) {
            String modelName = thingsModel.getModelName();
            if (StringUtils.isEmpty(modelName)) {
                thingsModel.setType(1);
                continue;
            }

            thingsModel.setType(classifyModelType(modelName));
        }

    }

    /**
     * 根据物模型名称分类类型
     * @param modelName 物模型名称
     * @return 1-属性, 2-功能, 3-事件
     */
    private Integer classifyModelType(String modelName) {
        // 事件类型关键词
        if (containsAny(modelName, "报警", "异常", "故障", "不能", "联锁", "过长", "超限", "超限度")) {
            return 3;
        }

        // 特殊处理：包含"高"或"低"但不包含其他功能关键词的归为事件
        if ((modelName.contains("高") || modelName.contains("低"))
                && !containsAny(modelName, "阀", "电机", "开门", "关门", "启动", "停止")) {
            return 3;
        }

        if (containsAny(modelName, "阀", "电机", "开门", "关门", "启动", "停止", "复位", "引入",
                "加压", "冷却", "排水", "抽气", "充气")) {
            return 2;
        }

        // 默认为属性类型
        return 1;
    }

    /**
     * 判断字符串是否包含任意一个关键词
     * @param str 待检查的字符串
     * @param keywords 关键词数组
     * @return 是否包含任一关键词
     */
    private boolean containsAny(String str, String... keywords) {
        if (str == null || keywords == null) {
            return false;
        }
        for (String keyword : keywords) {
            if (str.contains(keyword)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取modbus配置可选择物模型
     */
    @PreAuthorize("@ss.hasPermi('iot:model:list')")
    @GetMapping("/listModbus")
    @ApiOperation("获取modbus配置可选择物模型")
    public TableDataInfo listModbus(Long productId)
    {
        startPage();
        List<ModbusAndThingsVO> list = thingsModelService.getModbusConfigUnSelectThingsModel(productId);
        return getDataTable(list);
    }


    /**
     * 根据设备获取可读写物模型
     */
    @PreAuthorize("@ss.hasPermi('iot:model:list')")
    @GetMapping("/write")
    @ApiOperation("根据设备获取可读写物模型")
    public TableDataInfo write(Long deviceId)
    {
        startPage();
        List<ThingsModel> thingsModelList = thingsModelService.selectThingsModelBySerialNumber(deviceId);
        return getDataTable(thingsModelList);
    }

}
