package com.ygtx.gxt.controller;

import com.ygtx.common.annotation.Log;
import com.ygtx.common.core.controller.BaseController;
import com.ygtx.common.core.domain.AjaxResult;
import com.ygtx.common.core.page.TableDataInfo;
import com.ygtx.common.enums.BusinessType;
import com.ygtx.gxt.domain.GxtRepairOrder;
import com.ygtx.gxt.domain.GxtWorkOrder;
import com.ygtx.gxt.domain.OrderScoreInfo;
import com.ygtx.gxt.service.IGxtOrderHourService;
import com.ygtx.gxt.service.IGxtRepairOrderService;
import com.ygtx.gxt.service.IGxtWorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

import java.util.List;
import java.util.Map;

/**
 * 工单工时Controller
 * 
 * @author lingming
 * @date 2025-11-12
 */
@RestController
@RequestMapping("/gxt/orderHour")
@Api(tags = "工单工时管理")
public class GxtOrderHourController extends BaseController
{
    @Autowired
    private IGxtRepairOrderService gxtRepairOrderService;

    @Autowired
    private IGxtWorkOrderService gxtWorkOrderService;
    
    @Autowired
    private IGxtOrderHourService gxtOrderHourService;

    /**
     * 查询工单工时列表（合并维修工单和维保工单）
     */
    @ApiOperation("查询工单工时列表（合并维修工单和维保工单）")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "orderType", value = "工单类型", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "timeRange", value = "时间范围", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "beginDate", value = "开始日期", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "endDate", value = "结束日期", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "keyword", value = "关键词", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class)
    })
    @GetMapping("/list")
    public TableDataInfo list(GxtRepairOrder repairOrder, GxtWorkOrder workOrder, 
                              @RequestParam(required = false) String orderType,
                              @RequestParam(required = false) String timeRange,
                              @RequestParam(required = false) String beginDate,
                              @RequestParam(required = false) String endDate,
                              @RequestParam(required = false) String keyword) {
        // 开启分页插件自动分页
        startPage();
        // 查询合并的工单列表
        List<OrderScoreInfo> list = gxtOrderHourService.selectUnionOrderList(repairOrder, workOrder, orderType, timeRange, beginDate, endDate, keyword);
        return getDataTable(list);
    }

    /**
     * 查询工单工时统计信息
     */
    @ApiOperation("查询工单工时统计信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "orderType", value = "工单类型", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "timeRange", value = "时间范围", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "beginDate", value = "开始日期", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "endDate", value = "结束日期", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "keyword", value = "关键词", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class)
    })
    @GetMapping("/statistics")
    public AjaxResult getStatistics(GxtRepairOrder repairOrder, GxtWorkOrder workOrder, 
                                    @RequestParam(required = false) String orderType,
                                    @RequestParam(required = false) String timeRange,
                                    @RequestParam(required = false) String beginDate,
                                    @RequestParam(required = false) String endDate,
                                    @RequestParam(required = false) String keyword) {
        Map<String, Object> statistics = gxtOrderHourService.getOrderHourStatistics(repairOrder, workOrder, orderType, timeRange, beginDate, endDate, keyword);
        return AjaxResult.success(statistics);
    }
    
    /**
     * 获取工单详情（包含工时构成信息）
     */
    @ApiOperation("获取工单详情（包含工时构成信息）")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "orderType", value = "工单类型", required = true, dataType = "Integer", paramType = "path", dataTypeClass = Integer.class),
        @ApiImplicitParam(name = "orderId", value = "工单ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    })
    @GetMapping("/detail/{orderType}/{orderId}")
    public AjaxResult getOrderDetail(@PathVariable("orderType") Integer orderType, @PathVariable("orderId") Long orderId)
    {
        OrderScoreInfo order = null;
        if (orderType == 1) {
            // 维修工单
            GxtRepairOrder repairOrder = gxtRepairOrderService.selectGxtRepairOrderById(orderId);
            // 转换为OrderScoreInfo对象
            order = convertRepairOrderToScoreInfo(repairOrder);
        } else if (orderType == 2) {
            // 维保工单
            GxtWorkOrder workOrder = gxtWorkOrderService.selectGxtWorkOrderById(orderId);
            // 转换为OrderScoreInfo对象
            order = convertWorkOrderToScoreInfo(workOrder);
        }
        
        if (order != null) {
            // 计算工时构成信息
            gxtOrderHourService.calculateOrderTimeDetails(order);
            return AjaxResult.success(order);
        }
        
        return AjaxResult.error("未找到工单信息");
    }
    
    /**
     * 将维修工单转换为OrderScoreInfo对象
     */
    private OrderScoreInfo convertRepairOrderToScoreInfo(GxtRepairOrder repairOrder) {
        if (repairOrder == null) {
            return null;
        }
        
        OrderScoreInfo info = new OrderScoreInfo();
        info.setOrderType(1);
        info.setId(repairOrder.getId());
        info.setWorkOrderProjectNo(repairOrder.getWorkOrderProjectNo());
        info.setWorkOrderStatus(repairOrder.getWorkOrderStatus());
        info.setGxtCenterId(repairOrder.getGxtCenterId());
        info.setGxtCenter(repairOrder.getGxtCenter());
        info.setPcsStationId(repairOrder.getPcsStationId());
        info.setPcsStationPid(repairOrder.getPcsStationPid());
        info.setPcsStationName(repairOrder.getPcsStationName());
        info.setPcsDeviceId(repairOrder.getPcsDeviceId());
        info.setPcsDeviceName(repairOrder.getPcsDeviceName());
        info.setBrand(repairOrder.getBrand());
        info.setModel(repairOrder.getModel());
        info.setAssignTime(repairOrder.getAssignTime());
        info.setAssignUserId(repairOrder.getAssignUserId());
        info.setAssignUserName(repairOrder.getAssignUserName());
        info.setAcceptTime(repairOrder.getAcceptTime());
        info.setAcceptUserId(repairOrder.getAcceptUserId());
        info.setAcceptUserName(repairOrder.getAcceptUserName());
        info.setRealStartTime(repairOrder.getRealStartTime());
        info.setRealEndTime(repairOrder.getRealEndTime());
        info.setTeamLeaderId(repairOrder.getTeamLeaderId());
        info.setTeamLeaderName(repairOrder.getTeamLeaderName());
        info.setWorkGroupMemberId(repairOrder.getWorkGroupMemberId());
        info.setWorkGroupMemberName(repairOrder.getWorkGroupMemberName());
        info.setScore(repairOrder.getScore() != null ? repairOrder.getScore().doubleValue() : null);
        info.setReviewContent(repairOrder.getReviewContent());
        info.setSuspendReason(repairOrder.getSuspendReason());
        info.setRestartTime(repairOrder.getRestartTime());
        info.setPriorityType(repairOrder.getPriorityType());
        info.setScoringStatus(repairOrder.getScoringStatus());
        info.setWorkSummary(repairOrder.getContent());
        info.setMaintenanceType(repairOrder.getMaintenanceType());
        info.setPlanHour(repairOrder.getPlanHour() != null ? repairOrder.getPlanHour().doubleValue() : null);
        info.setFaultCode(repairOrder.getFaultCode());
        info.setFaultDesc(repairOrder.getFaultDesc());
        info.setOccurTime(repairOrder.getOccurTime());
        info.setReviewScoreNum(repairOrder.getReviewScoreNum());
        info.setFinalCoefficient(repairOrder.getFinalCoefficient());
        info.setCreateTime(repairOrder.getCreateTime());
        info.setUpdateTime(repairOrder.getUpdateTime());
        return info;
    }
    
    /**
     * 将维保工单转换为OrderScoreInfo对象
     */
    private OrderScoreInfo convertWorkOrderToScoreInfo(GxtWorkOrder workOrder) {
        if (workOrder == null) {
            return null;
        }
        
        OrderScoreInfo info = new OrderScoreInfo();
        info.setOrderType(2);
        info.setId(workOrder.getId());
        info.setWorkOrderProjectNo(workOrder.getWorkOrderProjectNo());
        info.setWorkOrderStatus(workOrder.getWorkOrderStatus());
        info.setGxtCenterId(workOrder.getGxtCenterId());
        info.setGxtCenter(workOrder.getGxtCenter());
        info.setPcsStationId(workOrder.getPcsStationId());
        info.setPcsStationPid(workOrder.getPcsStationPid());
        info.setPcsStationName(workOrder.getPcsStationName());
        info.setPcsDeviceId(workOrder.getPcsDeviceId());
        info.setPcsDeviceName(workOrder.getPcsDeviceName());
        info.setBrand(workOrder.getBrand());
        info.setModel(workOrder.getModel());
        info.setAssignTime(workOrder.getAssignTime());
        info.setAssignUserId(workOrder.getAssignUserId());
        info.setAssignUserName(workOrder.getAssignUserName());
        info.setAcceptTime(workOrder.getAcceptTime());
        info.setAcceptUserId(workOrder.getAcceptUserId());
        info.setAcceptUserName(workOrder.getAcceptUserName());
        info.setRealStartTime(workOrder.getRealStartTime());
        info.setRealEndTime(workOrder.getRealEndTime());
        info.setTeamLeaderId(workOrder.getTeamLeaderId());
        info.setTeamLeaderName(workOrder.getTeamLeaderName());
        info.setWorkGroupMemberId(workOrder.getWorkGroupMemberId());
        info.setWorkGroupMemberName(workOrder.getWorkGroupMemberName());
        info.setScore(workOrder.getScore() != null ? workOrder.getScore().doubleValue() : null);
        info.setReviewContent(workOrder.getReviewContent());
        info.setSuspendReason(workOrder.getSuspendReason());
        info.setRestartTime(workOrder.getRestartTime());
        info.setPriorityType(workOrder.getPriorityType() != null ? workOrder.getPriorityType().toString() : null);
        info.setScoringStatus(workOrder.getScoringStatus());
        info.setWorkSummary(workOrder.getRealContent());
        info.setInspectionType(workOrder.getInspectionType());
        info.setPlanStartTime(workOrder.getPlanStartTime());
        info.setPlanEndTime(workOrder.getPlanEndTime());
        info.setPlanHour(workOrder.getPlanHour() != null ? workOrder.getPlanHour().doubleValue() : null);
        info.setFaultCode(workOrder.getFaultCode());
        info.setFaultDesc(workOrder.getFaultDesc());
        info.setSuspendTime(workOrder.getSuspendTime());
        info.setPauseReason(workOrder.getPauseReason());
        info.setPauseTime(workOrder.getPauseTime());
        info.setCompleteTime(workOrder.getCompleteTime());
        info.setReviewScoreNum(workOrder.getReviewScoreNum());
        info.setFinalCoefficient(workOrder.getFinalCoefficient());
        info.setCreateTime(workOrder.getCreateTime());
        info.setUpdateTime(workOrder.getUpdateTime());
        return info;
    }
}