package com.bonus.sgzb.material.service.impl;

import com.bonus.sgzb.base.api.domain.MachinePart;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.StringHelper;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.mapper.PurchaseCheckDetailsMapper;
import com.bonus.sgzb.material.mapper.PurchaseCheckInfoMapper;
import com.bonus.sgzb.material.mapper.TaskMapper;
import com.bonus.sgzb.material.service.IPurchaseCheckInfoService;
import com.bonus.sgzb.material.vo.GlobalContants;
import com.bonus.sgzb.material.vo.NoticeInfoVO;
import com.bonus.sgzb.system.api.RemoteUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 新购验收任务Service业务层处理
 *
 * @author bonus
 * @date 2023-12-10
 */
@Service
public class PurchaseCheckInfoServiceImpl implements IPurchaseCheckInfoService {
    @Resource
    private PurchaseCheckInfoMapper purchaseCheckInfoMapper;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private PurchaseCheckDetailsMapper purchaseCheckDetailsMapper;

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 查询新购验收任务
     *
     * @param taskId  新购验收任务主键
     * @param keyword 关键字筛选
     * @return 新购验收任务
     */
    @Override
    public PurchaseCheckInfo selectPurchaseCheckInfoByTaskId(Long taskId, String keyword) {
        PurchaseCheckInfo purchaseCheckInfo = purchaseCheckInfoMapper.selectPurchaseCheckInfoByTaskId(taskId);
        PurchaseCheckDetails purchaseCheckDetails = new PurchaseCheckDetails();
        purchaseCheckDetails.setTaskId(purchaseCheckInfo.getTaskId());
        purchaseCheckDetails.setKeyWord(keyword);
        List<PurchaseCheckDetails> purchaseCheckDetailsList = purchaseCheckDetailsMapper.selectPurchaseCheckDetailsList(purchaseCheckDetails);
        purchaseCheckInfo.setCheckDetailsList(purchaseCheckDetailsList);
        return purchaseCheckInfo;
    }

    /**
     * 查询新购入库任务列表
     *
     * @param purchaseCheckInfo 新购入库任务
     * @return 新购入库任务
     */
    @Override
    public List<PurchaseCheckInfo> selectPutInListList(PurchaseCheckInfo purchaseCheckInfo) {
        List<PurchaseCheckInfo> purchaseCheckInfos = purchaseCheckInfoMapper.selectPutInListList(purchaseCheckInfo);
        for (PurchaseCheckInfo checkInfo : purchaseCheckInfos) {
            String typeName = purchaseCheckInfoMapper.selectTypeNameByTaskId(checkInfo.getTaskId(), "2");
            checkInfo.setPurchasingTypeName(typeName);
        }
        return purchaseCheckInfos;
    }

    @Override
    public List<PurchaseCheckInfo> exportList(PurchaseCheckInfo purchaseCheckInfo) {
        return purchaseCheckInfoMapper.exportList(purchaseCheckInfo);
    }

    @Override
    public List<PurchaseInput> putInExportList(PurchaseCheckInfo purchaseCheckInfo) {
        return purchaseCheckInfoMapper.putInExportList(purchaseCheckInfo);
    }

    /**
     * 新购验收单
     */
    @Override
    public PurchaseCheckInfo getAcceptanceForm(Long taskId, String keyword) {
        PurchaseCheckInfo purchaseCheckInfo = purchaseCheckInfoMapper.selectPurchaseCheckInfoByTaskId(taskId);
        PurchaseCheckDetails purchaseCheckDetails = new PurchaseCheckDetails();
        purchaseCheckDetails.setTaskId(purchaseCheckInfo.getTaskId());
        purchaseCheckDetails.setKeyWord(keyword);
        List<PurchaseCheckDetails> purchaseCheckDetailsList = purchaseCheckDetailsMapper.getAcceptanceForm(purchaseCheckDetails);
        purchaseCheckInfo.setCheckDetailsList(purchaseCheckDetailsList);
        return purchaseCheckInfo;
    }

    @Override
    public List<PurchaseCheckInfo> selectPutInListExamine(PurchaseCheckInfo purchaseCheckInfo) {
        List<PurchaseCheckInfo> purchaseCheckInfos = purchaseCheckInfoMapper.selectPutInListExamine(purchaseCheckInfo);
        for (PurchaseCheckInfo checkInfo : purchaseCheckInfos) {
            String typeName = purchaseCheckInfoMapper.selectTypeNameByTaskId(checkInfo.getTaskId(), "3");
            checkInfo.setPurchasingTypeName(typeName);
        }
        return purchaseCheckInfos;
    }

    @Override
    public List<MachinePart> getWholeSetDetails(PurchaseCheckInfo purchaseCheckInfo) {
        return purchaseCheckInfoMapper.getWholeSetDetails(purchaseCheckInfo);
    }

    /**
     * 查询新购验收任务列表
     *
     * @param purchaseCheckInfo 新购验收任务
     * @return 新购验收任务
     */
    @Override
    public List<PurchaseCheckInfo> selectPurchaseCheckInfoList(PurchaseCheckInfo purchaseCheckInfo) {
        List<PurchaseCheckInfo> purchaseCheckInfos = purchaseCheckInfoMapper.selectPurchaseCheckInfoList(purchaseCheckInfo);
        Map<Long, PurchaseCheckInfo> taskIdInfoMap = new HashMap<>(); // 缓存查询结果，避免重复查询
        for (PurchaseCheckInfo checkInfo : purchaseCheckInfos) {
            // 判断是否已经查询过该taskId的结果，如果没有，进行查询并缓存
            if (!taskIdInfoMap.containsKey(checkInfo.getTaskId())) {
                List<PurchaseCheckInfo> taskInfoList = purchaseCheckInfoMapper.selectTypeNameAndManageTypeByTaskId(checkInfo.getTaskId());
                if (!taskInfoList.isEmpty()) {
                    taskIdInfoMap.put(checkInfo.getTaskId(), taskInfoList.get(0));
                }
            }

            // 获取缓存中的查询结果，进行处理
            Optional<PurchaseCheckInfo> optionalInfo = Optional.ofNullable(taskIdInfoMap.get(checkInfo.getTaskId()));
            if (optionalInfo.isPresent()) {
                PurchaseCheckInfo taskInfo = optionalInfo.get();
                String typeName = taskInfo.getPurchasingTypeName();
                String manageType = taskInfo.getManageType().contains("0") ? "0" : "1";
                checkInfo.setPurchasingTypeName(typeName);
                checkInfo.setManageType(manageType);
            }
        }
        return purchaseCheckInfos;
    }

    /**
     * 新增新购验收任务
     *
     * @param purchaseCheckInfo 新购验收任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPurchaseCheckInfo(PurchaseCheckInfo purchaseCheckInfo) {
        TmTask task = new TmTask();
        // 暂定的状态字典表
        task.setTaskType(23);
        task.setTaskStatus(24);
        // 采购单号
        task.setCode(purchaseCodeRule());
        task.setCreateTime(DateUtils.getNowDate());
        task.setCompanyId(purchaseCheckInfo.getCompanyId());
        task.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
        // 创建任务信息
        taskMapper.insertTmTask(task);
        purchaseCheckInfo.setTaskId(task.getTaskId());
        purchaseCheckInfo.setCreateTime(DateUtils.getNowDate());

        // 批量新增新购任务详情信息
        List<PurchaseCheckDetails> checkDetailsList = purchaseCheckInfo.getCheckDetailsList();
        if (checkDetailsList != null) {
            for (PurchaseCheckDetails purchaseCheckDetails : checkDetailsList) {
                purchaseCheckDetails.setTaskId(task.getTaskId());
                purchaseCheckDetails.setStatus(2);
            }
            purchaseCheckDetailsMapper.insertPurchaseCheckDetailsList(checkDetailsList);
        }
        // 新增任务信息
        return purchaseCheckInfoMapper.insertPurchaseCheckInfo(purchaseCheckInfo);
    }

    /**
     * 采购单号编码生成规则
     */
    private String purchaseCodeRule() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String taskNum = taskMapper.selectTaskNumByMonths(nowDate, 23);
        if (StringHelper.isNotEmpty(taskNum)) {
            // 将字符串转换为整数
            int num = Integer.parseInt(taskNum);
            // 执行加一操作
            num++;
            // 将结果转换回字符串格式，并确保结果是四位数，不足四位则在前面补0
            taskNum = String.format("%04d", num);
        } else {
            taskNum = "0001";
        }
        String code = "XG" + format + "-" + taskNum;
        return code;
    }

    /**
     * 修改新购验收任务
     *
     * @param purchaseCheckInfo 新购验收任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePurchaseCheckInfo(PurchaseCheckInfo purchaseCheckInfo) throws Exception {
        Long taskId = purchaseCheckInfo.getTaskId();
        TmTask task = taskMapper.selectTmTaskByTaskId(taskId);
        // 判断当前任务是否为待通知状态
        if (task == null || task.getTaskStatus() != GlobalContants.NUM6) {
            throw new Exception("当前任务不可修改!!!");
        }
        // 批量新增新购任务详情信息
        List<PurchaseCheckDetails> checkDetailsList = purchaseCheckInfo.getCheckDetailsList();
        if (checkDetailsList != null) {
            // 先删除全部的任务详情信息
            purchaseCheckDetailsMapper.deleteCheckDetailsByTaskId(taskId);
            for (PurchaseCheckDetails purchaseCheckDetails : checkDetailsList) {
                purchaseCheckDetails.setTaskId(taskId);
                purchaseCheckDetails.setStatus(2);
            }
            // 添加任务详情信息
            purchaseCheckDetailsMapper.insertPurchaseCheckDetailsList(checkDetailsList);
        }
        purchaseCheckInfo.setUpdateTime(DateUtils.getNowDate());
        return purchaseCheckInfoMapper.updatePurchaseCheckInfo(purchaseCheckInfo);
    }

    /**
     * 批量删除新购验收任务
     *
     * @param taskIds 需要删除的新购验收任务主键
     * @return 结果
     */
    @Override
    public int deletePurchaseCheckInfoByTaskIds(Long[] taskIds) {
        return purchaseCheckInfoMapper.deletePurchaseCheckInfoByTaskIds(taskIds);
    }

    /**
     * 删除新购验收任务信息
     *
     * @param taskId 新购验收任务主键
     * @return 结果
     */
    @Override
    public int deletePurchaseCheckInfoByTaskId(Long taskId) {
        int result = 0;
        try {
            // 第一步：删除验收任务表
            purchaseCheckInfoMapper.deletePurchaseCheckInfoByTaskId(taskId);
            // 第二步：删除验收任务详情表
            purchaseCheckDetailsMapper.deleteCheckDetailsByTaskId(taskId);
            // 第三步：删除任务表
            taskMapper.deleteTmTaskByTaskId(taskId);
            result = 1;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 验收通知
     *
     * @param noticeInfoVO 验收通知内容
     * @return 结果
     */
    @Override
    public Boolean insertBmNoticeInfo(NoticeInfoVO noticeInfoVO) throws Exception {
        // 任务状态修改
        TmTask task = new TmTask();
        Long taskId = noticeInfoVO.getTaskId();
        if (taskId == null) {
            throw new Exception("任务taskId为空!!");
        }
        TmTask task1 = taskMapper.selectTmTaskByTaskId(taskId);
        if (task1.getTaskStatus() != GlobalContants.NUM6) {
            throw new Exception("任务状态不为待通知!!");
        }
        task.setTaskId(taskId);
        task.setTaskStatus(25);
        taskMapper.updateTmTask(task);
        // 修改任务详情状态
        purchaseCheckDetailsMapper.updateCheckDetailsByTaskId(taskId);

        String message = noticeInfoVO.getMessage();
        List<BmNoticeInfo> bmNoticeInfoList = noticeInfoVO.getBmNoticeInfoList();
        if (bmNoticeInfoList.size() <= 0) {
            throw new Exception("绑定用户为空");
        }
        Boolean send = true;
        for (BmNoticeInfo bmNoticeInfo : bmNoticeInfoList) {
            bmNoticeInfo.setContent(message);
            bmNoticeInfo.setTaskId(taskId);
            bmNoticeInfo.setModelName("新购机具验收");
            bmNoticeInfo.setCreateTime(new Date());
            String phone = bmNoticeInfo.getPhone();
            // 短信通知
            send = remoteUserService.send(phone, message);
            purchaseCheckInfoMapper.insertBmNoticeInfo(bmNoticeInfo);
        }
        return send;
    }
}
