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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.domain.lease.LeaseOutSign;
import com.bonus.common.biz.enums.PartLeaseTaskStatusEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.ma.domain.PartType;
import com.bonus.material.part.domain.MaPartTypeKeeper;
import com.bonus.material.part.domain.PartLeaseDetails;
import com.bonus.material.part.domain.PartLeaseInfo;
import com.bonus.material.part.domain.vo.PartLeaseVo;
import com.bonus.material.part.mapper.PartLeaseMapper;
import com.bonus.material.part.service.PartLeaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author : 阮世耀
 * @version : 1.0
 * @PackagePath: com.bonus.material.lease.service.impl
 * @CreateTime: 2024-12-27  13:40
 * @Description: 描述
 */
@Service
@Slf4j
public class PartLeaseServiceImpl implements PartLeaseService {

    @Resource
    private PartLeaseMapper partLeaseMapper;

    /**
     * 查询配件领用信息列表
     *
     * @param partLeaseInfo 任务id
     */
    @Override
    public List<PartLeaseInfo> selectPartLeaseInfoList(PartLeaseInfo partLeaseInfo) {
        List<PartLeaseInfo> list = partLeaseMapper.selectPartLeaseInfoList(partLeaseInfo);
        if (CollectionUtil.isNotEmpty(list)) {
            String keyWord = partLeaseInfo.getKeyWord();
            // 如果关键字不为空，进行过滤
            if (!StringUtils.isBlank(keyWord)) {
                list = list.stream()
                        .filter(item -> containsKeyword(item, keyWord))
                        .collect(Collectors.toList());
            }
        }
        return list;
    }

    /**
     * 关键字搜索
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(PartLeaseInfo item, String keyWord) {
        return (item.getPartName() != null && item.getPartName().contains(keyWord)) ||
                (item.getCode() != null && item.getCode().contains(keyWord)) ||
                (item.getCreator() != null && item.getCreator().contains(keyWord)) ||
                (item.getAuditor() != null && item.getAuditor().contains(keyWord));
    }

    /**
     * 新增配件领用信息
     *
     * @param partLeaseInfo 任务id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPartLeaseInfo(PartLeaseInfo partLeaseInfo) {
        if (null == partLeaseInfo || null == partLeaseInfo.getPartLeaseDetailsList()) {
            throw new ServiceException("领用信息不能为空");
        }
        for (PartLeaseDetails partLeaseDetails : partLeaseInfo.getPartLeaseDetailsList()) {
            if (null == partLeaseDetails.getPartId() || null == partLeaseDetails.getPreNum() || null == partLeaseDetails.getStorageNum()) {
                throw new ServiceException("领用明细信息不能为空");
            }
            if (partLeaseDetails.getPreNum().compareTo(partLeaseDetails.getStorageNum()) > 0) {
                throw new ServiceException("领用数量不能大于库存数量");
            }
        }
        int thisMonthMaxOrder = partLeaseMapper.getMonthMaxOrderByDate(DateUtils.getCurrentYear(), DateUtils.getCurrentMonth());
        final String taskCode = genderTaskCode(thisMonthMaxOrder);
        partLeaseInfo.setCode(taskCode).setMonthOrder(thisMonthMaxOrder + 1).setCreator(SecurityUtils.getLoginUser().getUserid().toString())
                .setCreateTime(DateUtils.getNowDate());
        final int insertPartLeaseInfo = partLeaseMapper.insertPartLeaseInfo(partLeaseInfo);
        final int batchDetailsNum;
        if (0 < insertPartLeaseInfo) {
            for (PartLeaseDetails partLeaseDetails : partLeaseInfo.getPartLeaseDetailsList()) {
                partLeaseDetails.setTaskId(partLeaseInfo.getTaskId());
            }
            batchDetailsNum = partLeaseMapper.batchPartLeaseDetails(partLeaseInfo.getPartLeaseDetailsList());
        } else {
            throw new ServiceException("领用信息新增失败");
        }
        if (batchDetailsNum != partLeaseInfo.getPartLeaseDetailsList().size()) {
            throw new ServiceException("领用明细未全部新增完成,数据已回滚");
        }
        return insertPartLeaseInfo;
    }

    /**
     * 生成任务编号并构造Tm_Task任务对象
     * @param thisMonthMaxOrder 当月最大单号
     * @return 任务对象
     */
    private static String genderTaskCode(Integer thisMonthMaxOrder) {
        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        final Date nowDate = DateUtils.getNowDate();
        final String format = dateFormat.format(nowDate);
        final String result = format.replace("-", "");
        return MaterialConstants.PART_LEASE_TASK_TYPE_LEASE + result + String.format("-%03d", thisMonthMaxOrder + 1);
    }

    /**
     * 查询配件领用详情
     *
     * @param partLeaseDetails 任务id
     */
    @Override
    public PartLeaseVo selectPartLeaseDetailsList(PartLeaseDetails partLeaseDetails) {
        PartLeaseVo partLeaseVo = new PartLeaseVo();
        List<PartLeaseDetails> list = partLeaseMapper.selectPartLeaseDetailsList(partLeaseDetails);
        if (CollectionUtils.isNotEmpty(list)) {
            partLeaseVo.setDetailsList(list);
            PartLeaseDetails details = new PartLeaseDetails();
            String deptName = list.stream()
                    .map(PartLeaseDetails::getDeptName)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.joining(","));
            String sendDeptName = list.stream()
                    .map(PartLeaseDetails::getSendDeptName)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.joining(","));
            details.setDeptName(deptName);
            details.setSendDeptName(sendDeptName);
            partLeaseVo.setDetails(details);
            // 获取list中的制单人签名
            PartLeaseDetails partLeaseDetails1 = list.get(0);
            if (StringUtils.isNotBlank(partLeaseDetails1.getCreateSignUrl())) {
                if (!partLeaseDetails1.getCreateSignUrl().startsWith("http")) {
                    partLeaseDetails1.setCreateSignUrl("data:image/png;base64," + partLeaseDetails1.getCreateSignUrl());
                }
                LeaseOutSign leaseOutSign = new LeaseOutSign(partLeaseDetails1.getCreateSignType(),
                        partLeaseDetails1.getCreateSignUrl());
                partLeaseVo.setLeaseSignInfo(leaseOutSign);
            }
            // 根据list集合中的auditor进行分组，分别获取签名
            Map<String, List<PartLeaseDetails>> auditorMap = list.stream()
                    .filter(item -> StringUtils.isNotBlank(item.getAuditor()))
                    .collect(Collectors.groupingBy(PartLeaseDetails::getAuditor));
            List<LeaseOutSign> arrayList = new ArrayList<>();
            // 根据key获取auditorMap中的值，每个key只有获取一次值即可，转入到arrayList中
            for (String key : auditorMap.keySet()) {
                List<PartLeaseDetails> value = auditorMap.get(key);
                PartLeaseDetails partLeaseDetails2 = value.get(0);
                if (StringUtils.isNotBlank(partLeaseDetails2.getSignUrl())) {
                    if (!partLeaseDetails2.getSignUrl().startsWith("http")) {
                        partLeaseDetails2.setSignUrl("data:image/png;base64," + partLeaseDetails2.getSignUrl());
                    }
                    LeaseOutSign leaseOutSign = new LeaseOutSign(partLeaseDetails2.getSignType(),
                            partLeaseDetails2.getSignUrl());
                    arrayList.add(leaseOutSign);
                }
            }
            partLeaseVo.setApproveSignInfo(arrayList);
            // 获取库管签名
            String signId = partLeaseMapper.selectSignList(partLeaseDetails);
            if (StringUtils.isNotBlank(signId)) {
                // 根据id获取库管签名,将signId转换为集合
                List<String> signIdList = Arrays.asList(signId.split(","));
                List<LeaseOutSign> signList = partLeaseMapper.selectSignListInfo(signIdList);
                partLeaseVo.setKgSignInfo(signList);
            }
        }
        return partLeaseVo;
    }

    /**
     * 查询配件领用树结构列表
     * @param partType
     * @return
     */
    @Override
    public AjaxResult selectPartTreeList(PartType partType) {
        //获取当前用户ID
        Long userId = SecurityUtils.getLoginUser().getUserid();
        partType.setUserId(userId);
        List<PartType> list = new ArrayList<>();
        List<PartType> secondList = new ArrayList<>();
        List<PartType> thirdList = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>(2);
        //List<PartType> partTypeList = partLeaseMapper.selectPartTreeList(partType);
        List<PartType> partTypeList = partLeaseMapper.selectUserList(partType);
        if (!CollectionUtils.isEmpty(partTypeList)) {
            if ("1".equals(partType.getLevel())) {
                // 获取partTypeList中的level为1的数据
                for (PartType type : partTypeList) {
                    PartType type1 = new PartType();
                    type1.setId(type.getFirstId());
                    type1.setPaName(type.getPartType());
                    // 先判断list集合中是否包含该数据
                    if (!list.contains(type1)) {
                        list.add(type1);
                    }
                }
                return AjaxResult.success(list);
            }
            if ("2".equals(partType.getLevel()) && partType.getId() == null) {
                // 获取partTypeList中的level为2的数据
                if(partType.getFlag() == null) {
                    // 获取partTypeList中的level为2的数据
                    for (PartType type : partTypeList) {
                        PartType type1 = new PartType();
                        type1.setId(type.getSecondId());
                        type1.setPaName(type.getPartName());
                        type1.setSecondId(type.getSecondId());
                        type1.setSecondLevel(type.getSecondLevel());
                        type1.setThirdId(type.getThirdId());
                        type1.setThirdLevel(type.getThirdLevel());
                        type1.setStorageNum(type.getStorageNum());
                        type1.setUnitName(type.getUnitName());
                        type1.setPartName(type.getPartName());
                        // 先判断list集合中是否包含该数据
                        if (!list.contains(type1)) {
                            list.add(type1);
                        }
                    }
                    return AjaxResult.success(list);
                }else{
                    for (PartType type : partTypeList) {
                        PartType type1 = new PartType();
                        type1.setId(type.getSecondId());
                        type1.setPaName(type.getPaName());
                        type1.setSecondId(type.getSecondId());
                        type1.setSecondLevel(type.getSecondLevel());
                        type1.setThirdId(type.getThirdId());
                        type1.setThirdLevel(type.getThirdLevel());
                        type1.setStorageNum(type.getStorageNum());
                        type1.setUnitName(type.getUnitName());
                        type1.setPartName(type.getPartName());
                        // 先判断list集合中是否包含该数据
                        if (!list.contains(type1)) {
                            list.add(type1);
                        }
                    }
                    if (!CollectionUtils.isEmpty(list)) {
                        // 从list获取secondLevel为2的数据，并去重放到secondList中
                        for (PartType type : list) {
                            if ("2".equals(type.getSecondLevel())) {
                                PartType type1 = new PartType();
                                type1.setId(type.getSecondId());
                                type1.setPaName(type.getPartName());
                                if (!secondList.contains(type1)) {
                                    secondList.add(type1);
                                }
                            }
                            if ("3".equals(type.getThirdLevel())) {
                                PartType type1 = new PartType();
                                type1.setId(type.getThirdId());
                                type1.setPaName(type.getPaName());
                                type1.setLevel(type.getThirdLevel());
                                type1.setUnitName(type.getUnitName());
                                type1.setStorageNum(type.getStorageNum());
                                if (!thirdList.contains(type1)) {
                                    thirdList.add(type1);
                                }
                            }
                        }
                        map.put("secondList", secondList);
                        map.put("thirdList", thirdList);
                        return AjaxResult.success(map);
                    }
                }

            }
            if ("3".equals(partType.getLevel()) && partType.getId() == null) {
                // 获取partTypeList中的level为3的数据
                for (PartType type : partTypeList) {
                    PartType type1 = new PartType();
                    type1.setId(type.getThirdId());
                    type1.setPaName(type.getPaName());
                    type1.setStorageNum(type.getStorageNum());
                    type1.setUnitName(type.getUnitName());
                    // 先判断list集合中是否包含该数据
                    if (!list.contains(type1)) {
                        list.add(type1);
                    }
                }
                return AjaxResult.success(list);
            }
            if (partType.getId() != null) {
                List<PartType> partTypeList1 = partLeaseMapper.selectUserList(partType);
                if (!CollectionUtils.isEmpty(partTypeList1)) {
                    list.addAll(partTypeList1);
                }
            }
            if (!CollectionUtils.isEmpty(list)) {
                // 从list获取secondLevel为2的数据，并去重放到secondList中
                for (PartType type : list) {
                    if ("2".equals(type.getSecondLevel())) {
                        PartType type1 = new PartType();
                        type1.setId(type.getSecondId());
                        type1.setPaName(type.getPartName());
                        if (!secondList.contains(type1)) {
                            secondList.add(type1);
                        }
                    }
                    if ("3".equals(type.getThirdLevel())) {
                        PartType type1 = new PartType();
                        type1.setId(type.getThirdId());
                        type1.setPaName(type.getPaName());
                        type1.setLevel(type.getThirdLevel());
                        type1.setUnitName(type.getUnitName());
                        type1.setStorageNum(type.getStorageNum());
                        if (!thirdList.contains(type1)) {
                            thirdList.add(type1);
                        }
                    }
                }
                map.put("secondList", secondList);
                map.put("thirdList", thirdList);
                return AjaxResult.success(map);
            }
        }
        return AjaxResult.success(partTypeList);
    }

    /**
     * 审核配件领用任务
     * @param partLeaseInfo
     * @return
     */
    @Override
    @Transactional
    public AjaxResult auditPartLeaseInfo(PartLeaseInfo partLeaseInfo) {
        if (partLeaseInfo == null || CollectionUtils.isEmpty(partLeaseInfo.getPartLeaseDetailsList()) ||
                partLeaseInfo.getTaskStatus() == null || partLeaseInfo.getTaskId() == null) {
            return AjaxResult.error("配件领用审核信息不能为空");
        }
        String userId = SecurityUtils.getLoginUser().getUserid().toString();
        String createBy = null;
        PartLeaseInfo info = partLeaseMapper.selectPartLeaseInfoById(partLeaseInfo.getTaskId());
        if (info != null) {
            createBy = info.getCreator();
        }
        try {
            // 审核通过
            if (partLeaseInfo.getTaskStatus() == 1) {
                for (PartLeaseDetails partLeaseDetails : partLeaseInfo.getPartLeaseDetailsList()) {
                    // 修改详情表的状态
                    partLeaseDetails.setStatus(PartLeaseTaskStatusEnum.LEASE_TASK_TO_AUDIT.getStatus());
                    partLeaseDetails.setUpdateBy(userId);
                    partLeaseDetails.setUpdateTime(DateUtils.getNowDate());
                    int res = partLeaseMapper.updatePartLeaseDetails(partLeaseDetails);
                    if (res > 0) {
                        // 审核通过，扣减ma_part_type表库存
                        res = partLeaseMapper.updateMaTypeStockNum(partLeaseDetails);
                        if (res == 0) {
                            throw new ServiceException("配件库存不足");
                        }
                        // 增加个人库存
                        // 现根据人员以及配件id去查询，存在则更新，不存在则新增
                        partLeaseDetails.setCreateBy(StringUtils.isBlank(createBy) ? null : createBy);
                        partLeaseDetails.setCreateTime(DateUtils.getNowDate());
                        List<PartLeaseDetails> list = partLeaseMapper.selectPerson(partLeaseDetails);
                        if (CollectionUtils.isEmpty(list)) {
                            res = partLeaseMapper.insertPersonStockNum(partLeaseDetails);
                            if (res == 0) {
                                throw new ServiceException("个人库存新增失败");
                            }
                        } else {
                            res = partLeaseMapper.updatePersonStockNum(partLeaseDetails);
                            if (res == 0) {
                                throw new ServiceException("个人库存更新失败");
                            }
                        }
                    } else {
                        throw new ServiceException("领用信息审核失败");
                    }
                }
            } else if (partLeaseInfo.getTaskStatus() == 2) {
                for (PartLeaseDetails partLeaseDetails : partLeaseInfo.getPartLeaseDetailsList()) {
                    // 修改详情表的状态
                    partLeaseDetails.setStatus(PartLeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                    partLeaseDetails.setUpdateBy(userId);
                    partLeaseDetails.setUpdateTime(DateUtils.getNowDate());
                    int res = partLeaseMapper.updatePartLeaseDetails(partLeaseDetails);
                    if (res == 0) {
                        throw new ServiceException("领用信息审核失败");
                    }
                }
            }
            // 根据任务id查询详情状态，修改最外层任务状态
            PartLeaseDetails partLeaseDetails = new PartLeaseDetails();
            partLeaseDetails.setTaskId(partLeaseInfo.getTaskId());
            List<PartLeaseDetails> partLeaseDetailsByTaskId = partLeaseMapper.selectPartLeaseDetailsList(partLeaseDetails);
            // 将集合中的status取出
            List<Integer> statusList = partLeaseDetailsByTaskId.stream()
                    .map(PartLeaseDetails::getStatus)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(statusList)) {
                int publishedStatus = PartLeaseTaskStatusEnum.LEASE_TASK_TO_PUBLISHED.getStatus();
                int inProgressStatus = PartLeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus();
                boolean notContainsNoFinished =!statusList.contains(publishedStatus);
                boolean allReject = statusList.stream()
                        .allMatch(status -> status.equals(inProgressStatus));
                if (notContainsNoFinished && !allReject) {
                    partLeaseMapper.updateTaskStatus(partLeaseInfo.getTaskId().toString(), PartLeaseTaskStatusEnum.LEASE_TASK_TO_AUDIT.getStatus());
                } else if (notContainsNoFinished && allReject) {
                    partLeaseMapper.updateTaskStatus(partLeaseInfo.getTaskId().toString(), PartLeaseTaskStatusEnum.LEASE_TASK_IN_PROGRESS.getStatus());
                }
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult selectPartTreeListByLevel(PartType partType) {
        if (partType == null || partType.getId() == null) {
            return AjaxResult.error("参数不能为空");
        }
        List<PartType> list = new ArrayList<>();
        PartType type = partLeaseMapper.selectPartTreeListByLevel(partType);
        if (type != null) {
            type.setId(type.getParentId());
            PartType type1 = partLeaseMapper.selectPartTreeListByLevel(type);
            if (type1 != null) {
                list.add(type1);
                type1.setId(type1.getParentId());
                PartType type2 = partLeaseMapper.selectPartTreeListByLevel(type1);
                if (type2 != null) {
                    list.add(type2);
                }
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 新增库管员配置
     * @param typeKeepers
     * @return
     */
    @Override
    public AjaxResult insertTypeKeeper(MaPartTypeKeeper typeKeepers) {
        if (typeKeepers == null) {
            return AjaxResult.error("参数不能为空");
        }
        if (!CollectionUtils.isEmpty(typeKeepers.getTypeIds())) {
            for (Long typeId : typeKeepers.getTypeIds()) {
                // 先根据typeId查询库管员配置是否已经存在，存在则先删除
                typeKeepers.setTypeId(typeId);
                List<MaPartTypeKeeper> list = partLeaseMapper.selectTypeKeeperByTypeId(typeKeepers);
                if (!CollectionUtils.isEmpty(list)) {
                    for (MaPartTypeKeeper typeKeeper : list) {
                        partLeaseMapper.deleteTypeKeeper(typeKeeper);
                    }
                }
                typeKeepers.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                typeKeepers.setCreateTime(DateUtils.getNowDate());
                int res = partLeaseMapper.insertTypeKeeper(typeKeepers);
                if (res == 0) {
                    return AjaxResult.error("绑定失败，请联系管理员");
                }
            }
        }
        return AjaxResult.success("绑定成功");
    }

    /**
     * 解绑库管员配置
     * @param typeKeepers
     * @return
     */
    @Override
    public AjaxResult deleteTypeKeeper(List<MaPartTypeKeeper> typeKeepers) {
        if (CollectionUtils.isEmpty(typeKeepers)) {
            return AjaxResult.error("参数不能为空");
        }
        for (MaPartTypeKeeper typeKeeper : typeKeepers) {
            int res = partLeaseMapper.deleteTypeKeeper(typeKeeper);
            if (res == 0) {
                return AjaxResult.error("解绑失败，请联系管理员");
            }
        }
        return AjaxResult.success("解绑成功");
    }

    /**
     * 根据二级id查询三级列表
     * @param partType
     * @return
     */
    @Override
    public AjaxResult selectPartList(PartType partType) {
        List<PartType> list = partLeaseMapper.selectPartTreeList(partType);
        return AjaxResult.success(list);
    }
}
