package com.ytpm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.ytpm.agent.model.YtPlatformAttach;
import com.ytpm.agent.model.YtWorkorder;
import com.ytpm.agent.param.AttachParam;
import com.ytpm.agent.param.WorkorderParam;
import com.ytpm.dao.AgentAttachMapper;
import com.ytpm.dao.WorkorderMapper;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.service.WorkorderService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Marx
 * @date 2025/7/31 17:22
 */
@Service
public class WorkorderServiceImpl implements WorkorderService {

    @Resource
    private WorkorderMapper workorderMapper;
    @Resource
    private AgentAttachMapper attachMapper;

    /**
     * 创建工单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> createWorkorder(WorkorderParam param) {
        YtWorkorder ytWorkorder = new YtWorkorder();
        BeanUtils.copyProperties(param, ytWorkorder);
        ytWorkorder.setWorkorderId(IdUtil.fastSimpleUUID());
        workorderMapper.insert(ytWorkorder);
        if(CollUtil.isNotEmpty(param.getAttachList())){
            List<AttachParam> attachList = param.getAttachList();
            List<YtPlatformAttach> dataList = new ArrayList<>();
            YtPlatformAttach attach;
            for (AttachParam attachParam : attachList) {
                attach = new YtPlatformAttach();
                BeanUtils.copyProperties(attachParam, attach);
                attach.setTargetType(1);
                attach.setTargetId(ytWorkorder.getWorkorderId());
                attach.setUploadTime(new Date());
                attach.setAttachId(IdUtil.getSnowflakeNextIdStr());
                attach.setUploadUserId(param.getCreateUserId());
                dataList.add(attach);
            }
            attachMapper.batchInsert(dataList);
        }
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }

    /**
     * 关闭工单
     */
    @Override
    public Result<String> closeWorkorder(String workorderId, String userId) {
        YtWorkorder old = workorderMapper.selectPrimary(workorderId);
        if(Objects.isNull(old)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        YtWorkorder workorder = new YtWorkorder();
        workorder.setWorkorderId(workorderId);
        workorder.setWorkorderStatus(1);
        workorder.setProcessor(userId);
        workorder.setFinishTime(new Date());
        workorder.setRemark("代理商主动关闭");
        workorderMapper.updateById(workorder);
        return Result.resultOk(RepMessage.MODIFY_SUCCESS);
    }
}
