package org.xyzh.workcase.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xyzh.api.workcase.dto.TbWorkcaseDTO;
import org.xyzh.api.workcase.dto.TbWorkcaseDeviceDTO;
import org.xyzh.api.workcase.dto.TbWorkcaseProcessDTO;
import org.xyzh.api.workcase.service.WorkcaseService;
import org.xyzh.common.auth.utils.LoginUtil;
import org.xyzh.common.core.domain.LoginDomain;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.utils.validation.ValidationResult;
import org.xyzh.common.utils.validation.ValidationUtils;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.v3.oas.annotations.Operation;

import java.util.Arrays;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * @description    工单管理控制器
 * @filename    WorkcaseController.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-19
 */
@Tag(name = "工单管理")
@RestController
@RequestMapping("/workcase")
public class WorkcaseController {

    @Autowired
    private WorkcaseService workcaseService;

    // ========================= 工单管理 =========================

    @Operation(summary = "创建工单")
    @PreAuthorize("hasAuthority('workcase:ticket:create')")
    @PostMapping
    public ResultDomain<TbWorkcaseDTO> createWorkcase(@RequestBody TbWorkcaseDTO workcase) {
        ValidationResult vr = ValidationUtils.validate(workcase, Arrays.asList(
            ValidationUtils.requiredString("deviceNamePlateImg", "设备名称牌图片"),
            ValidationUtils.requiredString("type", "问题类型"),
            ValidationUtils.requiredString("userId", "用户ID"),
            ValidationUtils.requiredString("username", "用户名称")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.createWorkcase(workcase);
    }

    @Operation(summary = "更新工单")
    @PreAuthorize("hasAuthority('workcase:ticket:update')")
    @PutMapping
    public ResultDomain<TbWorkcaseDTO> updateWorkcase(@RequestBody TbWorkcaseDTO workcase) {
        ValidationResult vr = ValidationUtils.validate(workcase, Arrays.asList(
            ValidationUtils.requiredString("workcaseId", "工单ID")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.updateWorkcase(workcase);
    }

    @Operation(summary = "删除工单")
    @PreAuthorize("hasAuthority('workcase:ticket:update')")
    @DeleteMapping("/{workcaseId}")
    public ResultDomain<TbWorkcaseDTO> deleteWorkcase(@PathVariable(value = "workcaseId") String workcaseId) {
        TbWorkcaseDTO workcase = new TbWorkcaseDTO();
        workcase.setWorkcaseId(workcaseId);
        return workcaseService.deleteWorkcase(workcase);
    }

    @Operation(summary = "获取工单详情")
    @PreAuthorize("hasAuthority('workcase:ticket:view')")
    @GetMapping("/{workcaseId}")
    public ResultDomain<TbWorkcaseDTO> getWorkcaseById(@PathVariable(value = "workcaseId") String workcaseId) {
        return workcaseService.getWorkcaseById(workcaseId);
    }

    @Operation(summary = "查询工单列表")
    @PreAuthorize("hasAuthority('workcase:ticket:view')")
    @PostMapping("/list")
    public ResultDomain<TbWorkcaseDTO> getWorkcaseList(@RequestBody TbWorkcaseDTO filter) {
        LoginDomain loginDomain = LoginUtil.getCurrentLogin();
        if ("guest".equals(loginDomain.getUser().getStatus())) {
            filter.setUserId(loginDomain.getUser().getUserId());
        }
        return workcaseService.getWorkcaseList(filter);
    }

    @Operation(summary = "分页查询工单")
    @PreAuthorize("hasAuthority('workcase:ticket:view')")
    @PostMapping("/page")
    public ResultDomain<TbWorkcaseDTO> getWorkcasePage(@RequestBody PageRequest<TbWorkcaseDTO> pageRequest) {
        ValidationResult vr = ValidationUtils.validate(pageRequest, Arrays.asList(
            ValidationUtils.requiredNumber("pageParam.page", "页码", 1, null),
            ValidationUtils.requiredNumber("pageParam.pageSize", "每页数量", 1, 100)
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.getWorkcasePage(pageRequest);
    }

    // ========================= CRM同步接口 =========================

    @Operation(summary = "同步工单到CRM")
    @PostMapping("/sync/crm")
    public ResultDomain<Void> syncWorkcaseToCrm(@RequestBody TbWorkcaseDTO workcase) {
        ValidationResult vr = ValidationUtils.validate(workcase, Arrays.asList(
            ValidationUtils.requiredString("workcaseId", "工单ID")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.syncWorkcaseToCrm(workcase);
    }

    @Operation(summary = "接收CRM工单更新（CRM回调）")
    @PostMapping("/receive/crm")
    public ResultDomain<Void> receiveWorkcaseFromCrm(@RequestBody String jsonBody) {
        JSONObject json = JSONObject.parseObject(jsonBody);
        return workcaseService.receiveWorkcaseFromCrm(json);
    }

    // ========================= 工单处理过程 =========================

    @Operation(summary = "创建工单处理过程")
    @PreAuthorize("hasAuthority('workcase:ticket:process')")
    @PostMapping("/process")
    public ResultDomain<TbWorkcaseProcessDTO> createWorkcaseProcess(@RequestBody TbWorkcaseProcessDTO process) {
        ValidationResult vr = ValidationUtils.validate(process, Arrays.asList(
            ValidationUtils.requiredString("workcaseId", "工单ID"),
            ValidationUtils.requiredString("action", "操作类型")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.createWorkcaseProcess(process);
    }

    @Operation(summary = "更新工单处理过程")
    @PreAuthorize("hasAuthority('workcase:ticket:process')")
    @PutMapping("/process")
    public ResultDomain<TbWorkcaseProcessDTO> updateWorkcaseProcess(@RequestBody TbWorkcaseProcessDTO process) {
        ValidationResult vr = ValidationUtils.validate(process, Arrays.asList(
            ValidationUtils.requiredString("processId", "处理过程ID")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.updateWorkcaseProcess(process);
    }

    @Operation(summary = "删除工单处理过程")
    @PreAuthorize("hasAuthority('workcase:ticket:process')")
    @DeleteMapping("/process/{processId}")
    public ResultDomain<TbWorkcaseProcessDTO> deleteWorkcaseProcess(@PathVariable(value = "processId") String processId) {
        TbWorkcaseProcessDTO process = new TbWorkcaseProcessDTO();
        process.setProcessId(processId);
        return workcaseService.deleteWorkcaseProcess(process);
    }

    @Operation(summary = "查询工单处理过程列表")
    @PreAuthorize("hasAuthority('workcase:ticket:process')")
    @PostMapping("/process/list")
    public ResultDomain<TbWorkcaseProcessDTO> getWorkcaseProcessList(@RequestBody TbWorkcaseProcessDTO filter) {
        return workcaseService.getWorkcaseProcessList(filter);
    }

    @Operation(summary = "分页查询工单处理过程")
    @PreAuthorize("hasAuthority('workcase:ticket:process')")
    @PostMapping("/process/page")
    public ResultDomain<TbWorkcaseProcessDTO> getWorkcaseProcessPage(@RequestBody PageRequest<TbWorkcaseProcessDTO> pageRequest) {
        ValidationResult vr = ValidationUtils.validate(pageRequest, Arrays.asList(
            ValidationUtils.requiredNumber("pageParam.page", "页码", 1, null),
            ValidationUtils.requiredNumber("pageParam.pageSize", "每页数量", 1, 100)
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.getWorkcaseProcessPage(pageRequest);
    }

    // ========================= 工单设备管理 =========================

    @Operation(summary = "创建工单设备")
    @PreAuthorize("hasAuthority('workcase:ticket:device')")
    @PostMapping("/device")
    public ResultDomain<TbWorkcaseDeviceDTO> createWorkcaseDevice(@RequestBody TbWorkcaseDeviceDTO device) {
        ValidationResult vr = ValidationUtils.validate(device, Arrays.asList(
            ValidationUtils.requiredString("workcaseId", "工单ID"),
            ValidationUtils.requiredString("device", "设备名称")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.createWorkcaseDevice(device);
    }

    @Operation(summary = "更新工单设备")
    @PreAuthorize("hasAuthority('workcase:ticket:device')")
    @PutMapping("/device")
    public ResultDomain<TbWorkcaseDeviceDTO> updateWorkcaseDevice(@RequestBody TbWorkcaseDeviceDTO device) {
        ValidationResult vr = ValidationUtils.validate(device, Arrays.asList(
            ValidationUtils.requiredString("workcaseId", "工单ID"),
            ValidationUtils.requiredString("device", "设备名称")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.updateWorkcaseDevice(device);
    }

    @Operation(summary = "删除工单设备")
    @PreAuthorize("hasAuthority('workcase:ticket:device')")
    @DeleteMapping("/device/{workcaseId}/{device}")
    public ResultDomain<TbWorkcaseDeviceDTO> deleteWorkcaseDevice(@PathVariable(value = "workcaseId") String workcaseId, @PathVariable(value = "device") String device) {
        TbWorkcaseDeviceDTO deviceDTO = new TbWorkcaseDeviceDTO();
        deviceDTO.setWorkcaseId(workcaseId);
        deviceDTO.setDevice(device);
        return workcaseService.deleteWorkcaseDevice(deviceDTO);
    }

    @Operation(summary = "查询工单设备列表")
    @PreAuthorize("hasAuthority('workcase:ticket:device')")
    @PostMapping("/device/list")
    public ResultDomain<TbWorkcaseDeviceDTO> getWorkcaseDeviceList(@RequestBody TbWorkcaseDeviceDTO filter) {
        return workcaseService.getWorkcaseDeviceList(filter);
    }

    @Operation(summary = "分页查询工单设备")
    @PreAuthorize("hasAuthority('workcase:ticket:device')")
    @PostMapping("/device/page")
    public ResultDomain<TbWorkcaseDeviceDTO> getWorkcaseDevicePage(@RequestBody PageRequest<TbWorkcaseDeviceDTO> pageRequest) {
        ValidationResult vr = ValidationUtils.validate(pageRequest, Arrays.asList(
            ValidationUtils.requiredNumber("pageParam.page", "页码", 1, null),
            ValidationUtils.requiredNumber("pageParam.pageSize", "每页数量", 1, 100)
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseService.getWorkcaseDevicePage(pageRequest);
    }

    // 
}
