package com.ruoyi.web.controller.app;

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

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.jsonUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
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.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.app.domain.InspectionItem;
import com.ruoyi.app.service.IInspectionItemService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 检查项目Controller
 * 
 * @author coede
 * @date 2025-03-19
 */
@RestController
@RequestMapping("/app/inspectionItem")
public class InspectionItemController extends BaseController
{
    @Autowired
    private IInspectionItemService inspectionItemService;

    /**
     * 查询检查项目列表
     */
    @GetMapping("/list")
    public TableDataInfo list(InspectionItem inspectionItem)
    {
        startPage();
        List<InspectionItem> list = inspectionItemService.selectInspectionItemList(inspectionItem);
        return getDataTable(list);
    }

    /**
     * 导出检查项目列表
     */
    @PreAuthorize("@ss.hasPermi('app:inspectionItem:export')")
    @Log(title = "检查项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InspectionItem inspectionItem)
    {
        List<InspectionItem> list = inspectionItemService.selectInspectionItemList(inspectionItem);
        ExcelUtil<InspectionItem> util = new ExcelUtil<InspectionItem>(InspectionItem.class);
        util.exportExcel(response, list, "检查项目数据");
    }

    /**
     * 获取检查项目详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(inspectionItemService.selectInspectionItemById(id));
    }

    /**
     * 新增检查项目
     */
    @PreAuthorize("@ss.hasPermi('app:inspectionItem:add')")
    @Log(title = "检查项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated  @RequestBody InspectionItem inspectionItem)
    {
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode jsonArray = mapper.readTree(inspectionItem.getResult());
            String fieldToCheck = "name";
            if (jsonUtil.checkForDuplicateFields(jsonArray, fieldToCheck))
            {
                return error("新增检查项目'" + inspectionItem.getItemName() + "'失败，本次添加中存在重复的检查结果");
            }
            if (!inspectionItemService.checkItemNameUnique(inspectionItem))
            {
                return error("新增检查项目'" + inspectionItem.getItemName() + "'失败，列表中存在重复的项目名称");
            }
            inspectionItem.setCreateBy(getUsername());
            return toAjax(inspectionItemService.insertInspectionItem(inspectionItem));
        } catch (Exception e) {
            return error("新增检查项目'" + inspectionItem.getItemName() + "'失败，错误的检查结果格式");
        }


    }

    /**
     * 修改检查项目
     */
    @PreAuthorize("@ss.hasPermi('app:inspectionItem:edit')")
    @Log(title = "检查项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody InspectionItem inspectionItem)
    {
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode jsonArray = mapper.readTree(inspectionItem.getResult());
            String fieldToCheck = "name";
            if (jsonUtil.checkForDuplicateFields(jsonArray, fieldToCheck))
            {
                return error("修改检查项目'" + inspectionItem.getItemName() + "'失败，本次添加中存在重复的检查结果");
            }
            if (!inspectionItemService.checkItemNameUnique(inspectionItem))
            {
                return error("修改检查项目'" + inspectionItem.getItemName() + "'失败，列表中存在重复的项目名称");
            }
            inspectionItem.setUpdateBy(getUsername());
            return toAjax(inspectionItemService.insertInspectionItem(inspectionItem));
        } catch (Exception e) {
            return error("修改检查项目'" + inspectionItem.getItemName() + "'失败，错误的检查结果格式");
        }
    }

    /**
     * 删除检查项目
     */
    @PreAuthorize("@ss.hasPermi('app:inspectionItem:remove')")
    @Log(title = "检查项目", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(inspectionItemService.deleteInspectionItemByIds(ids));
    }

    /**
     * 获取检查项目选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        InspectionItem inspectionItem = new InspectionItem();
        List<InspectionItem> list = inspectionItemService.selectInspectionItemList(inspectionItem);
        return success(list);
    }
}
