package com.zksy.web.controller.gasbasic;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zksy.base.domain.WorkOrder;
import com.zksy.base.domain.WorkOrderLog;
import com.zksy.base.service.BusinessWorkOrderService;
import com.zksy.common.core.controller.BaseController;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.utils.DateUtils;
import com.zksy.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 业务工单管理 Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/work-order")
@Api(tags = "业务工单管理")
public class BusinessWorkOrderController extends BaseController {

    @Autowired
    private BusinessWorkOrderService businessWorkOrderService;

    @GetMapping("/list")
    @ApiOperation("查询工单列表（equipmentType：gas-燃气 drainage-排水，为空默认燃气）")
    public AjaxResult list(Integer orderType, Integer orderLevel, Integer orderStatus, String deviceCode, String keyword, String equipmentType, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {

        IPage<WorkOrder> page = businessWorkOrderService.selectWorkOrderList(orderType, orderLevel, orderStatus, deviceCode, keyword, equipmentType, pageNum, pageSize);

        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        data.put("pageNum", page.getCurrent());
        data.put("pageSize", page.getSize());
        return AjaxResult.success(data);
    }

    @GetMapping("/{orderId}")
    @ApiOperation("查询工单详情（含操作日志）")
    public AjaxResult detail(@PathVariable Long orderId) {
        WorkOrder order = businessWorkOrderService.getWorkOrderDetail(orderId);
        List<WorkOrderLog> logs = businessWorkOrderService.getWorkOrderLogs(orderId);

        Map<String, Object> data = new HashMap<>();
        data.put("order", order);
        data.put("logs", logs);
        return AjaxResult.success(data);
    }

    @PostMapping("/dispatch")
    @ApiOperation("派单")
    public AjaxResult dispatch(@RequestBody Map<String, Object> body) {
        if (body.get("orderId") == null) {
            return AjaxResult.error("工单ID不能为空");
        }
        Long orderId = Long.valueOf(body.get("orderId").toString());
        String remarks = body.get("remarks") != null ? body.get("remarks").toString() : "";
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        // 支持多人派单：优先使用 handlerIds 数组，兼容旧版 handlerId
        if (body.get("handlerIds") != null) {
            // 使用 List<?> 兼容 Jackson 解析出的 Integer/Long/String 类型
            List<?> handlerIdList = (List<?>) body.get("handlerIds");
            if (handlerIdList.isEmpty()) {
                return AjaxResult.error("接单人不能为空");
            }
            List<Long> handlerIds = new ArrayList<>();
            for (Object item : handlerIdList) {
                if (item != null) {
                    handlerIds.add(Long.valueOf(item.toString()));
                }
            }
            businessWorkOrderService.batchDispatchOrder(orderId, handlerIds, remarks, userId, userName);
        } else if (body.get("handlerId") != null) {
            Long handlerId = Long.valueOf(body.get("handlerId").toString());
            businessWorkOrderService.dispatchOrder(orderId, handlerId, remarks, userId, userName);
        } else {
            return AjaxResult.error("接单人不能为空");
        }
        return AjaxResult.success("派单成功");
    }

    @PutMapping("/verify")
    @ApiOperation("核查")
    public AjaxResult verify(@RequestBody Map<String, Object> body) {
        Long orderId = Long.valueOf(body.get("orderId").toString());
        String handleResult = body.get("handleResult") != null ? body.get("handleResult").toString() : "";
        String solution = body.get("solution") != null ? body.get("solution").toString() : "";
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        businessWorkOrderService.verifyOrder(orderId, handleResult, solution, userId, userName);
        return AjaxResult.success("核查完成");
    }

    @PutMapping("/process")
    @ApiOperation("处理")
    public AjaxResult process(@RequestBody Map<String, Object> body) {
        Long orderId = Long.valueOf(body.get("orderId").toString());
        String handleResult = body.get("handleResult") != null ? body.get("handleResult").toString() : "";
        String solution = body.get("solution") != null ? body.get("solution").toString() : "";
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        businessWorkOrderService.processOrder(orderId, handleResult, solution, userId, userName);
        return AjaxResult.success("处理完成");
    }

    @PutMapping("/complete")
    @ApiOperation("完成/提交验收")
    public AjaxResult complete(@RequestParam Long orderId, @RequestParam String result) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        businessWorkOrderService.completeOrder(orderId, result, userId, userName);
        return AjaxResult.success("提交验收成功");
    }

    @PutMapping("/close")
    @ApiOperation("验收通过/结案，同步联动隐患状态为已整改")
    public AjaxResult close(@RequestBody Map<String, Object> body) {
        Long orderId = Long.valueOf(body.get("orderId").toString());
        String result = body.get("result") != null ? body.get("result").toString() : "";
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();
        businessWorkOrderService.closeOrder(orderId, result, userId, userName);
        return AjaxResult.success("验收通过");
    }

    @PostMapping("/createFromHazard")
    @ApiOperation("从隐患创建工单")
    public AjaxResult createFromHazard(@RequestBody Map<String, Object> body) {
        String hazardId = (String) body.get("hazardId");
        String hazardNo = (String) body.get("hazardNo");
        String hazardDesc = (String) body.get("hazardDesc");
        String equipmentId = (String) body.get("equipmentId");
        String hazardLevel = (String) body.get("hazardLevel");
        String hazardImages = (String) body.get("hazardImages");
        String planFinishTimeStr = (String) body.get("planFinishTime");

        if (hazardId == null || equipmentId == null) {
            return AjaxResult.error("隐患ID和设备ID不能为空");
        }

        Date planFinishTime = null;
        if (StringUtils.isNotEmpty(planFinishTimeStr)) {
            planFinishTime = DateUtils.parseDate(planFinishTimeStr);
        }

        Long orderId = businessWorkOrderService.createWorkOrderFromHazard(hazardId, hazardNo, hazardDesc, equipmentId, hazardLevel, hazardImages, planFinishTime);
        return AjaxResult.success("工单创建成功", orderId);
    }

    @DeleteMapping("/{orderId}")
    @ApiOperation("取消工单")
    public AjaxResult cancel(@PathVariable Long orderId) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        businessWorkOrderService.cancelOrder(orderId, userId, userName);
        return AjaxResult.success("取消工单成功");
    }
}
