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

import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.StringHelper;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.mapper.PurchaseAccessoryMapper;
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.IPurchaseAccessoryService;
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.Date;
import java.util.List;

/**
 * @author hay
 * @description 新购配件任务Service业务层处理
 * @date 2024/1/17 16:42
 */
@Service
public class PurchaseAccessoryServiceImpl implements IPurchaseAccessoryService {
    @Resource
    private PurchaseAccessoryMapper purchaseAccessoryMapper;

    @Resource
    private TaskMapper taskMapper;

    /**
     * 新增新购验收任务
     *
     * @param purchasePartInfo 新购验收任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPurchaseAccessory(PurchasePartInfo purchasePartInfo) {
        int res = 0;
        try {
            TmTask task = new TmTask();
            // 暂定的状态字典表
            task.setTaskType(67);
            task.setTaskStatus(68);
            // 采购单号
            task.setCode(purchaseCodeRule());
            task.setCreateTime(DateUtils.getNowDate());
            task.setCompanyId(purchasePartInfo.getCompanyId());
            task.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
            // 创建任务信息
            res = taskMapper.insertTmTask(task);
            if (res == 0) {
                throw new RuntimeException("新增失败，创建任务未成功");
            }
            purchasePartInfo.setTaskId(task.getTaskId());
            purchasePartInfo.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
            purchasePartInfo.setCreateTime(DateUtils.getNowDate());
            // 批量新增新购任务详情信息
            List<PurchasePartDetails> partDetailsList = purchasePartInfo.getPartDetailsList();
            if (partDetailsList != null) {
                for (PurchasePartDetails purchasePartDetails : partDetailsList) {
                    purchasePartDetails.setTaskId(task.getTaskId());
                    purchasePartDetails.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                    purchasePartDetails.setCreateTime(DateUtils.getNowDate());
                }
                res = purchaseAccessoryMapper.insertPurchasePartDetailsList(partDetailsList);
                if (res == 0) {
                    throw new RuntimeException("新增失败，新增详情未成功");
                }
            }
            // 新增任务信息
            res = purchaseAccessoryMapper.insertPurchasePartInfo(purchasePartInfo);
            if (res == 0) {
                throw new RuntimeException("新增失败，新增新购配件未成功");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return res;
    }

    @Override
    public List<PurchasePartInfo> selectPurchasePartInfoList(PurchasePartInfo purchasePartInfo) {
        List<PurchasePartInfo> purchasePartInfos = purchaseAccessoryMapper.selectPurchasePartInfoList(purchasePartInfo);
        for (PurchasePartInfo partInfo : purchasePartInfos) {
            String typeName = purchaseAccessoryMapper.selectTypeNameByTaskId(partInfo.getTaskId(),"1");
            partInfo.setPurchasingTypeName(typeName);
        }
        return purchasePartInfos;
    }

    @Override
    public PurchasePartInfo selectPurchasePartInfoByTaskId(Long taskId, String keyWord) {
        PurchasePartInfo purchasePartInfo = purchaseAccessoryMapper.selectPurchasePartInfoByTaskId(taskId);
        PurchasePartDetails purchasePartDetails = new PurchasePartDetails();
        purchasePartDetails.setTaskId(purchasePartInfo.getTaskId());
        purchasePartDetails.setKeyWord(keyWord);
        List<PurchasePartDetails> purchasePartDetailsList = purchaseAccessoryMapper.selectPurchasePartDetailsList(purchasePartDetails);
        purchasePartInfo.setPartDetailsList(purchasePartDetailsList);
        return purchasePartInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePurchaseCheckInfo(PurchasePartInfo purchasePartInfo) {
        int res = 0;
        try {
            Long taskId = purchasePartInfo.getTaskId();
            TmTask task = taskMapper.selectTmTaskByTaskId(taskId);
            // 判断当前任务是否为待通知状态
            if (task == null || task.getTaskStatus() != GlobalContants.NUM5) {
                throw new RuntimeException("当前任务不可修改!!!");
            }
            // 批量新增新购任务详情信息
            List<PurchasePartDetails> partDetailsList = purchasePartInfo.getPartDetailsList();
            if (partDetailsList != null) {
                // 先删除全部的任务详情信息
                res = purchaseAccessoryMapper.deletePartDetailsByTaskId(taskId);
                if (res == 0) {
                    throw new RuntimeException("修改失败，删除未成功");
                }
                for (PurchasePartDetails purchasePartDetails : partDetailsList) {
                    purchasePartDetails.setTaskId(taskId);
                    purchasePartDetails.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                    purchasePartDetails.setUpdateTime(DateUtils.getNowDate());
                }
                // 添加任务详情信息
                res = purchaseAccessoryMapper.insertPurchasePartDetailsList(partDetailsList);
                if (res == 0) {
                    throw new RuntimeException("修改失败,添加详情信息未成功");
                }
            }
            purchasePartInfo.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
            purchasePartInfo.setUpdateTime(DateUtils.getNowDate());
            res = purchaseAccessoryMapper.updatePurchasePartInfo(purchasePartInfo);
            if (res == 0) {
                throw new RuntimeException("修改失败,修改基本信息未成功");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return res;
    }

    @Override
    public AjaxResult deletePurchasePartInfoByTaskIds(Long[] taskIds) {
        for (Long taskId : taskIds) {
            TmTask task = taskMapper.selectTmTaskByTaskId(taskId);
            // 判断当前任务是否为待通知状态
            if (task == null || task.getTaskStatus() >= 69) {
                return AjaxResult.error("当前任务已验收，不可删除!");
            }
        }
        int res = purchaseAccessoryMapper.deletePurchasePartInfoByTaskIds(taskIds);
        if (res > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    @Override
    public List<PurchasePartInfo> selectPutInListList(PurchasePartInfo purchasePartInfo) {
        List<PurchasePartInfo> purchasePartInfos = purchaseAccessoryMapper.selectPutInListList(purchasePartInfo);
        for (PurchasePartInfo partInfo : purchasePartInfos) {
            String typeName = purchaseAccessoryMapper.selectTypeNameByTaskId(partInfo.getTaskId(),"2");
            partInfo.setPurchasingTypeName(typeName);
        }
        return purchasePartInfos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePurchaseCheckDetails(List<PurchasePartDetails> purchasePartDetailsList) {
        int res = 0;
        try {
            Long taskId = 0L;
            for (PurchasePartDetails purchasePartDetails : purchasePartDetailsList) {
                taskId = purchasePartDetails.getTaskId();
                if ("通过".equals(purchasePartDetails.getCheckResult())) {
                    purchasePartDetails.setStatus(1);
                } else if ("不通过".equals(purchasePartDetails.getCheckResult())) {
                    purchasePartDetails.setStatus(2);
                } else {
                    purchasePartDetails.setStatus(0);
                }
                purchasePartDetails.setUpdateTime(DateUtils.getNowDate());
                res = purchaseAccessoryMapper.updatePurchasePartDetails(purchasePartDetails);
                if (res == 0) {
                    throw new RuntimeException("验收失败,修改状态未成功");
                }
            }
            //判断是否全部已操作（不通过或通过）
            int count=purchaseAccessoryMapper.isOperateAll(taskId);
            if (count<=0){
                //是否为全部不通过
                int count1 = purchaseAccessoryMapper.selectPurchasePartDetailsStatusIsNoPass(taskId);
                if (count1<=0){
                    //是则将任务状态改为验收不通过
                    TmTask task = new TmTask();
                    task.setTaskId(taskId);
                    task.setTaskStatus(71);
                    task.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                    task.setUpdateTime(DateUtils.getNowDate());
                    taskMapper.updateTmTask(task);
                }else {
                    // 当全部操作,修改任务为验收状态
                    TmTask task = new TmTask();
                    task.setTaskId(taskId);
                    task.setTaskStatus(69);
                    task.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                    task.setUpdateTime(DateUtils.getNowDate());
                    taskMapper.updateTmTask(task);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return res;
    }

    @Override
    public List<PurchasePartInfo> getPartList(String level) {
        return purchaseAccessoryMapper.getPartList(level);
    }

    @Override
    public List<PurchasePartDetails> selectPutinDetails(PurchasePartDetails purchasePartDetails) {
        //因传入status=0时在SQL中处理有问题所以在此处理
        if (purchasePartDetails.getStatus()!=null){
            if (purchasePartDetails.getStatus()==0){
                purchasePartDetails.setStatus(1);
            }else if (purchasePartDetails.getStatus()==1){
                purchasePartDetails.setStatus(3);
            }else if (purchasePartDetails.getStatus()==2){
                purchasePartDetails.setStatus(4);
            }
        }
        return purchaseAccessoryMapper.selectPutinDetails(purchasePartDetails);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int checkInput(List<PurchasePartDetails> purchasePartDetailsList) {
        int res = 0;
        try {
            Long taskId = 0L;
            for (PurchasePartDetails partDetails : purchasePartDetailsList) {
                taskId = partDetails.getTaskId();
                //处理审核通过的
                if ("1".equals(partDetails.getCheckResult())) {
                    partDetails.setStatus(3);
                    partDetails.setInputNum(partDetails.getCheckNum());
                    partDetails.setInputTime(DateUtils.getNowDate().toString());

                    partDetails.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                    partDetails.setUpdateTime(DateUtils.getNowDate());
                    //查询该任务是否已审核
                    res = purchaseAccessoryMapper.setlectStatusById(partDetails.getId());
                    if (res <= 0) {
                        res = purchaseAccessoryMapper.updatePurchasePartDetails(partDetails);
                        if (res == 0) {
                            throw new RuntimeException("审核入库失败,修改状态未成功");
                        }
                        res = purchaseAccessoryMapper.updatePartTypeNum(partDetails.getPartId(), partDetails.getCheckNum());
                        if (res == 0) {
                            throw new RuntimeException("审核入库失败,修改配件库存未成功");
                        }
                    }
                } else {
                    partDetails.setStatus(4);
                    partDetails.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                    partDetails.setUpdateTime(DateUtils.getNowDate());
                    //查询该任务是否已审核
                    res = purchaseAccessoryMapper.setlectStatusById(partDetails.getId());
                    if (res <= 0) {
                        res = purchaseAccessoryMapper.updatePurchasePartDetails(partDetails);
                        if (res == 0) {
                            throw new RuntimeException("审核入库失败,修改状态未成功");
                        }
                    }
                }
            }

            // 当全部审核,修改任务入库状态
            int count = purchaseAccessoryMapper.selectPurchasePartDetailsStatus(taskId);
            if (count <= 0) {
                TmTask task = new TmTask();
                task.setTaskId(taskId);
                task.setTaskStatus(70);
                task.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                task.setUpdateTime(DateUtils.getNowDate());
                res = taskMapper.updateTmTask(task);
                if (res == 0) {
                    throw new RuntimeException("审核入库失败,修改任务状态未成功");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(DateUtils.getNowDate());
    }

    @Override
    public List<PurchasePartInfo> exportList(PurchasePartInfo bean) {
        return purchaseAccessoryMapper.exportList(bean);
    }

    @Override
    public List<PurchasePartDetails> inputExport(PurchasePartDetails bean) {
        return purchaseAccessoryMapper.inputExport(bean);
    }

    @Override
    public PurchasePartInfo getAcceptanceForm(Long taskId, String keyWord) {
        PurchasePartInfo purchasePartInfo = purchaseAccessoryMapper.selectPurchasePartInfoByTaskId(taskId);
        PurchasePartDetails purchasePartDetails = new PurchasePartDetails();
        purchasePartDetails.setTaskId(purchasePartInfo.getTaskId());
        purchasePartDetails.setKeyWord(keyWord);
        List<PurchasePartDetails> purchasePartDetailsList = purchaseAccessoryMapper.getAcceptanceForm(purchasePartDetails);
        purchasePartInfo.setPartDetailsList(purchasePartDetailsList);
        return purchasePartInfo;
    }

    @Override
    public List<PurchasePartDetails> warehousingEntry(PurchasePartDetails purchasePartDetails) {
        return purchaseAccessoryMapper.warehousingEntry(purchasePartDetails);
    }

    /**
     * 新购配件--采购单号编码生成规则
     */
    private String purchaseCodeRule() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String taskNum = taskMapper.selectTaskNumByMonths(nowDate, 67);
        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;
    }

}
