package com.ytpm.middle.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.agent.model.YtWorkorder;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.middle.dao.AttachMapper;
import com.ytpm.middle.dao.WorkorderMapper;
import com.ytpm.middle.enums.AttachTargetEnum;
import com.ytpm.middle.param.WorkorderListParam;
import com.ytpm.middle.service.WorkorderService;
import com.ytpm.middle.view.WorkorderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author Marx
 * @date 2025/8/1 9:11
 */
@Service
public class WorkorderServiceImpl implements WorkorderService {

    @Resource
    private WorkorderMapper workorderMapper;
    @Resource
    private AttachMapper attachMapper;

    /**
     * 查询工单列表
     */
    @Override
    public ResultTable<WorkorderVO> queryList(WorkorderListParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        return ResultTable.resultTableOk(new PageInfo<WorkorderVO>(workorderMapper.queryList(param)));
    }

    /**
     * 处理工单
     */
    @Override
    public Result<String> processWorkorder(String workorderId, String remark, String userId) {
        YtWorkorder old = workorderMapper.selectByPrimary(workorderId);
        if(Objects.isNull(old)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        YtWorkorder workorder = new YtWorkorder();
        workorder.setWorkorderId(workorderId);
        workorder.setRemark(remark);
        workorder.setWorkorderStatus(1);
        workorder.setProcessor(userId);
        workorder.setFinishTime(new Date());
        workorder.setUpdateParam(userId);
        workorderMapper.updateById(workorder);
        return Result.resultOk(RepMessage.PROCESS_SUCCESS);
    }

    /**
     * 查询工单详情
     */
    @Override
    public Result<WorkorderVO> selectOne(String workorderId) {
        YtWorkorder old = workorderMapper.selectByPrimary(workorderId);
        if(Objects.isNull(old)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        WorkorderVO vo = new WorkorderVO();
        BeanUtils.copyProperties(old, vo);
        vo.setAttachList(attachMapper.queryByTargetId(old.getWorkorderId(), AttachTargetEnum.WORKORDER.getBusinessNode()));
        return Result.resultObjOk(vo);
    }
}
