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

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.app.controller.admin.NotifyMessageSocket;
import cn.iocoder.yudao.module.base.entity.RepairWorker;
import cn.iocoder.yudao.module.base.mapper.RepairWorkerMapper;
import cn.iocoder.yudao.module.base.service.RepairWorkerService;
import cn.iocoder.yudao.module.base.vo.RepairWorkerPageReqVO;
import cn.iocoder.yudao.module.base.vo.RepairWorkerRespVO;
import cn.iocoder.yudao.module.base.vo.RepairWorkerSaveReqVO;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
import cn.iocoder.yudao.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.api.user.dto.UserDTO;
import cn.iocoder.yudao.module.tickets.entity.DlRepairTitem;
import cn.iocoder.yudao.module.tickets.service.DlRepairTitemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.common.BaseConstants.TICKET_EMPLOY;
import static cn.iocoder.yudao.common.RepairCons.DICT_REPAIR_WORK_TYPE;

/**
 * 维修工人 Service 实现类
 *
 * @author pqz
 */
@Service
@Validated
public class RepairWorkerServiceImpl extends ServiceImpl<RepairWorkerMapper, RepairWorker> implements RepairWorkerService {

    @Resource
    private RepairWorkerMapper workerMapper;

    @Resource
    @Lazy
    private DlRepairTitemService dlRepairTitemService;
    @Resource
    private NotifyMessageSendApi sendApi;
    @Autowired
    private NotifyMessageSocket notifyMessageSocket;
    @Resource
    private DictDataApi dictDataApi;


    /**
     * 批量创建维修工人
     *
     * @param userList 选中用户集合
     * @author lzt
     * @date 2024年10月10日
     **/
    @Override
    public void saveWorkers(List<UserDTO> userList) {
        if (CollectionUtil.isNotEmpty(userList)) {
            //获取已有的维修工人ID列表
            List<Long> existingWorkerIds = workerMapper.getAllWorkerIds();

            List<RepairWorker> saveList = new ArrayList<>();
            userList.forEach(item -> {
                if (!existingWorkerIds.contains(item.getId())) {
                    RepairWorker worker = new RepairWorker();
                    worker.setUserId(item.getId());
                    worker.setUserName(item.getNickname());
                    saveList.add(worker);
                }
            });

            if (!saveList.isEmpty()) {
                saveBatch(saveList);
            }
        }
    }

    @Override
    public void updateWorker(RepairWorkerSaveReqVO updateReqVO) {
        // 更新
        RepairWorker updateObj = BeanUtils.toBean(updateReqVO, RepairWorker.class);
        workerMapper.updateById(updateObj);
    }

    @Override
    public void deleteWorker(String id) {
        // 删除
        workerMapper.deleteById(id);
    }


    @Override
    public RepairWorker getWorker(String id) {
        return workerMapper.selectById(id);
    }

    /**
     * @param pageReqVO RepairWorkerPageReqVO实体
     * @param page      分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.base.vo.RepairWorkerRespVO>
     * @author PQZ
     * @date 14:12 2024/10/9
     **/
    @Override
    public IPage<RepairWorkerRespVO> queryListPage(RepairWorkerPageReqVO pageReqVO, Page<RepairWorkerRespVO> page) {
        IPage<RepairWorkerRespVO> respVOIPage= workerMapper.queryListPage(pageReqVO, page);
        if(!respVOIPage.getRecords().isEmpty()){
            // 单位字典
            List<DictDataRespDTO> recordTypeList = dictDataApi.getDictDataList(DICT_REPAIR_WORK_TYPE);
            Map<String,String> typeMap = recordTypeList.stream().collect(Collectors.toMap(DictDataRespDTO::getValue,DictDataRespDTO::getLabel));
            respVOIPage.getRecords().stream().peek(item->item.setWorkTypeText(typeMap.get(item.getWorkType()))).collect(Collectors.toList());
        }
        return respVOIPage;
    }

    /**
     * 通过工单ID查到工单ID中所选择的员工信息
     *
     * @param ticketId 工单ID
     * @author 小李
     * @date 15:53 2024/10/14
     **/
    @Override
    public List<RepairWorker> listByTicketId(String ticketId) {
        // 查工单的项目信息
        List<DlRepairTitem> titems = dlRepairTitemService.list(new LambdaQueryWrapper<DlRepairTitem>()
                .and(item -> {
                    item.eq(DlRepairTitem::getTicketId, ticketId)
                            .eq(DlRepairTitem::getItemType, "01");
                }));
        // 取所有的员工ID
        Set<String> ids = titems.stream().flatMap(item -> Arrays.stream(item.getRepairIds().split(","))).collect(Collectors.toSet());
        List<RepairWorker> repairWorkerList = baseMapper.selectList(new LambdaQueryWrapper<RepairWorker>().in(RepairWorker::getUserId, ids));
        if(!repairWorkerList.isEmpty()){
            // 单位字典
            List<DictDataRespDTO> recordTypeList = dictDataApi.getDictDataList(DICT_REPAIR_WORK_TYPE);
            Map<String,String> typeMap = recordTypeList.stream().collect(Collectors.toMap(DictDataRespDTO::getValue,DictDataRespDTO::getLabel));
            repairWorkerList.stream().peek(item->item.setWorkTypeText(typeMap.get(item.getWorkType()))).collect(Collectors.toList());
        }
        //翻译工种
        return repairWorkerList;

    }

    /**
     * 向指定用户发送消息
     *
     * @param userId 用户id
     * @param text   消息通知内容
     * @author PQZ
     * @date 16:27 2024/10/18
     **/
    @Override
    public void sentMessage(Long userId, String text) {
        try {
            //获取当前登录用户
            LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
            // 准备发送参数
            Map<String, Object> templateParams = new HashMap<>();
            // 发送模版内容
            templateParams.put("text", text);
            // 发送站内信
            sendApi.sendSingleMessageToAdmin(new NotifySendSingleToUserReqDTO()
                    .setUserId(userId)
                    .setTemplateCode(TICKET_EMPLOY).setTemplateParams(templateParams));
            //发送语音提醒
            notifyMessageSocket.sendMessage(text, loginUser.getTenantId().toString(), userId.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过班组长的id查该班组的员工
     *
     * @author 小李
     * @date 16:55 2024/10/14
     **/
    @Override
    public List<RepairWorker> listByLeads() {
        // 取班组长的记录
        RepairWorker worker = baseMapper.selectOne(new LambdaQueryWrapper<RepairWorker>().eq(RepairWorker::getUserId, SecurityFrameworkUtils.getLoginUserId()));
        // 根据班组长的工种查所有该工程的工人
        List<RepairWorker> workerList = baseMapper.selectList(new LambdaQueryWrapper<RepairWorker>().eq(RepairWorker::getWorkType, worker.getWorkType()));
        // 去掉班组长自己
        return workerList.stream().filter(item -> !Objects.equals(item.getUserId(), worker.getUserId())).collect(Collectors.toList());
    }

    /**
     * 查当前登录用户是否维修班组长
     *
     * @return boolean
     * @author vinjor-M
     * @date 18:17 2024/10/16
     **/
    @Override
    public boolean getIfLeader() {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        LambdaQueryWrapper<RepairWorker> queryWrapper = new LambdaQueryWrapper<RepairWorker>()
                .eq(RepairWorker::getUserId, userId);
        List<RepairWorker> list = this.list(queryWrapper);
        return !list.isEmpty() && "1".equals(list.get(0).getIsLeads());
    }
}
