package com.pm.repairOrder.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import com.pm.common.core.domain.model.LoginUser;
import com.pm.common.utils.DateUtils;
import com.pm.common.utils.SecurityUtils;
import com.pm.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pm.repairOrder.mapper.RepairOrderMapper;
import com.pm.repairOrder.service.IRepairOrderService;
import com.pm.common.config.PageData;

/**
 * 维修工单Service业务层处理
 *
 * @author pm
 * @date 2025-04-27
 */
@Service
public class RepairOrderServiceImpl implements IRepairOrderService
{
    @Autowired
    private RepairOrderMapper repairOrderMapper;

    /**
     * 查询维修工单
     *
     * @param id 维修工单主键
     * @return 维修工单
     */
    @Override
    public PageData selectRepairOrderById(String id)
    {
        return repairOrderMapper.selectRepairOrderById(id);
    }

    /**
     * 查询维修工单列表
     *
     * @param pd 维修工单
     * @return 维修工单
     */
    @Override
    public List<PageData> selectRepairOrderList(PageData pd)
    {
        if(pd.containsKey("state")){
            pd.put("userId",SecurityUtils.getLoginUser().getUserId());
        }
        return repairOrderMapper.selectRepairOrderList(pd);
    }

    /**
     * 新增维修工单
     *
     * @param pd 维修工单
     * @return 结果
     */
    @Override
    public int insertRepairOrder(PageData pd)
    {
        pd.put("id", IdUtils.simpleUUID());
        pd.put("createTime", DateUtils.getTime());
        if(pd.containsKey("finishBy")&&!pd.getString("finishBy").equals("")){
            pd.put("assignTime", DateUtils.getTime());
            pd.put("orderStatus", 1);
        }
        return repairOrderMapper.insertRepairOrder(pd);
    }

    /**
     * 修改维修工单
     *
     * @param pd 维修工单
     * @return 结果
     */
    @Override
    public int updateRepairOrder(PageData pd)
    {
        pd.put("updateTime", DateUtils.getTime());
        if(pd.containsKey("finishBy")&&!pd.getString("finishBy").equals("")){ //如果责任人不为空则说明数据已分配 但是只要是分配了责任人的这个数据都不是空
            pd.put("assignTime", DateUtils.getTime());
            pd.put("orderStatus", 1);
        }
        if (pd.containsKey("finishTime")&&!pd.getString("finishTime").equals("")){ // 如果完成时间不为空则说明数据已完成
            pd.put("orderStatus", 2);
        }
        return repairOrderMapper.updateRepairOrder(pd);
    }

    /**
     * 批量删除维修工单
     *
     * @param ids 需要删除的维修工单主键
     * @return 结果
     */
    @Override
    public int deleteRepairOrderByIds(String[] ids)
    {
        return repairOrderMapper.deleteRepairOrderByIds(ids);
    }

    /**
     * 删除维修工单信息
     *
     * @param id 维修工单主键
     * @return 结果
     */
    @Override
    public int deleteRepairOrderById(String id)
    {
        return repairOrderMapper.deleteRepairOrderById(id);
    }

    /**
     * 获取工单统计数据
     */
    @Override
    public Map<String, Object> getRepairOrderStatistics(PageData pd)
    {
        Map<String, Object> result = new HashMap<>();
        if(pd.containsKey("isMe")){
            pd.put("userId",SecurityUtils.getLoginUser().getUserId());
        }
        // 获取所有工单
        List<PageData> allOrders = repairOrderMapper.selectRepairOrderList(pd);

        // 统计总数
        result.put("total", allOrders.size());

        // 统计各状态数量
        long pending = allOrders.stream()
                .filter(o -> "0".equals(o.getString("orderStatus")))
                .count();
        long processing = allOrders.stream()
                .filter(o -> "1".equals(o.getString("orderStatus")))
                .count();
        long completed = allOrders.stream()
                .filter(o -> "2".equals(o.getString("orderStatus")))
                .count();

        result.put("pending", pending);
        result.put("processing", processing);
        result.put("completed", completed);

        // 计算趋势（简化处理）
        result.put("totalTrend", 12);
        result.put("pendingTrend", -5);
        result.put("processingTrend", 8);
        result.put("completedTrend", 15);

        return result;
    }
    /**
     * 获取工单操作日志
     */
    @Override
    public List<PageData> getRepairOrderLogs(PageData pd)
    {
        return repairOrderMapper.selectRepairOrderLogs(pd);
    }

    /**
     * 添加操作日志
     */
    @Override
    public int addOperationLog(PageData pd)
    {
        // 设置日志ID
        pd.put("logId", UUID.randomUUID().toString().replace("-", ""));
        // 设置操作人
        pd.put("operateUser", SecurityUtils.getUsername());
        // 设置操作时间
        pd.put("operateTime", DateUtils.getNowDate());

        return repairOrderMapper.insertRepairOrderLog(pd);
    }

    /**
     * 生成工单编号
     */
    @Override
    public String generateOrderNo()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        // 生成4位随机数
        int random = (int) (Math.random() * 9000) + 1000;
        return "WO" + timestamp + random;
    }

}
