package com.ygtx.gxt.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;

import com.github.pagehelper.util.StringUtil;
import com.ygtx.common.constant.HttpStatus;
import com.ygtx.common.core.page.PageDomain;
import com.ygtx.common.core.page.TableSupport;
import com.ygtx.gxt.domain.*;
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.service.IGxtWorkOrderService;
import com.ygtx.common.utils.poi.ExcelUtil;
import com.ygtx.common.core.page.TableDataInfo;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.common.annotation.Excel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

/**
 * 维保工单Controller
 *
 * @author ygtx
 * @date 2025-10-25
 */
@RestController
@RequestMapping("/gxt/order")
@Api(tags = "维保工单管理")
public class GxtWorkOrderController extends BaseController
{
    @Autowired
    private IGxtWorkOrderService gxtWorkOrderService;

    /**
     * 查询维保工单列表
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:list')")
    @GetMapping("/list")
    @ApiOperation("查询维保工单列表")
    public TableDataInfo list(GxtWorkOrder gxtWorkOrder)
    {
        startPage();
        List<GxtWorkOrder> list = gxtWorkOrderService.selectGxtWorkOrderList(gxtWorkOrder);
        return getDataTable(list);
    }

    /**
     * 导出维保工单列表
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:export')")
    @Log(title = "维保工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出维保工单列表")
    public void export(HttpServletResponse response, GxtWorkOrder gxtWorkOrder, 
                       @RequestParam(value = "exportFields", required = false) String exportFieldsStr) {
        List<GxtWorkOrder> list = gxtWorkOrderService.selectGxtWorkOrderList(gxtWorkOrder);
        ExcelUtil<GxtWorkOrder> util = new ExcelUtil<GxtWorkOrder>(GxtWorkOrder.class);
        if (exportFieldsStr != null && !exportFieldsStr.isEmpty()) {
            // 将字符串分割成数组
            String[] exportFields = exportFieldsStr.split(",");
            util.showColumn(exportFields);
        }
        util.exportExcel(response, list, "维保工单数据");
    }

    /**
     * 导入维保工单数据
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:import')")
    @Log(title = "维保工单", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ApiOperation("导入维保工单数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "file", value = "工单文件", required = true, dataType = "MultipartFile", dataTypeClass = MultipartFile.class),
        @ApiImplicitParam(name = "updateSupport", value = "是否更新支持", required = true, dataType = "boolean", dataTypeClass = Boolean.class)
    })
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<GxtWorkOrder> util = new ExcelUtil<GxtWorkOrder>(GxtWorkOrder.class);
        List<GxtWorkOrder> workOrderList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = gxtWorkOrderService.importGxtWorkOrder(workOrderList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载维保工单导入模板
     */
    @PostMapping("/importTemplate")
    @ApiOperation("下载维保工单导入模板")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<GxtWorkOrder> util = new ExcelUtil<GxtWorkOrder>(GxtWorkOrder.class);
        util.importTemplateExcel(response, "维保工单数据");
    }

    /**
     * 获取维保工单详细信息
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取维保工单详细信息")
    @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(gxtWorkOrderService.selectGxtWorkOrderById(id));
    }

    /**
     * 新增维保工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:add')")
    @Log(title = "维保工单", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增维保工单")
    public AjaxResult add(@RequestBody GxtWorkOrder gxtWorkOrder)
    {
        return toAjax(gxtWorkOrderService.insertGxtWorkOrder(gxtWorkOrder));
    }

    /**
     * 修改维保工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:edit')")
    @Log(title = "维保工单", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改维保工单")
    public AjaxResult edit(@RequestBody GxtWorkOrder gxtWorkOrder)
    {
        return toAjax(gxtWorkOrderService.updateGxtWorkOrder(gxtWorkOrder));
    }

    /**
     * 删除维保工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:remove')")
    @Log(title = "维保工单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除维保工单")
    @ApiImplicitParam(name = "ids", value = "工单ID数组", required = true, dataType = "Long[]", paramType = "path", dataTypeClass = Long[].class)
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(gxtWorkOrderService.deleteGxtWorkOrderByIds(ids));
    }

    /**
     * 派单给班组组长
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:assign')")
    @Log(title = "派单给班组组长", businessType = BusinessType.UPDATE)
    @PutMapping("/assignToTeamLeader/{id}")
    public AjaxResult assignToTeamLeader(
            @PathVariable("id") Long id,
            @RequestParam("teamLeaderId") Long teamLeaderId,
            @RequestParam("teamLeaderName") String teamLeaderName)
    {
        return toAjax(gxtWorkOrderService.assignToTeamLeader(id, teamLeaderId, teamLeaderName));
    }

    /**
     * 班组组长接单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:accept')")
    @Log(title = "班组组长接单", businessType = BusinessType.UPDATE)
    @PutMapping("/acceptByTeamLeader/{id}")
    public AjaxResult acceptByTeamLeader(@PathVariable("id") Long id)
    {
        return toAjax(gxtWorkOrderService.acceptByTeamLeader(id));
    }

    /**
     * 班组组长派单给工作组成员
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:assign')")
    @Log(title = "派单给工作组成员", businessType = BusinessType.UPDATE)
    @PutMapping("/assignToWorkGroupMember/{id}")
    public AjaxResult assignToWorkGroupMember(
            @PathVariable("id") Long id,
            @RequestParam("workGroupMemberId") Long workGroupMemberId,
            @RequestParam("workGroupMemberName") String workGroupMemberName)
    {
        return toAjax(gxtWorkOrderService.assignToWorkGroupMember(id, workGroupMemberId, workGroupMemberName));
    }

    /**
     * 工作组成员接单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:accept')")
    @Log(title = "工作组成员接单", businessType = BusinessType.UPDATE)
    @PutMapping("/acceptByWorkGroupMember/{id}")
    @ApiOperation("工作组成员接单")
    @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    public AjaxResult acceptByWorkGroupMember(@PathVariable("id") Long id)
    {
        return toAjax(gxtWorkOrderService.acceptByWorkGroupMember(id));
    }

//    /**
//     * 挂起工单
//     */
//    @PreAuthorize("@ss.hasPermi('worklog:maintenance:order:suspend')")
//    @Log(title = "挂起工单", businessType = BusinessType.UPDATE)
//    @PutMapping("/suspend/{id}")
//    @ApiOperation("挂起工单")
//    @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
//    public AjaxResult suspend(
//            @PathVariable("id") Long id,
//            @RequestParam("suspendReason") String suspendReason)
//    {
//        return toAjax(gxtWorkOrderService.suspendWorkOrder(id, suspendReason));
//    }

    /**
     * 重启工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:restart')")
    @Log(title = "重启工单", businessType = BusinessType.UPDATE)
    @PutMapping("/restart/{id}")
    @ApiOperation("重启工单")
    @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    public AjaxResult restart(@PathVariable("id") Long id)
    {
        return toAjax(gxtWorkOrderService.restartWorkOrder(id));
    }

    /**
     * 完成工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:complete') or @ss.hasPermi('gxt:maintenance:order:rating') or @ss.hasPermi('gxt:maintenance:order:approve') or @ss.hasPermi('gxt:maintenance:order:restart') ")
    @Log(title = "完成工单", businessType = BusinessType.UPDATE)
    @PostMapping("/complete/{id}")
    @ApiOperation("完成工单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "gxtWorkOrder", value = "工单对象", required = true, dataType = "GxtWorkOrder", dataTypeClass = GxtWorkOrder.class)
    })
    public AjaxResult complete(@PathVariable("id") Long id, @RequestBody GxtWorkOrder gxtWorkOrder)
    {
        gxtWorkOrder.setId(id);
        return toAjax(gxtWorkOrderService.completeWorkOrder(gxtWorkOrder));
    }

    /**
     * 查询工单流转记录
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:query')")
    @GetMapping("/flow/{orderId}")
    @ApiOperation("查询工单流转记录")
    @ApiImplicitParam(name = "orderId", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    public AjaxResult getFlowList(@PathVariable("orderId") Long orderId)
    {
        List<GxtWorkOrderFlow> flowList = gxtWorkOrderService.selectWorkOrderFlowByOrderId(orderId);
        return success(flowList);
    }

    /**
     * 接单（支持一次性选择处理人员和检修人员）
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:accept')")
    @Log(title = "接单", businessType = BusinessType.UPDATE)
    @PostMapping("/accept/{id}")
    @ApiOperation("接单（支持一次性选择处理人员和检修人员）")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "gxtWorkOrder", value = "工单对象", required = true, dataType = "GxtWorkOrder", dataTypeClass = GxtWorkOrder.class)
    })
    public AjaxResult accept(@PathVariable("id") Long id, @RequestBody GxtWorkOrder gxtWorkOrder)
    {
        gxtWorkOrder.setId(id);
        return toAjax(gxtWorkOrderService.acceptOrder(gxtWorkOrder));
    }

    /**
     * 开始处理工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:start')")
    @Log(title = "开始处理", businessType = BusinessType.UPDATE)
    @PostMapping("/start/{id}")
    @ApiOperation("开始处理工单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "gxtWorkOrder", value = "工单对象", required = true, dataType = "GxtWorkOrder", dataTypeClass = GxtWorkOrder.class)
    })
    public AjaxResult start(@PathVariable("id") Long id, @RequestBody GxtWorkOrder gxtWorkOrder)
    {
        gxtWorkOrder.setId(id);
        return toAjax(gxtWorkOrderService.startWorkOrder(gxtWorkOrder));
    }

    /**
     * 暂停工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:pause')")
    @Log(title = "暂停工单", businessType = BusinessType.UPDATE)
    @PostMapping("/pause/{id}")
    @ApiOperation("暂停工单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "gxtWorkOrder", value = "工单对象", required = true, dataType = "GxtWorkOrder", dataTypeClass = GxtWorkOrder.class)
    })
    public AjaxResult pause(@PathVariable("id") Long id, @RequestBody GxtWorkOrder gxtWorkOrder)
    {
        gxtWorkOrder.setId(id);
        return toAjax(gxtWorkOrderService.pauseWorkOrder(gxtWorkOrder));
    }

    /**
     * 继续处理工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:resume') or @ss.hasPermi('gxt:maintenance:order:autoResume')")
    @Log(title = "继续处理", businessType = BusinessType.UPDATE)
    @PostMapping("/resume/{id}")
    @ApiOperation("继续处理工单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "gxtWorkOrder", value = "工单对象", required = true, dataType = "GxtWorkOrder", dataTypeClass = GxtWorkOrder.class)
    })
    public AjaxResult resume(@PathVariable("id") Long id, @RequestBody GxtWorkOrder gxtWorkOrder)
    {
        gxtWorkOrder.setId(id);
        return toAjax(gxtWorkOrderService.resumeWorkOrder(gxtWorkOrder));
    }

    /**
     * 挂起工单申请
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:suspend')")
    @Log(title = "申请挂起", businessType = BusinessType.UPDATE)
    @PostMapping("/suspend/{id}")
    @ApiOperation("挂起工单申请")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "gxtWorkOrder", value = "工单对象", required = true, dataType = "GxtWorkOrder", dataTypeClass = GxtWorkOrder.class)
    })
    public AjaxResult suspend(@PathVariable("id") Long id, @RequestBody GxtWorkOrder gxtWorkOrder)
    {
        gxtWorkOrder.setId(id);
        return toAjax(gxtWorkOrderService.suspendWorkOrder(gxtWorkOrder));
    }

    /**
     * 审批挂起申请
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:approve')")
    @Log(title = "审批挂起", businessType = BusinessType.UPDATE)
    @PostMapping("/approve/{id}")
    @ApiOperation("审批挂起申请")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "gxtWorkOrder", value = "工单对象", required = true, dataType = "GxtWorkOrder", dataTypeClass = GxtWorkOrder.class)
    })
    public AjaxResult approve(@PathVariable("id") Long id, @RequestBody GxtWorkOrder gxtWorkOrder)
    {
        gxtWorkOrder.setId(id);
        return toAjax(gxtWorkOrderService.approveWorkOrder(gxtWorkOrder));
    }

    /**
     * 上传工单附件
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:import')")
    @Log(title = "上传附件", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadAttachments")
    @ApiOperation("上传工单附件")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "orderId", value = "工单ID", required = true, dataType = "Long", dataTypeClass = Long.class),
        @ApiImplicitParam(name = "files", value = "附件文件列表", required = true, dataType = "List", dataTypeClass = List.class)
    })
    public AjaxResult uploadAttachments(
            @RequestParam("orderId") Long orderId,
            @RequestParam("files") List<GxtWorkOrderAttachment> files)
    {
        return toAjax(gxtWorkOrderService.uploadAttachments(orderId, files));
    }

    @GetMapping("/getHomePageOrderListData")
    @ApiOperation("获取首页工单列表数据")
    public TableDataInfo getHomePageOrderListData(GxtOrderData gxtOrderData)
    {
        List<GxtOrderData> result = new ArrayList<>();
        int total = 0;
        if (gxtWorkOrderService.isSelect(gxtOrderData)) {
            List<GxtOrderData> list = gxtWorkOrderService.selectHomePageWorkOrderList(gxtOrderData);
            total = list.size();
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            if (pageNum!=null && pageSize!=null) {
                int from = (pageNum-1) * pageSize;
                int to = pageNum * pageSize;
                if (to>=total) {
                    result.addAll(list.subList(from,total));
                }else {
                    result.addAll(list.subList(from, to));
                }
            }
        }
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("查询成功");
        dataInfo.setTotal(total);
        dataInfo.setRows(result);
        return dataInfo;
    }

    @PostMapping("/exportHomePageOrderList")
    @ApiOperation("导出首页工单列表")
    public void exportHomePageOrderList(HttpServletResponse response, GxtOrderData gxtOrderData)
    {
        List<GxtOrderData> list = gxtWorkOrderService.selectHomePageWorkOrderList(gxtOrderData);

        // 获取有值的字段名称
        List<String> nonNullFields = new ArrayList<>();
        if (!list.isEmpty() && StringUtil.isNotEmpty(list.get(0).getOrderCode())) {
            nonNullFields.add("orderCode");
        }
        getNonNullFields(gxtOrderData,nonNullFields);
        
        // 创建Excel工具类实例
        ExcelUtil<GxtOrderData> util = new ExcelUtil<GxtOrderData>(GxtOrderData.class);
        
        // 设置只显示同时满足两个条件的字段
        if (!nonNullFields.isEmpty()) {
            util.showColumn(nonNullFields.toArray(new String[0]));
        }
        
        util.exportExcel(response, list, "工单数据列表");
    }
    
    /**
     * 作废维保工单
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:invalidate')")
    @Log(title = "维保工单", businessType = BusinessType.UPDATE)
    @PostMapping("/invalidate")
    @ApiOperation("作废维保工单")
    public AjaxResult invalidate(@RequestBody GxtWorkOrder gxtWorkOrder)
    {
        return toAjax(gxtWorkOrderService.invalidateGxtWorkOrder(gxtWorkOrder));
    }
    
    /**
     * 获取对象中非空字段的名称
     * @param obj 对象实例
     * @return 非空字段名称列表
     */
    private void getNonNullFields(GxtOrderData obj,List<String> nonNullFields) {
        if (obj == null) {
            return;
        }
        
        Field[] fields = GxtOrderData.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                // 检查字段是否有Excel注解
                if (field.isAnnotationPresent(Excel.class)) {
                    field.setAccessible(true);
                    Object value = field.get(obj);
                    // 如果字段有值，则添加到列表中
                    if (value != null && !StringUtils.isEmpty(String.valueOf(value)) && (String.valueOf(value).equals("true") || String.valueOf(value).equals("1"))) {
                        nonNullFields.add(field.getName());
                    }
                }
            } catch (IllegalAccessException e) {
                // 忽略访问异常
            }
        }
    }

    /**
     * 获取维保工单导出字段列表
     */
    @GetMapping("/exportFields")
    @ApiOperation("获取维保工单导出字段列表")
    public AjaxResult getExportFields() {
        ExcelUtil<GxtWorkOrder> util = new ExcelUtil<GxtWorkOrder>(GxtWorkOrder.class);
        return success(util.getExportFields());
    }

    /**
     * 停机（工单停机）
     */
    @PreAuthorize("@ss.hasPermi('gxt:maintenance:order:shutdown')")
    @Log(title = "维保工单", businessType = BusinessType.UPDATE)
    @PutMapping("/shutdown")
    @ApiOperation("停机")
    public AjaxResult shutdown(@RequestBody GxtWorkOrder gxtWorkOrder)
    {
        return toAjax(gxtWorkOrderService.shutdownOrder(gxtWorkOrder));
    }
}