package com.ygtx.gxt.controller;

import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.util.StringUtil;
import com.ygtx.common.annotation.Excel;
import com.ygtx.common.core.domain.entity.SysDictData;
import com.ygtx.gxt.service.IGxtEquipmentService;
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 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.GxtFanInspectionScore;
import com.ygtx.gxt.service.IGxtFanInspectionScoreService;
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 com.ygtx.gxt.domain.vo.GxtFanInspectionScoreVo;
import com.ygtx.system.service.ISysDictDataService;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;

/**
 * 风机类型检查分值Controller
 *
 * @author ruoyi
 * @date 2025-11-06
 */
@RestController
@RequestMapping("/gxt/fanInspectionScore")
@Api(tags = "风机类型检查分值")
public class GxtFanInspectionScoreController extends BaseController
{
    @Autowired
    private IGxtFanInspectionScoreService gxtFanInspectionScoreService;

    @Autowired
    private IGxtEquipmentService gxtEquipmentService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询风机类型检查分值列表
     */
    @PreAuthorize("@ss.hasPermi('gxt:scorefaninspection:list')")
    @ApiOperation("查询风机类型检查分值列表")
    @GetMapping("/list")
    public TableDataInfo list(GxtFanInspectionScore gxtFanInspectionScore)
    {
        startPage();
        List<GxtFanInspectionScore> list = gxtFanInspectionScoreService.selectGxtFanInspectionScoreList(gxtFanInspectionScore);
        return getDataTable(list);
    }

    /**
     * 导出风机类型检查分值列表
     */
    @PreAuthorize("@ss.hasPermi('gxt:scorefaninspection:export')")
    @Log(title = "风机类型检查分值", businessType = BusinessType.EXPORT)
    @ApiOperation("导出风机类型检查分值列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, GxtFanInspectionScore gxtFanInspectionScore,
                       @RequestParam(value = "exportFields", required = false) String exportFieldsStr)
    {
        List<GxtFanInspectionScore> list = gxtFanInspectionScoreService.selectGxtFanInspectionScoreList(gxtFanInspectionScore);
        
        // 转换为VO类并填充维保类型名称
        List<GxtFanInspectionScoreVo> voList = convertToVoList(list);
        
        ExcelUtil<GxtFanInspectionScoreVo> util = new ExcelUtil<GxtFanInspectionScoreVo>(GxtFanInspectionScoreVo.class);
        if (exportFieldsStr != null && !exportFieldsStr.isEmpty()) {
            // 将字符串分割成数组
            String[] exportFields = exportFieldsStr.split(",");
            util.showColumn(exportFields);
        }
        util.exportExcel(response, voList, "风机类型检查分值数据");
    }

    /**
     * 获取风机类型检查分值导出字段列表
     */
    @GetMapping("/exportFields")
    @ApiOperation("获取风机类型检查分值导出字段列表")
    public AjaxResult getExportFields() {
        ExcelUtil<GxtFanInspectionScoreVo> util = new ExcelUtil<GxtFanInspectionScoreVo>(GxtFanInspectionScoreVo.class);
        util.init(null, "风机类型检查分值", "", Excel.Type.EXPORT);
        return success(util.getExportFields());
    }

    /**
     * 获取风机类型检查分值详细信息
     */
    @PreAuthorize("@ss.hasPermi('gxt:scorefaninspection: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 AjaxResult.success(gxtFanInspectionScoreService.selectGxtFanInspectionScoreById(id));
    }

    /**
     * 新增风机类型检查分值
     */
    @PreAuthorize("@ss.hasPermi('gxt:scorefaninspection:add')")
    @Log(title = "风机类型检查分值", businessType = BusinessType.INSERT)
    @ApiOperation("新增风机类型检查分值")
    @PostMapping
    public AjaxResult add(@RequestBody GxtFanInspectionScore gxtFanInspectionScore)
    {
        return toAjax(gxtFanInspectionScoreService.insertGxtFanInspectionScore(gxtFanInspectionScore));
    }

    /**
     * 修改风机类型检查分值
     */
    @PreAuthorize("@ss.hasPermi('gxt:scorefaninspection:edit')")
    @Log(title = "风机类型检查分值", businessType = BusinessType.UPDATE)
    @ApiOperation("修改风机类型检查分值")
    @PutMapping
    public AjaxResult edit(@RequestBody GxtFanInspectionScore gxtFanInspectionScore)
    {
        return toAjax(gxtFanInspectionScoreService.updateGxtFanInspectionScore(gxtFanInspectionScore));
    }

    /**
     * 删除风机类型检查分值
     */
    @PreAuthorize("@ss.hasPermi('gxt:scorefaninspection: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(gxtFanInspectionScoreService.deleteGxtFanInspectionScoreByIds(ids));
    }

    /**
     * 获取所有风机类型列表（去重）
     */
    @ApiOperation("获取所有风机类型列表（去重）")
    @GetMapping("/fanTypes")
    public AjaxResult listFanTypes()
    {
        List<String> list = gxtEquipmentService.selectAllModels();
        return AjaxResult.success(list);
    }

    /**
     * 根据风机类型查询检查类型列表
     */
    @ApiOperation("根据风机类型查询检查类型列表")
    @ApiImplicitParam(name = "fanType", value = "风机类型", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
    @GetMapping("/inspectionTypes/{fanType}")
    public AjaxResult listInspectionTypesByFanType(@PathVariable String fanType)
    {
        List<GxtFanInspectionScore> list = gxtFanInspectionScoreService.selectGxtFanInspectionScoreByFanType(fanType);
        return AjaxResult.success(list);
    }
    
    /**
     * 将实体类列表转换为VO类列表，并填充维保类型名称
     */
    private List<GxtFanInspectionScoreVo> convertToVoList(List<GxtFanInspectionScore> list) {
        List<GxtFanInspectionScoreVo> voList = new ArrayList<>();
        
        for (GxtFanInspectionScore entity : list) {
            GxtFanInspectionScoreVo vo = new GxtFanInspectionScoreVo();
            
            // 手动复制属性
            vo.setId(entity.getId());
            vo.setFanType(entity.getFanType());
            vo.setScore(entity.getScore());
            vo.setRemark(entity.getRemark());
            vo.setCreateBy(entity.getCreateBy());
            vo.setCreateTime(entity.getCreateTime());
            vo.setUpdateBy(entity.getUpdateBy());
            vo.setUpdateTime(entity.getUpdateTime());
            
            // 根据inspectionTypeId获取维保类型名称
            if (entity.getInspectionTypeId() != null) {
                String inspectionTypeName = sysDictDataService.selectDictLabel("gxt_inspection_type", entity.getInspectionTypeId().toString());
                vo.setInspectionTypeName(inspectionTypeName != null ? inspectionTypeName : "");
            }
            
            voList.add(vo);
        }
        
        return voList;
    }
    
    /**
     * 导入风机类型检查分值数据
     */
    @PreAuthorize("@ss.hasPermi('gxt:scorefaninspection:import')")
    @Log(title = "风机类型检查分值", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, @RequestParam(defaultValue = "false") boolean updateSupport) throws Exception
    {
        ExcelUtil<GxtFanInspectionScore> util = new ExcelUtil<GxtFanInspectionScore>(GxtFanInspectionScore.class);
        List<GxtFanInspectionScore> fanInspectionScoreList = util.importExcel(file.getInputStream());
        if (!fanInspectionScoreList.isEmpty()) {
            SysDictData dictData = new SysDictData();
            dictData.setDictType("gxt_inspection_type");
            dictData.setStatus("0");
            List<SysDictData> dataList = sysDictDataService.selectDictDataList(dictData);
            if (dataList.isEmpty()) {
                return error("数据库风机类型为空");
            }
            for (GxtFanInspectionScore score:fanInspectionScoreList) {
                if (score.getScore().compareTo(BigDecimal.ZERO)<=0) {
                    return error("分值不为正数");
                }
                score.setStatus(0);
                String fanName = score.getInspectionTypeName();
                if (StringUtil.isNotEmpty(fanName)) {
                    for (SysDictData data:dataList) {
                        if (data.getDictLabel().equals(fanName)) {
                            score.setInspectionTypeId(Integer.valueOf(data.getDictValue()));
                            break;
                        }
                    }
                }
            }
        }
        String operName = getUsername();
        String message = gxtFanInspectionScoreService.importFanInspectionScoreList(fanInspectionScoreList, updateSupport, operName);
        return success(message);
    }
    
    /**
     * 下载风机类型检查分值导入模板
     */
    @PreAuthorize("@ss.hasPermi('gxt:scorefaninspection:import')")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<GxtFanInspectionScoreVo> util = new ExcelUtil<GxtFanInspectionScoreVo>(GxtFanInspectionScoreVo.class);
        util.importTemplateExcel(response, "风机类型检查分值数据");
    }
}