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

import com.bonus.sgzb.base.api.domain.MaInputRecord;
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.PurchaseCheckServiceCenterMapper;
import com.bonus.sgzb.material.mapper.TaskMapper;
import com.bonus.sgzb.material.service.PurchaseCheckServiceCenterService;
import com.bonus.sgzb.material.vo.GlobalContants;
import com.bonus.sgzb.base.api.domain.MaInputVO;
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.Date;
import java.util.List;

/**
 * 新购验收任务Service业务层处理
 *
 * @author bonus
 * @date 2023-12-10
 */
@Service
public class PurchaseCheckServiceCenterServiceImpl implements PurchaseCheckServiceCenterService {
    @Resource
    private PurchaseCheckServiceCenterMapper purchaseCheckServiceCenterMapper;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private PurchaseCheckDetailsMapper purchaseCheckDetailsMapper;

    @Resource
    private PurchaseCheckDetailsMapper checkDetailsMapper;

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 查询新购验收任务
     *
     * @param taskId  新购验收任务主键
     * @param keyword 关键字筛选
     * @return 新购验收任务
     */
    @Override
    public PurchaseCheckInfo selectPurchaseCheckInfoByTaskId(Long taskId, String keyword) {
        PurchaseCheckInfo purchaseCheckInfo = purchaseCheckServiceCenterMapper.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 = purchaseCheckServiceCenterMapper.selectPutInListList(purchaseCheckInfo);
        for (PurchaseCheckInfo checkInfo : purchaseCheckInfos) {
            String typeName = purchaseCheckServiceCenterMapper.selectTypeNameByTaskId(checkInfo.getTaskId(),"2");
            checkInfo.setPurchasingTypeName(typeName);
        }
        return purchaseCheckInfos;
    }

    /**
     * 获取入库清单明细
     *
     * @param purchaseMacodeInfo 查询条件
     * @return 结果
     */
    @Override
    public List<PurchaseMacodeInfo> selectPutinDetails(PurchaseMacodeInfo purchaseMacodeInfo) {
        return purchaseCheckServiceCenterMapper.selectPutinDetails(purchaseMacodeInfo);
    }

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

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

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

    /**
     * 查询新购验收任务列表
     *
     * @param purchaseCheckInfo 新购验收任务
     * @return 新购验收任务
     */
    @Override
    public List<PurchaseCheckInfo> selectPurchaseCheckInfoList(PurchaseCheckInfo purchaseCheckInfo) {
        List<PurchaseCheckInfo> purchaseCheckInfos = purchaseCheckServiceCenterMapper.selectPurchaseCheckInfoList(purchaseCheckInfo);
        for (PurchaseCheckInfo checkInfo : purchaseCheckInfos) {
            String typeName = purchaseCheckServiceCenterMapper.selectTypeNameByTaskId(checkInfo.getTaskId(),"1");
            checkInfo.setPurchasingTypeName(typeName);
        }
        return purchaseCheckInfos;
    }

    /**
     * 修改编码管理的入库状态,暂时不用
     *
     * @param maInputVO 入库信息
     * @return 结果
     */
    @Override
    public int modifyManageStatus(MaInputVO maInputVO) {
        Long taskId = maInputVO.getTaskId();
        String checkResult = maInputVO.getCheckResult();
        List<MaInputRecord> inputRecordList = maInputVO.getInputRecordList();
        for (MaInputRecord maInputRecord : inputRecordList) {
            Long typeId = maInputRecord.getTypeId();

            //修改编码管理表入库状态
            PurchaseMacodeInfo purchaseMacodeInfo = new PurchaseMacodeInfo();
            purchaseMacodeInfo.setTaskId(taskId);
            purchaseMacodeInfo.setTypeId(typeId);
            purchaseMacodeInfo.setMaCode(maInputRecord.getMaCode());

            // 修改验收任务详细表入库数量
            if ("1".equals(checkResult)) {
                //修改机具状态为在库
                PurchaseCheckDetails purchaseCheckDetails = new PurchaseCheckDetails();
                purchaseCheckDetails.setStatus(6);
                purchaseCheckDetails.setTaskId(taskId);
                purchaseCheckDetails.setTypeId(typeId);
                checkDetailsMapper.updateStatusByTaskIdTypeId(purchaseCheckDetails);
            }else {
                //删除ma_machine表
                purchaseCheckServiceCenterMapper.deleteMaMachineInfoByMaId(maInputRecord.getMaId());
                //删除ma_machine_label表
                purchaseCheckServiceCenterMapper.deleteMaMachineLabelByMaId(maInputRecord.getMaId());
                //删除ma_label_bind表
                purchaseCheckServiceCenterMapper.deleteMaLabelBindByMaId(maInputRecord.getMaId());
                //修改purchase_macode_info表
                purchaseCheckServiceCenterMapper.updatetePurchaseMaCodeInfoByMaCodeAndTaskIdAndTypeId(taskId,typeId,maInputRecord.getMaCode());
                //修改purchase_check_details表
                checkDetailsMapper.updateByTaskId(taskId,typeId);
            }
        }

        //判断是否全部已操作（通过或不通过）
        int count=purchaseCheckServiceCenterMapper.isOperateAll(taskId);
        if (count<=0) {
            //是否为全部不通过
            int count1 = purchaseCheckServiceCenterMapper.selectPurchaseCheckDetailsStatus(taskId);
            if (count1 <= 0) {
                //是则将任务状态改为验收不通过
                TmTask task = new TmTask();
                task.setTaskId(taskId);
                task.setTaskStatus(106);
                task.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                task.setUpdateTime(DateUtils.getNowDate());
                taskMapper.updateTmTask(task);
            } else {
                // 当全部操作,修改任务为验收状态
                TmTask task = new TmTask();
                task.setTaskId(taskId);
                task.setTaskStatus(105);
                task.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                task.setUpdateTime(DateUtils.getNowDate());
                taskMapper.updateTmTask(task);
            }
        }
        return 1;
    }

    @Override
    public int selectExamineType(Long companyId) {
        return purchaseCheckServiceCenterMapper.selectExamineType(companyId);
    }

    /**
     * 新增新购验收任务
     *
     * @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 purchaseCheckServiceCenterMapper.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 purchaseCheckServiceCenterMapper.updatePurchaseCheckInfo(purchaseCheckInfo);
    }

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

    /**
     * 删除新购验收任务信息
     *
     * @param taskId 新购验收任务主键
     * @return 结果
     */
    @Override
    public int deletePurchaseCheckInfoByTaskId(Long taskId) {
        return purchaseCheckServiceCenterMapper.deletePurchaseCheckInfoByTaskId(taskId);
    }

    /**
     * 验收通知
     *
     * @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);
            purchaseCheckServiceCenterMapper.insertBmNoticeInfo(bmNoticeInfo);
        }
        return send;
    }
}
