package com.ygtx.gxt.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.system.service.ISysDeptService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ygtx.common.annotation.Log;
import com.ygtx.common.core.controller.BaseController;
import com.ygtx.common.core.domain.AjaxResult;
import com.ygtx.common.enums.BusinessType;
import com.ygtx.gxt.domain.GxtFaultCodes;
import com.ygtx.gxt.service.IGxtFaultCodesService;
import com.ygtx.common.utils.poi.ExcelUtil;
import com.ygtx.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

/**
 * 故障代码管理Controller
 * 
 * @author ouyj
 * @date 2025-10-29
 */
@RestController
@RequestMapping("/gxt/faultCodes")
@Api(tags = "故障代码管理")
public class GxtFaultCodesController extends BaseController
{
    @Autowired
    private IGxtFaultCodesService gxtFaultCodesService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 查询故障代码管理列表
     */
    @ApiOperation("查询故障代码管理列表")
    @GetMapping("/list")
    public TableDataInfo list(GxtFaultCodes gxtFaultCodes)
    {
        startPage();
        List<GxtFaultCodes> list = gxtFaultCodesService.selectGxtFaultCodesList(gxtFaultCodes);
        return getDataTable(list);
    }

    /**
     * 导出故障代码管理列表
     */
    @PreAuthorize("@ss.hasPermi('gxt:faultCodes:export')")
    @Log(title = "故障代码管理", businessType = BusinessType.EXPORT)
    @ApiOperation("导出故障代码管理列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, GxtFaultCodes gxtFaultCodes,
                       @RequestParam(value = "exportFields", required = false) String exportFieldsStr) {
        List<GxtFaultCodes> list = gxtFaultCodesService.selectGxtFaultCodesList(gxtFaultCodes);
        ExcelUtil<GxtFaultCodes> util = new ExcelUtil<GxtFaultCodes>(GxtFaultCodes.class);
        if (exportFieldsStr != null && !exportFieldsStr.isEmpty()) {
            // 将字符串分割成数组
            String[] exportFields = exportFieldsStr.split(",");
            util.showColumn(exportFields);
        }
        util.exportExcel(response, list, "故障代码管理数据");
    }

    /**
     * 获取故障代码管理导出字段列表
     */ 
    @GetMapping("/exportFields")
    @ApiOperation("获取故障代码管理导出字段列表")
    public AjaxResult getExportFields() {
        ExcelUtil<GxtFaultCodes> util = new ExcelUtil<GxtFaultCodes>(GxtFaultCodes.class);
        return success(util.getExportFields());
    }

    /**
     * 获取故障代码管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('gxt:faultCodes:query')")
    @ApiOperation("获取故障代码管理详细信息")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(gxtFaultCodesService.selectGxtFaultCodesById(id));
    }

    /**
     * 新增故障代码管理
     */
    @PreAuthorize("@ss.hasPermi('gxt:faultCodes:add')")
    @Log(title = "故障代码管理", businessType = BusinessType.INSERT)
    @ApiOperation("新增故障代码管理")
    @PostMapping
    public AjaxResult add(@RequestBody GxtFaultCodes gxtFaultCodes)
    {
        if (!gxtFaultCodesService.checkGxtFaultCodesByStationModelFaultCode(gxtFaultCodes)) {
            return error("新增失败，已存在相同的场站、机型、故障代码组合");
        }
        if (!gxtFaultCodesService.checkGxtFaultCodesByStationModelBarcode(gxtFaultCodes)) {
            return error("新增失败，已存在相同的场站、机型、故障条文组合");
        }
        return toAjax(gxtFaultCodesService.insertGxtFaultCodes(gxtFaultCodes));
    }

    /**
     * 修改故障代码管理
     */
    @PreAuthorize("@ss.hasPermi('gxt:faultCodes:edit')")
    @Log(title = "故障代码管理", businessType = BusinessType.UPDATE)
    @ApiOperation("修改故障代码管理")
    @PutMapping
    public AjaxResult edit(@RequestBody GxtFaultCodes gxtFaultCodes)
    {
        if (!gxtFaultCodesService.checkGxtFaultCodesByStationModelFaultCode(gxtFaultCodes)) {
            return error("修改失败，已存在相同的场站、机型、故障代码组合");
        }
        if (!gxtFaultCodesService.checkGxtFaultCodesByStationModelBarcode(gxtFaultCodes)) {
            return error("修改失败，已存在相同的场站、机型、故障条文组合");
        }
        return toAjax(gxtFaultCodesService.updateGxtFaultCodes(gxtFaultCodes));
    }

    /**
     * 删除故障代码管理
     */
    @PreAuthorize("@ss.hasPermi('gxt:faultCodes:remove')")
    @Log(title = "故障代码管理", businessType = BusinessType.DELETE)
    @ApiOperation("删除故障代码管理")
    @ApiImplicitParam(name = "ids", value = "主键ID数组", required = true, dataType = "Long[]", paramType = "path", dataTypeClass = Long[].class)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(gxtFaultCodesService.deleteGxtFaultCodesByIds(ids));
    }

    /**
     * 导入故障代码管理数据
     */
    @PreAuthorize("@ss.hasPermi('gxt:faultCodes:import')")
    @Log(title = "故障代码管理", businessType = BusinessType.IMPORT)
    @ApiOperation("导入故障代码管理数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "file", value = "上传文件", required = true, dataType = "MultipartFile", paramType = "form", dataTypeClass = MultipartFile.class),
        @ApiImplicitParam(name = "updateSupport", value = "是否支持更新", required = true, dataType = "Boolean", paramType = "query", dataTypeClass = Boolean.class)
    })
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<GxtFaultCodes> util = new ExcelUtil<GxtFaultCodes>(GxtFaultCodes.class);
        List<GxtFaultCodes> faultCodesList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = gxtFaultCodesService.importGxtFaultCodes(faultCodesList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载故障代码管理导入模板
     */
    @ApiOperation("下载故障代码管理导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        /*ExcelUtil<GxtFaultCodes> util = new ExcelUtil<GxtFaultCodes>(GxtFaultCodes.class);
        util.importTemplateExcel(response, "故障代码管理数据");*/
        try {
            String filename = URLEncoder.encode("faultCodes.xlsx", StandardCharsets.UTF_8.toString());
            Resource resource = resourceLoader.getResource("classpath:faultCodes.xlsx");
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            try (ServletOutputStream out = response.getOutputStream();
                 InputStream stream = resource.getInputStream()) {
                byte buff[] = new byte[1024];
                int length;
                // 从文件输入流读取数据，并写入响应输出流中，实现文件下载
                while ((length = stream.read(buff)) > 0) {
                    out.write(buff, 0, length);
                }
                out.flush(); // 刷新输出流，确保所有数据都被发送到客户端
            }
        } catch (IOException e) {
            e.printStackTrace(); // 输出异常信息，便于排查问题
        }
    }

    /**
     * 查询场站列表（部门级别为3或4的）
     */
    @ApiOperation("查询场站列表（部门级别为3或4的）")
    @GetMapping("/stations")
    public AjaxResult listStations()
    {
        SysDept dept = new SysDept();
        dept.setStatus("0"); // 只查询启用的部门
        List<SysDept> deptList = deptService.selectDeptList(dept);
        // 筛选部门级别为3或4的部门作为场站
        List<SysDept> stationList = deptList.stream()
                .filter(d -> "4".equals(d.getLevel()))
                .collect(Collectors.toList());
        return AjaxResult.success(stationList);
    }

    /**
     * 根据场站ID查询机型列表（从设备管理中获取）
     */
    @ApiOperation("根据场站ID查询机型列表（从设备管理中获取）")
    @ApiImplicitParam(name = "stationId", value = "场站ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping("/models/{stationId}")
    public AjaxResult listModelsByStation(@PathVariable("stationId") Long stationId)
    {
        List<String> list = gxtFaultCodesService.selectModelListByStationId(stationId);
        return AjaxResult.success(list);
    }
}