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

import cn.hutool.core.collection.CollUtil;
import com.bonus.sgzb.base.api.domain.BackApplyInfo;
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.core.utils.StringUtils;
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.BackApplyMapper;
import com.bonus.sgzb.material.mapper.TaskMapper;
import com.bonus.sgzb.material.service.BackApplyService;
import com.bonus.sgzb.material.vo.TypeTreeBuild;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author hay
 * @date 2023/12/20 14:55
 */
@Service
public class BackApplyServiceImpl implements BackApplyService {

    @Autowired
    private BackApplyMapper backApplyMapper;

    @Autowired
    private TaskMapper tmTaskMapper;

    @Override
    public List<BackApplyInfo> getBackApplyList(BackApplyInfo bean) {
        Set<String> roles = SecurityUtils.getLoginUser().getRoles();
        if (roles.contains("admin")) {
            //管理员可以看到所有退料申请
            return backApplyMapper.getBackApplyListByAdmin1(bean);
        }
        //个人只能看到自己的申请的退料
        String username = SecurityUtils.getLoginUser().getUsername();
        bean.setCreateBy(username);
        return backApplyMapper.getBackApplyList(bean);
    }

    @Override
    public List<BackApplyInfo> getBackAuditList(BackApplyInfo bean) {
        Set<String> roles = SecurityUtils.getLoginUser().getRoles();
        Long companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
        if (roles.contains("admin")) {
            //管理员可以看到所有退料申请
            return backApplyMapper.getBackApplyListByAdmin(bean);
        }
        List<BackApplyInfo> backApplyInfos = new ArrayList<>();
        List<BackApplyInfo> backApplyListByAdmin = backApplyMapper.getBackApplyListByAdmin(bean);
        //机具分公司只能看到机具公司的退料
        if (CollUtil.isNotEmpty(backApplyListByAdmin)) {
            if (roles.contains("jjfgs") || Objects.equals(companyId, 101L)) {
                for (BackApplyInfo backApplyInfo : backApplyListByAdmin) {
                    if (StringUtils.hasText(backApplyInfo.getCompanyId()) && backApplyInfo.getCompanyId().contains(String.valueOf(companyId))) {
                        backApplyInfos.add(backApplyInfo);
                    }
                }
            }
        }
        //调试分公司只能看到调试公司的退料
        if (CollUtil.isNotEmpty(backApplyListByAdmin)) {
            if (roles.contains("tsfgs") || Objects.equals(companyId, 102L)) {
                for (BackApplyInfo backApplyInfo : backApplyListByAdmin) {
                    if (StringUtils.hasText(backApplyInfo.getCompanyId()) && backApplyInfo.getCompanyId().contains(String.valueOf(companyId))) {
                        backApplyInfos.add(backApplyInfo);
                    }
                }
            }
        }
        return backApplyInfos;
    }

    @Override
    public List<BackApplyInfo> getMaterialList(BackApplyInfo bean) {
        return backApplyMapper.getMaterialList(bean);
    }

    @Override
    public String genderBackCode() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String taskNum = backApplyMapper.selectTaskNumByMonth(nowDate, 36);
        if (StringHelper.isNotEmpty(taskNum)) {
            // 将字符串转换为整数
            int num = Integer.parseInt(taskNum);
            // 执行加一操作
            num++;
            // 将结果转换回字符串格式，并确保结果是四位数，不足四位则在前面补0
            taskNum = String.format("%04d", num);
        } else {
            taskNum = "0001";
        }
        String code = "T" + format + "-" + taskNum;
        return code;
    }

    @Override
    public int insertSelective(BackApplyInfo bean) {
        return backApplyMapper.insertTask(bean);
    }

    @Override
    public int insertTaskAgreement(BackApplyInfo bean) {
        return backApplyMapper.insertTaskAgreement(bean);
    }

    @Override
    public int insertBackApply(BackApplyInfo bean) {
        return backApplyMapper.insertBackApply(bean);
    }

    @Override
    public int upload(BackApplyInfo bean) {
        return backApplyMapper.upload(bean);
    }

    @Override
    public int uploadByCq(BackApplyInfo bean) {
        return backApplyMapper.uploadByCq(bean);
    }

    @Override
    public List<BackApplyInfo> getView(BackApplyInfo bean) {
        Long companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
        if (StringUtils.isNotEmpty(bean.getBadId())) {
            String badId = bean.getBadId();
            String[] split = badId.split(",");
            bean.setSplit(split);
        }
        if (companyId != null) {
            bean.setCompanyId(companyId.toString());
        }
        List<BackApplyInfo> view = backApplyMapper.getView(bean);
        return getMaTypeDetails(view);
    }

    private List<BackApplyInfo> getMaTypeDetails(List<BackApplyInfo> view) {
        if (view.size() > 0) {
            for (BackApplyInfo backApplyInfo : view) {
                List<MachinePart> machineParts = new ArrayList<>();
                List<TmTask> typeIds = tmTaskMapper.getMaTypeDetails(backApplyInfo);
                typeIds.removeIf(item -> item == null);
                for (TmTask typeId : typeIds) {
                    MachinePart machinePart = tmTaskMapper.getMachineParts(typeId);
                    machinePart.setPartNum((Double.parseDouble(typeId.getPartNum()) * Double.parseDouble(backApplyInfo.getPreNum())));
                    machineParts.add(machinePart);
                }
                backApplyInfo.setMaTypeDetails(machineParts);
            }
        }
        return view;
    }

    @Override
    public List<BackApplyInfo> getViewByApply(BackApplyInfo bean) {
        List<BackApplyInfo> viewByApply = backApplyMapper.getViewByApply(bean);
        if (bean.getFlag() == 1) {
            List<BackApplyInfo> backApplyInfos = new ArrayList<>();
            for (BackApplyInfo backApplyInfo : viewByApply) {
                if ("2".equals(backApplyInfo.getStatus()) || "4".equals(backApplyInfo.getStatus())) {
                    backApplyInfos.add(backApplyInfo);
                }
            }
            return backApplyInfos;
        }
        return viewByApply;

    }

    @Override
    public AjaxResult setModify(List<BackApplyInfo> bean) {
        if (CollUtil.isNotEmpty(bean)) {
            for (BackApplyInfo backApplyInfo : bean) {
                if (!StringUtils.isEmpty(backApplyInfo.getDetailsId()) && !StringUtils.isEmpty(backApplyInfo.getNum())) {
                    String[] detailsId = backApplyInfo.getDetailsId().split(",");
                    String[] num = backApplyInfo.getNum().split(",");
                    for (int i = 0; i < detailsId.length; i++) {
                        String detailsIds = detailsId[i];
                        String nums = num[i];
                        int re = backApplyMapper.setModify(detailsIds, nums);
                        if (re < 1) {
                            return AjaxResult.error("修改失败");
                        }
                    }
                } else {
                    return AjaxResult.error("未获取到详情id或退料数量");
                }
            }
        } else {
            return AjaxResult.error("未获取到参数");
        }

        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult del(BackApplyInfo bean) {
        int re = backApplyMapper.del(bean);
        if (re > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    @Override
    public AjaxResult audit(BackApplyInfo bean) {
        Set<String> roles = null;
        Long userid = null;
        Long companyId = null;
        try {
            roles = SecurityUtils.getLoginUser().getRoles();
            userid = SecurityUtils.getLoginUser().getUserid();
            companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
        } catch (NullPointerException e) {
            e.printStackTrace();
            return AjaxResult.error("获取用户信息失败:{}", e);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int num = 0;
        if (!StringUtils.isEmpty(bean.getIds())) {
            String[] ids = bean.getIds().split(",");
            for (String id : ids) {
                bean.setId(Long.valueOf(id));
                if (roles != null && roles.contains("admin")) {
                    if (userid != null) {
                        bean.setCreateBy(userid.toString());
                    }
                    bean.setStatus("1");
                    int i = auditDetails(bean);
                    if (i == 0) {
                        return AjaxResult.error("审核失败");
                    }
                }
                if ((roles != null && roles.contains("jjfgs")) || (companyId != null && companyId.equals(101L))) {
                    if (companyId != null) {
                        bean.setCompanyId(companyId.toString());
                    }
                    if (userid != null) {
                        bean.setCreateBy(userid.toString());
                    }
                    bean.setStatus("1");
                    int i = auditDetails(bean);
                    if (i == 0) {
                        return AjaxResult.error("审核失败");
                    }
                }
                if ((roles != null && roles.contains("tsfgs")) || (companyId != null && companyId.equals(102L))) {
                    if (companyId != null) {
                        bean.setCompanyId(companyId.toString());
                    }
                    if (userid != null) {
                        bean.setCreateBy(userid.toString());
                    }
                    bean.setStatus("3");
                    int i = auditDetails(bean);
                    if (i == 0) {
                        return AjaxResult.error("审核失败");
                    }
                }
                List<Integer> taskIdById = backApplyMapper.getTaskIdById(bean);
                if (CollUtil.isNotEmpty(taskIdById)) {
                    for (Integer taskId : taskIdById) {
                        if (taskId == 1 || taskId == 3) {
                            num++;
                        }
                    }
                }
                if (num == taskIdById.size()) {
                    bean.setTaskStatus("38");
                    backApplyMapper.updateTmTask(bean);
                }
            }
            return AjaxResult.success("审核成功");
        } else {
            return AjaxResult.error("审核失败,未获取到参数");
        }
    }

    private int auditDetails(BackApplyInfo bean) {
        int re = 0;
        if (CollUtil.isNotEmpty(bean.getBackApplyDetails())) {
            List<BackApplyInfo> backApplyDetails = bean.getBackApplyDetails();
            for (BackApplyInfo backApplyDetail : backApplyDetails) {
                bean.setAuditNum(backApplyDetail.getNum());
                bean.setTypeId(backApplyDetail.getTypeId());
                re = backApplyMapper.audit(bean);
            }
        }
        return re;
    }

    @Override
    public AjaxResult refuse(BackApplyInfo bean) {
        if (SecurityUtils.getLoginUser() != null) {
            Set<String> roles = SecurityUtils.getLoginUser().getRoles();
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            Long companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();

            int num = 0;
            if (!StringUtils.isEmpty(bean.getIds())) {
                String[] ids = bean.getIds().split(",");
                for (int i = 0; i < ids.length; i++) {
                    String id = ids[i];
                    bean.setId(Long.valueOf(id));
                    if (userId == 1) {
                        bean.setCreateBy(userId.toString());
                        bean.setStatus("2");
                        int re = backApplyMapper.refuse(bean);
                        if (re < 1) {
                            return AjaxResult.error("驳回失败");
                        }
                    }
                    if (roles.contains("jjfgs")) {
                        bean.setCompanyId(companyId.toString());
                        bean.setCreateBy(userId.toString());
                        bean.setStatus("2");
                        int re = backApplyMapper.refuse(bean);
                        if (re < 1) {
                            return AjaxResult.error("驳回失败");
                        }
                    }
                    if (roles.contains("tsfgs")) {
                        bean.setCompanyId(companyId.toString());
                        bean.setCreateBy(userId.toString());
                        bean.setStatus("4");
                        int re = backApplyMapper.refuse(bean);
                        if (re < 1) {
                            return AjaxResult.error("驳回失败");
                        }
                    }
                    List<Integer> taskIdById = backApplyMapper.getTaskIdById(bean);
                    if (CollUtil.isNotEmpty(taskIdById)) {
                        for (Integer taskId : taskIdById) {
                            if (taskId == 2 || taskId == 4) {
                                num++;
                            }
                        }
                    }
                    if (num > 0) {
                        bean.setTaskStatus("101");
                        backApplyMapper.updateTmTask(bean);
                    }
                }
            }
            return AjaxResult.success("驳回成功");
        } else {
            return AjaxResult.error("驳回失败,未获取到参数");
        }
    }

    @Override
    public AjaxResult getUseTypeTree(BackApplyInfo bean) {
        List<TypeTreeNode> groupList = new ArrayList<>();
        List<TypeTreeNode> list = new ArrayList<>();
        try {
            list = backApplyMapper.getUseTypeTree(bean);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TypeTreeBuild treeBuild = new TypeTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            AjaxResult.error("类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public List<BackApplyInfo> exportList(BackApplyInfo bean) {
        return backApplyMapper.exportList(bean);
    }

    @Override
    public int delApply(BackApplyInfo bean) {
        return backApplyMapper.delApply(bean);
    }

    @Override
    public List<BackApplyInfo> selectIdByTaskId(Integer taskId) {
        return backApplyMapper.selectIdByTaskId(taskId);
    }

    @Override
    public int getUseNumByTypeId(String typeId) {
        int manageType = backApplyMapper.getManageType(typeId);
        if (manageType == 0) {
            // 编码入库的机具
            return backApplyMapper.getUseNumByTypeId(typeId);
        } else {
            // 数量入库的机具
            int leaseOutNum = backApplyMapper.getLeaseOutNum(typeId);
            int backCheckNum = backApplyMapper.getbackCheckNum(typeId);
            return leaseOutNum - backCheckNum;
        }
    }

    /**
     * 退料批量审核-审核(web)
     * @param dto
     * @return
     */
    @Override
    public AjaxResult auditAll(BackApplyDto dto) {
        Set<String> roles = null;
        Long userid = null;
        Long companyId = null;
        try {
            roles = SecurityUtils.getLoginUser().getRoles();
            userid = SecurityUtils.getLoginUser().getUserid();
            companyId = SecurityUtils.getLoginUser().getSysUser().getCompanyId();
        } catch (NullPointerException e) {
            e.printStackTrace();
            return AjaxResult.error("获取用户信息失败:{}", e);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CollectionUtils.isNotEmpty(dto.getBackApplyList())) {
            for (BackApplyListDto backApplyListDto : dto.getBackApplyList()) {
                dto.setId(backApplyListDto.getId());
                if (roles != null && roles.contains("admin")) {
                    if (userid != null) {
                        dto.setCreateBy(userid.toString());
                    }
                    dto.setStatus("1");
                    int i = auditAllDetails(dto);
                    if (i == 0) {
                        return AjaxResult.error("审核失败");
                    }
                }
                if (roles != null && roles.contains("jjfgs")) {
                    if (companyId != null) {
                        dto.setCompanyId(companyId.toString());
                    }
                    if (userid != null) {
                        dto.setCreateBy(userid.toString());
                    }
                    dto.setStatus("1");
                    int i = auditAllDetails(dto);
                    if (i == 0) {
                        return AjaxResult.error("审核失败");
                    }
                }
                if (roles != null && roles.contains("tsfgs")) {
                    if (companyId != null) {
                        dto.setCompanyId(companyId.toString());
                    }
                    if (userid != null) {
                        dto.setCreateBy(userid.toString());
                    }
                    dto.setStatus("3");
                    int i = auditAllDetails(dto);
                    if (i == 0) {
                        return AjaxResult.error("审核失败");
                    }
                }
                int num = 0;
                List<Integer> taskIdById = backApplyMapper.getTaskIdByIdAll(dto);
                if (CollUtil.isNotEmpty(taskIdById)) {
                    for (Integer taskId : taskIdById) {
                        if (taskId == 1 || taskId == 3) {
                            num++;
                        }
                    }
                }
                //审核成功，赋值任务状态38
                if (num == taskIdById.size()) {
                    dto.setTaskStatus("38");
                    backApplyMapper.updateTmTaskAll(dto);
                }
            }
            return AjaxResult.success("审核成功");
        } else {
            return AjaxResult.error("审核失败,未获取到参数");
        }
    }

    private int auditAllDetails(BackApplyDto dto) {
        int re = 0;
        if (CollUtil.isNotEmpty(dto.getBackApplyList())) {
            for (BackApplyListDto backApplyListDto : dto.getBackApplyList()) {
                for (BackApplyInfo backApplyDetail : backApplyListDto.getBackApplyDetails()) {
                    dto.setInnerId(backApplyListDto.getId());
                    dto.setAuditNum(backApplyDetail.getPreNum());
                    dto.setTypeId(backApplyDetail.getTypeId());
                    re = backApplyMapper.auditAll(dto);
                }
            }
        }
        return re;
    }

}
