package org.jeecg.modules.workOrder.controller;

import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.api.model.CabinetModel;
import org.jeecg.modules.api.service.CabinetConnectService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.workOrder.entity.OperationRecord;
import org.jeecg.modules.workOrder.entity.WorkOrder;
import org.jeecg.modules.workOrder.model.WorkOrderDto;
import org.jeecg.modules.workOrder.service.IOperationRecordService;
import org.jeecg.modules.workOrder.service.IWorkOrderService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.workOrder.service.IWorkPermitCompleteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 任务工单
 * @Author: jeecg-boot
 * @Date:   2025-02-10
 * @Version: V1.0
 */
@Api(tags="任务工单")
@RestController
@RequestMapping("/workOrder/workOrder")
@Slf4j
public class WorkOrderController extends JeecgController<WorkOrder, IWorkOrderService> {
	@Autowired
	private IWorkOrderService workOrderService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private IWorkPermitCompleteService workPermitCompleteService;
	 @Autowired
	 private CabinetConnectService cabinetConnectService;
	 @Value("${spring.active}")
	 private String activeProfile;
	@Autowired
	private IOperationRecordService operationRecordService;
	/**
	 * 分页列表查询
	 *
	 * @param workOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务工单-分页列表查询")
	@ApiOperation(value="任务工单-分页列表查询", notes="任务工单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<WorkOrder>> queryPageList(WorkOrder workOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WorkOrder> queryWrapper = QueryGenerator.initQueryWrapper(workOrder, req.getParameterMap());
		queryWrapper.eq("delete_flag",0);
		Page<WorkOrder> page = new Page<WorkOrder>(pageNo, pageSize);
		IPage<WorkOrder> pageList = workOrderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  *   通过工单id查询工单详细内容
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "任务工单-通过id查询工单详细内容")
	 @ApiOperation(value="任务工单-通过id查询工单详细内容", notes="任务工单-通过id查询工单详细内容")
	 @GetMapping(value = "/getDetailbyId")
	 public Result<WorkOrderDto> getDetailbyId(@RequestParam(name="id",required=true) String id,@RequestParam(name="queryAll",required=false) Integer queryAll) {
		 return Result.OK(workOrderService.getDetailbyId(id, queryAll!=0));
	 }

	/**
	 *   添加
	 *
	 * @param workOrder
	 * @return
	 */
	@AutoLog(value = "任务工单-添加")
	@ApiOperation(value="任务工单-添加", notes="任务工单-添加")
	//@RequiresPermissions("org.jeecg.modules:bu_work_order:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody WorkOrder workOrder) {
        try {
            if(workOrderService.addWorkOrder(workOrder))
                return Result.OK("添加成功！");
            else
                return Result.error("添加失败！");
        } catch (Exception e) {
			return Result.error(e.getMessage());
        }
    }

	/**
	 *  编辑
	 *
	 * @param workOrder
	 * @return
	 */
	@AutoLog(value = "任务工单-编辑")
	@ApiOperation(value="任务工单-编辑", notes="任务工单-编辑")
	//@RequiresPermissions("org.jeecg.modules:bu_work_order:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody WorkOrder workOrder) {
//		if(workOrder.getStatus()!=null && workOrder.getStatus()==3){
////			// 如果工单要开工，需要先判断是否请点
////			if(workPermitCompleteService.getCheckStatus(workOrder.getId())){
//				workOrderService.updateById(workOrder);
//				return Result.OK("开工成功!");
////			}else {
////				return Result.error("尚未完成请点，不能开工！");
////			}
//		}else if(workOrder.getStatus()!=null && workOrder.getStatus()==0){
//			return workOrderService.cancelWorkOrder(workOrder) ? Result.ok("撤销成功") : Result.error("撤销工单失败！");
//		}
		if(workOrder.getStatus() != null){
			switch (workOrder.getStatus()){
				case 3:
					//开工
					workOrderService.updateById(workOrder);
					return Result.OK("开工成功!");
				case 4:
					//完工
//					//todo 判断所有作业是否完成
//					long count = operationRecordService.queryUncompleteCount(workOrder.getId());
//					if(count > 0){
//						return Result.error("请先完成所有作业！");
//					}
					long toolCount = operationRecordService.queryUnreturnCount(workOrder.getId());
					if(toolCount > 0){
						return Result.error("请先归还所有工具！");
					}
					workOrderService.updateById(workOrder);
					return Result.OK("完工成功!");
				case 7:
					//停工，当天未完成的工单，需要跨天完成的工单
					long toolCount1 = operationRecordService.queryUnreturnCount(workOrder.getId());
					if(toolCount1 > 0){
						return Result.error("请先归还所有工具！");
					}
					return workOrderService.stopWorkOrder(workOrder) ? Result.ok("停工成功") : Result.error("停工失败！");
				case 0:
					//撤销
					return workOrderService.cancelWorkOrder(workOrder) ? Result.ok("撤销成功") : Result.error("撤销工单失败！");
			}
		}

		if(workOrder.getReviewType()!=null){
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			Map<Integer, Consumer<String>> reviewSetters = Map.of(
					1, workOrder::setReview1,
					2, workOrder::setReview2,
					3, workOrder::setReview3,
					4, workOrder::setReview4
			);

			Consumer<String> setter = reviewSetters.get(workOrder.getReviewType());
			if (setter != null) {
				setter.accept(user.getId());
			}
		}
		workOrderService.updateById(workOrder);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务工单-通过id删除")
	@ApiOperation(value="任务工单-通过id删除", notes="任务工单-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:bu_work_order:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		workOrderService.update(null,new LambdaUpdateWrapper<WorkOrder>().set(WorkOrder::getDeleteFlag,1)
				.eq(WorkOrder::getId,id));
		operationRecordService.remove(new LambdaQueryWrapper<OperationRecord>().eq(OperationRecord::getWorkOrder,id));
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务工单-批量删除")
	@ApiOperation(value="任务工单-批量删除", notes="任务工单-批量删除")
	//@RequiresPermissions("org.jeecg.modules:bu_work_order:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		workOrderService.update(null,new LambdaUpdateWrapper<WorkOrder>().set(WorkOrder::getDeleteFlag,1)
				.in(WorkOrder::getId,Arrays.asList(ids.split(","))));
		operationRecordService.remove(new LambdaQueryWrapper<OperationRecord>().in(OperationRecord::getWorkOrder,Arrays.asList(ids.split(","))));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "任务工单-通过id查询")
	@ApiOperation(value="任务工单-通过id查询", notes="任务工单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<WorkOrder> queryById(@RequestParam(name="id",required=true) String id) {
		WorkOrder workOrder = workOrderService.getById(id);
		if(workOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(workOrder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param workOrder
    */
    //@RequiresPermissions("org.jeecg.modules:bu_work_order:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WorkOrder workOrder) {
        return super.exportXls(request, workOrder, WorkOrder.class, "任务工单");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("bu_work_order:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WorkOrder.class);
    }

	 @RequiresRoles({"admin"})
	 @PostMapping("/asyncUser2Cabinet")
	 public Result<?> asyncUsers() {
		 List<SysUser> sysUsers = sysUserService.list();
		 List<CabinetModel> cabinetModels = sysUsers.stream().map(user -> {
			 CabinetModel model = new CabinetModel();
			 model.setUserId(user.getId());
			 model.setUserName(user.getUsername());
			 model.setNickName(user.getRealname());
			 model.setFaceUrl(user.getFaceUrl());
			 List<SysUserRole> sysuserRole = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,user.getId()));
			 if(!sysuserRole.isEmpty()) {
				 model.setRoles(sysuserRole.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
			 }
			 return model;
		 }).toList();

		 if("prod".equals(activeProfile)){
			 cabinetConnectService.sendUsers(cabinetModels);
		 }

		 return Result.ok();
	 }

	 @GetMapping("/workOrderStatic")
	 public Result<?> workOrderStatic() {
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<WorkOrder> workOrderList = workOrderService.list(new LambdaQueryWrapper<WorkOrder>().eq(!"admin".equals(user.getUsername()), WorkOrder::getCoordinator, user.getId())
				 .eq(WorkOrder::getDeleteFlag, 0));

		 // 状态统计：使用 Map 直接累加，避免中间变量
		 Map<String, Integer> resultMap = new HashMap<>();
		 resultMap.put("notStart", 0);
		 resultMap.put("start", 0);
		 resultMap.put("finish", 0);

		 // 统计逻辑
		 for (WorkOrder workOrder : workOrderList) {
			 switch (workOrder.getStatus()) {
				 case 2:
				 case 5:
				 case 6:
					 resultMap.put("notStart", resultMap.get("notStart") + 1);
					 break;
				 case 3:
					 resultMap.put("start", resultMap.get("start") + 1);
					 break;
				 case 4:
					 resultMap.put("finish", resultMap.get("finish") + 1);
					 break;
				 // 可选：default 忽略其他状态，或记录日志
			 }
		 }
		 return Result.OK(resultMap);
	 }
}
