package cn.iocoder.yudao.module.base.service.impl;

import cn.iocoder.yudao.common.RepairRoleEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.base.entity.RepairRecords;
import cn.iocoder.yudao.module.base.entity.RepairRecordsItem;
import cn.iocoder.yudao.module.base.entity.RepairWorker;
import cn.iocoder.yudao.module.base.mapper.RepairRecordsMapper;
import cn.iocoder.yudao.module.base.service.RepairRecordsItemService;
import cn.iocoder.yudao.module.base.service.RepairRecordsService;
import cn.iocoder.yudao.module.base.service.RepairWorkerService;
import cn.iocoder.yudao.module.base.vo.RepairRecordsPageReqVO;
import cn.iocoder.yudao.module.base.vo.RepairRecordsRespVO;
import cn.iocoder.yudao.module.base.vo.RepairWorkerRespVO;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 维修记录 Service 实现类
 *
 * @author lzt
 */
@Service
@Validated
public class RepairRecordsServiceImpl extends ServiceImpl<RepairRecordsMapper, RepairRecords> implements RepairRecordsService {

    @Resource
    private RepairRecordsMapper repairRecordsMapper;
    @Resource
    private AdminUserApi userApi;
    @Resource
    private RepairRecordsItemService itemService;
    @Resource
    private RepairWorkerService workerService;
    @Resource
    @Lazy
    private PermissionApi permissionApi;

    /**
     * 保存维修记录
     *
     * @param ticketId     工单id
     * @param repairItemId 工单子表id
     * @param type         工作类型（数据字典：repair_records_type;后端对应 RecordTypeEnum 枚举）
     * @param remark       备注
     * @param images       图片(相对路径按照“，”分隔)
     * @author PQZ
     * @date 14:51 2024/10/11
     **/
    @Override
    public void saveRepairRecord(String ticketId, String repairItemId, String type, String remark, String images) {
        //获取当前登录用户
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO loginUser = userApi.getUser(userId);
        //初始化维修记录
        RepairRecords repairRecords = new RepairRecords();
        repairRecords.setTicketId(ticketId);
        repairRecords.setRepairItemId(repairItemId);
        repairRecords.setType(type);
        repairRecords.setRemark(remark);
        repairRecords.setDealUserId(loginUser.getId());
        repairRecords.setDealUserName(loginUser.getNickname());
        //保存维修记录
        save(repairRecords);
        //保存附件信息
        itemService.saveItem(repairRecords.getId(), ticketId, repairItemId, images);
    }

    /**
     * 根据条件查询维修记录
     *
     * @param pageReqVO RepairRecordsPageReqVO实体
     * @return java.util.List<cn.iocoder.yudao.module.base.vo.RepairRecordsRespVO>
     * @author PQZ
     * @date 15:14 2024/10/11
     **/
    @Override
    public List<RepairRecordsRespVO> queryList(RepairRecordsPageReqVO pageReqVO) {
        //根据条件查询维修记录
        List<RepairRecordsRespVO> list = repairRecordsMapper.queryRepairRecords(pageReqVO);
        List<Long> userIds = list.stream().map(RepairRecords::getDealUserId).collect(Collectors.toList());
        //所有维修工
        List<RepairWorkerRespVO> allWorker = workerService.listAllWorker();
        //转换成map
        Map<Long,RepairWorkerRespVO> mapWorker = allWorker.stream().collect(Collectors.toMap(RepairWorker::getUserId,worker -> worker));
        //用户及角色
        Map<Long,List<String>> userRoleMap = permissionApi.roleCodesByUserIds(userIds);
        //为每一条维修记录设置查询附件
        list.forEach(item -> {
            String workerName = mapWorker.getOrDefault(item.getDealUserId(),new RepairWorkerRespVO()).getWorkerTypeStr();
            if (null != workerName) {
                item.setRoleName(workerName);
            } else {
                item.setRoleName(getRoleName(userRoleMap.get(item.getDealUserId())));
            }
            //相对路径按照“，”分隔
            item.setImages(item.getItemList().stream().map(RepairRecordsItem::getImage).collect(Collectors.joining(",")));
        });
        return list;
    }

    /**
     * 根据角色匹配名称
     * @author PQZ
     * @date 14:52 2024/11/7
     * @param codes 用户的角色codes集合
     * @return java.lang.String
     **/
    private String getRoleName(List<String> codes) {
        //维修业务管理员
        if (codes.contains(RepairRoleEnum.ADMIN.getCode())) {
            return RepairRoleEnum.ADMIN.getName();
        }
        // 总检
        if (codes.contains(RepairRoleEnum.INSPECTION.getCode())) {
            return RepairRoleEnum.INSPECTION.getName();
        }
        // 服务顾问
        if (codes.contains(RepairRoleEnum.ADVISOR.getCode())) {
            return RepairRoleEnum.ADVISOR.getName();
        }
        // 维修仓库管理员
        if (codes.contains(RepairRoleEnum.WAREHOUSE.getCode())) {
            return RepairRoleEnum.WAREHOUSE.getName();
        }
        // 维修财务
        if (codes.contains(RepairRoleEnum.WXCW.getCode())) {
            return RepairRoleEnum.WXCW.getName();
        }
        return null;
    }

    /**
     * 根据当前用户和工单主表id查询当前在维修的项目信息
     *
     * @param ticketId 工单id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
     * @author vinjor-M
     * @date 13:35 2024/10/19
     **/
    @Override
    public CommonResult<?> selectNowRepairByTicketId(String ticketId) {
        return CommonResult.success(repairRecordsMapper.selectNowRepairByTicketId(ticketId));
    }
}
