package com.xydl.cac.controller;

import com.xydl.cac.entity.IcdConfigType;
import com.xydl.cac.entity.IcdConfigTypeInst;
import com.xydl.cac.entity.IcdFile;
import com.xydl.cac.entity.IcdIed;
import com.xydl.cac.entity.constants.Constants;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.iec.RealTimeDataService;
import com.xydl.cac.model.ColumnModel;
import com.xydl.cac.model.IcdAttUpdateModel;
import com.xydl.cac.model.Response;
import com.xydl.cac.model.StaticVariable;
import com.xydl.cac.repository.IcdIedRepository;
import com.xydl.cac.service.DataService;
import com.xydl.cac.service.IcdFileConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Optional;

@RestController
@Api(tags = {"IcdConfig相关接口"})
@RequestMapping("icdconfig")
@Slf4j
public class IcdConfigController extends BasicController {

    @Resource
    IcdFileConfigService configService;
    @Resource
    DataService dataService;
    @Resource
    RealTimeDataService realTimeDataService;
    @Resource
    IcdIedRepository iedRepository;

    @PostMapping("upload")
    @ApiOperation("上传客户端icd文件")
    public Response<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file != null && file.getInputStream() != null) {
            String filename = file.getOriginalFilename();
            String content = IOUtils.toString(file.getInputStream(), Charset.forName("UTF-8"));
            configService.upload(content, filename, 0);
            return Response.success("OK");
        } else {
            return Response.fail("缺少上传文件");
        }
    }

    @GetMapping("listFile")
    @ApiOperation("查询客户端icd文件列表")
    public Response<List<IcdFile>> listFile() throws Exception {
        List<IcdFile> result = configService.listFile(Constants.Client);
        for (IcdFile file : result) {
            file.setXml(null);
        }
        return Response.success(result);
    }

    @GetMapping("listIed")
    @ApiOperation("查询客户端icd文件的IED列表")
    public Response<List<IcdIed>> listIed() throws Exception {
        List<IcdIed> result = configService.listIed();
        return Response.success(result);
    }

    @GetMapping("list")
    @ApiOperation("查询全部类型列表")
    public Response<List<IcdConfigType>> list(String iedName) throws Exception {
        List<IcdConfigType> result = configService.list(iedName);
        return Response.success(result);
    }

    @GetMapping("iedList")
    @ApiOperation("查询IED名字")
    public Response<List<String>> iedList() {
        List<String> result = configService.iedList();
        return Response.success(result);
    }

    @GetMapping("testIed")
    @ApiOperation("查询IED连接状态")
    public Response<List<IcdIed>> testIed() {
        return Response.success(StaticVariable.iedTestList);
    }

    @PostMapping("update")
    @ApiOperation("更新ICD类型配置")
    public Response<String> update(@RequestBody IcdConfigType item) throws Exception {
        configService.update(item);
        return Response.success("OK");
    }

    @PostMapping("updateAtt")
    @ApiOperation("更新ICD类型属性配置")
    public Response<String> updateAtt(@RequestBody IcdAttUpdateModel model) throws Exception {
        configService.updateAtt(model);
        return Response.success("OK");
    }

    @PostMapping("delete")
    @ApiOperation("删除ICD类型配置")
    public Response<String> delete(@Validated @NotNull(message = "id不能为空!") Integer id) throws Exception {
        if (id == null) {
            throw new BusinessException("id不能为空!");
        }
        configService.delete(id);
        return Response.success("OK");
    }

    @PostMapping("deleteAtt")
    @ApiOperation("删除ICD类型属性配置")
    public Response<String> deleteAtt(@Validated @NotNull(message = "attid不能为空!") Integer attid) throws Exception {
        if (attid == null) {
            throw new BusinessException("attid不能为空!");
        }
        configService.deleteAtt(attid);
        return Response.success("OK");
    }

    @GetMapping("tableList")
    @ApiOperation("查询data表名")
    public Response<List<ColumnModel>> tableList() throws Exception {
        List<ColumnModel> result = dataService.getDataTables();
        return Response.success(result);
    }

    @GetMapping("colList")
    @ApiOperation("查询data表字段名")
    public Response<List<ColumnModel>> colList(String tableName) throws Exception {
        List<ColumnModel> result = dataService.getDataTableColumns(tableName);
        return Response.success(result);
    }

    @PostMapping("clearAll")
    @ApiOperation("清空所有配置")
    public Response<String> clearAll() throws Exception {
        configService.clearAll();
        return Response.success("OK");
    }

    @PostMapping("generateParamindex")
    @ApiOperation("生成rptparamindex表的基础数据")
    public Response<String> generateParamindex() throws Exception {
        configService.generateParamindex();
        return Response.success("OK");
    }

    @GetMapping("listParamindex")
    @ApiOperation("查询该IED下的paramindex数据")
    public Response<List<IcdConfigTypeInst>> listParamindex(@Validated @NotNull(message = "iedName不能为空!") @Param("iedName") String iedName) throws Exception {
        List<IcdConfigTypeInst> result = configService.listParamindex(iedName);
        return Response.success(result);
    }

    @PostMapping("startCollect")
    @ApiOperation("开始实时采集转发")
    public Response<String> startCollect(@Validated @NotNull(message = "iedId不能为空!") Integer iedId) throws Exception {
        if (iedId == null) {
            throw new BusinessException("iedId不能为空!");
        }
        if (RealTimeDataService.inDoing) {
            throw new BusinessException("请稍后再操作");
        }
        Optional<IcdIed> optional = iedRepository.findById(iedId);
        if (!optional.isPresent()) {
            throw new BusinessException("未找到该IED id=" + iedId);
        }
        IcdIed ied = optional.get();
        try {
            realTimeDataService.startCollect(ied);
            ied.setStart(Constants.TRUE);
            iedRepository.save(ied);
            return Response.success("OK");
        } catch (Exception ex) {
            realTimeDataService.stopCollect(ied.getId());
            ied.setStart(Constants.FALSE);
            iedRepository.save(ied);
            return Response.fail(ex.getMessage());
        }
    }

    @PostMapping("stopCollect")
    @ApiOperation("停止实时采集转发")
    public Response<String> stopCollect(@Validated @NotNull(message = "iedId不能为空!") Integer iedId) throws Exception {
        if (iedId == null) {
            throw new BusinessException("iedId不能为空!");
        }
        if (RealTimeDataService.inDoing) {
            throw new BusinessException("请稍后再操作");
        }
        Optional<IcdIed> optional = iedRepository.findById(iedId);
        if (!optional.isPresent()) {
            throw new BusinessException("未找到该IED id=" + iedId);
        }
        IcdIed ied = optional.get();
        ied.setStart(Constants.FALSE);
        iedRepository.save(ied);
        realTimeDataService.stopCollect(ied.getId());
        return Response.success("OK");
    }

}
