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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.bonus.sgzb.base.api.domain.*;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.mapper.BackRecordMapper;
import com.bonus.sgzb.material.mapper.LeaseRecordMapper;
import com.bonus.sgzb.material.mapper.WorkSiteDirectManageMapper;
import com.bonus.sgzb.material.service.*;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author：梁超
 * @date：2024/3/4 - 14:50
 */
@Service
@Slf4j
public class WorkSiteDirectManageImpl implements WorkSiteDirectManageService {

    @Resource
    private WorkSiteDirectManageMapper workSiteDirectManageMapper;
    @Resource
    private TaskService tmTaskService;

    @Resource
    private BackApplyService backApplyService;

    @Resource
    private BackRecordMapper backRecordMapper;

    @Resource
    private ApplyInfoService applyInfoService;
    @Resource
    private LeaseRecordMapper leaseRecordMapper;

    @Override
    public List<SltAgreementInfo> getUseringData(SltAgreementInfo sltAgreementInfo) {
        return workSiteDirectManageMapper.getUseringData(sltAgreementInfo);
    }

    @Override
    @Transactional
    public int saveDirectApplyInfo(DirectApplyInfo directApplyInfo) {
        return workSiteDirectManageMapper.saveDirectApplyInfo(directApplyInfo);
    }

    @Override
    @Transactional
    public int saveDirectApplyDetails(DirectApplyDetails directApplyDetail) {
        return workSiteDirectManageMapper.saveDirectApplyDetails(directApplyDetail);
    }

    @Override
    public int refuseDirectApplyInfo(DirectApplyInfo directApplyInfos) {
        return workSiteDirectManageMapper.refuseDirectApplyInfo(directApplyInfos);
    }

    @Override
    public List<DirectApplyInfo> getList(DirectApplyInfo directApplyInfo) {
        return workSiteDirectManageMapper.getList(directApplyInfo);
    }

    @Override
    public String genderLeaseCode() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String format = simpleDateFormat.format(date);
        List<DirectApplyInfo> list = workSiteDirectManageMapper.getListAll();
        int i = list.size() + 1;
        String code = "ZZ" + format + "-" + list.size() + i;
        return code;
    }

    @Override
    public DirectApplyInfo getDirectApplyInfoById(String id) {
        return workSiteDirectManageMapper.getDirectApplyInfoById(id);
    }

    @Override
    public int insertTmTask(TmTask bean) {
        int res = 0;
        if (StringUtils.isNull(bean)) {
            return res;
        }
        // 创建任务
        int i = tmTaskService.insertSelective(bean);
        if (i < 1) {
            return res;
        } else {
            res = 1;
            return res;
        }
    }

    @Override
    public int insertAgreement(TmTask task) {
        int res = 0;
        boolean b = tmTaskService.insertAgreement(task) > 0;
        if (b) {
            res = 1;
        }
        return res;
    }

    @Override
    public int insertApplyInfoAndDetails(TmTask task) {
        int res = 0;
        if (task.getLeaseApplyInfo() != null) {
            if (CollUtil.isEmpty(task.getLeaseApplyDetails())) {
                return res;
            }
            if (StringUtils.isNull(task.getLeaseApplyInfo())) {
                return res;
            }

            // 获取任务编号
            String taskId = task.getId();
            List<List<LeaseApplyDetails>> deviceByCompanyList = CollUtil.groupByField(task.getLeaseApplyDetails(), "companyId");
            // 对拆分后的集合进行each遍历
            for (List<LeaseApplyDetails> leaseApplyDetailsList : deviceByCompanyList) {
                // 判断拆分后的集合内是否有数据
                if (CollUtil.isNotEmpty(leaseApplyDetailsList)) {
                    // 对领料任务表的对象做数据处理
                    LeaseApplyInfo leaseApplyInfo = task.getLeaseApplyInfo();
                    leaseApplyInfo.setCode(task.getCode()); // 创建领料单号
                    leaseApplyInfo.setTaskId(Integer.valueOf(taskId)); // 设置任务ID
                    leaseApplyInfo.setCompanyId(leaseApplyDetailsList.get(0).getCompanyId()); // 设置设备所属分公司,用于交给哪家审核
                    leaseApplyInfo.setType("2"); // 设置审批层级，先固定2层，后期根据接口传入Type区分来源设定
                    leaseApplyInfo.setStatus("1");  //设置为分公司审核通过
                    leaseApplyInfo.setLeaseType("0");  //设置为工程租赁
                    // 创建领料任务，返回领料任务编号
                    boolean addLeaseTaskResult = workSiteDirectManageMapper.insertSelective(leaseApplyInfo) > 0;
                    // 领料任务创建完成，进行领料任务明细插入
                    if (addLeaseTaskResult) {
                        // 领料任务编号
                        Integer leaseTaskId = leaseApplyInfo.getId();
                        ArrayList<Integer> ids = new ArrayList();
                        if (StringUtils.isNotNull(leaseTaskId)) {
                            for (LeaseApplyDetails leaseApplyDetails : leaseApplyDetailsList) {
                                leaseApplyDetails.setParenntId(leaseTaskId); // 设置领料任务ID
                                ids.add(leaseApplyDetails.getId());
                            }
                            // 插入领料任务明细
                            boolean addLeaseTaskDetailsResult = workSiteDirectManageMapper.batchInsert(leaseApplyDetailsList) > 0;
                            if (addLeaseTaskDetailsResult) {
                                System.out.println("领料任务创建成功");
                                workSiteDirectManageMapper.batchDel(ids);
                            } else {
                                return res;
                            }
                        } else {
                            return res;
                        }
                    } else {
                        return res;
                    }
                }
            }
            res = 1;
            return res;
        } else {
            return res;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertLeaseOutDetail(List<LeaseOutDetails> leaseOutDetails, TmTask lTask) {
        int res = 0;
        String maStatus = "15";
        double outNum = 0.1;
        if (StringUtils.isNull(leaseOutDetails)) {
            log.info("领料出库失败,请检查参数是否填写完整!");
            return res;
        }
        for (LeaseOutDetails leaseOutDetail : leaseOutDetails) {
            if (!(Objects.equals(Integer.valueOf(0), leaseOutDetail.getMaId()) || leaseOutDetail.getMaId() == null)) {
                String status = workSiteDirectManageMapper.getMachineStatus(leaseOutDetail);
                if (!maStatus.equals(status)) {
                    log.info("领料出库失败,该设备不是在库状态！");
                    return res;
                }
            }
            // 首先更新领料任务详情表的领料数及状态
            int updateLeaseApplyDetailsOutNum = workSiteDirectManageMapper.updateLeaseApplyDetailsOutNum(leaseOutDetail);
            if (updateLeaseApplyDetailsOutNum < 1) {
                return res;
            }
            // 插入领料出库明细表
            int insertSelectiveNum = workSiteDirectManageMapper.insertLeaseOutDetails(leaseOutDetail);
            if (insertSelectiveNum < 1) {
                return res;
            }
            // 更新 (ma_machine 设备表)的状态
            workSiteDirectManageMapper.updateMaMachineStatus(leaseOutDetail);

            int insSltInfoNum = insSltInfo(lTask.getAgreementId().toString(), leaseOutDetail);
            if (insSltInfoNum < 1) {
                return res;
            }
        }
        res = 1;
        return res;
    }

    private int insSltInfo(String agreementId, LeaseOutDetails leaseOutDetail) {
        MaType ma = leaseRecordMapper.getMaType(leaseOutDetail.getTypeId());
        return leaseRecordMapper.insSltInfo(leaseOutDetail, agreementId, ma);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBackApplyInfoAndDetails(BackApplyInfo bean) {
        int res = 0;
        boolean addLeaseTaskResult = false;
        Long backApplyInfoId = 0L;
        try {
            if (bean.getTaskId() != null) {
                if (bean.getBackApplyInfo() != null) {
                    if (CollUtil.isEmpty(bean.getBackApplyDetails())) {
                        return res;
                    }

                    Integer taskId = bean.getTaskId();
                    // 根据设备所属分公司拆分集合
                    List<List<BackApplyInfo>> backApplyInfoList = CollUtil.groupByField(bean.getBackApplyDetails(), "companyId");
                    // 判断拆分后的集合内是否有数据
                    if (CollUtil.isNotEmpty(backApplyInfoList)) {
                        // 对拆分后的集合进行each遍历
                        for (List<BackApplyInfo> leaseApplyDetailsList : backApplyInfoList) {
                            BackApplyInfo backApplyInfo1 = leaseApplyDetailsList.get(0);
                            // 对领料任务表的对象做数据处理
                            BackApplyInfo backApplyInfo = bean.getBackApplyInfo();
                            // 创建领料单号
                            backApplyInfo.setCode(bean.getCode());
                            // 设置任务ID
                            backApplyInfo.setTaskId(taskId);
                            // 设置设备所属分公司,用于交给哪家审核
                            backApplyInfo.setCompanyId(backApplyInfo1.getCompanyId());
                            // 创建领料任务，返回领料任务编号
                            addLeaseTaskResult = backApplyService.insertBackApply(backApplyInfo) > 0;
                            // 领料任务编号
                            backApplyInfoId = backApplyInfo.getId();

                            // 领料任务创建完成，进行领料任务明细插入
                            if (addLeaseTaskResult) {
                                if (StringUtils.isNotNull(backApplyInfoId)) {
                                    for (BackApplyInfo leaseApplyDetails : leaseApplyDetailsList) {
                                        //设置领料任务ID
                                        leaseApplyDetails.setId(backApplyInfoId);
                                        leaseApplyDetails.setNum(leaseApplyDetails.getDirectNum().toString());
                                        leaseApplyDetails.setAuditNum(leaseApplyDetails.getDirectNum().toString());
                                        // 插入领料任务明细
                                        boolean addLeaseTaskDetailsResult = backApplyService.upload(leaseApplyDetails) > 0;
                                        if (!addLeaseTaskDetailsResult) {
                                            log.info("退料任务创建成功，但退料任务明细插入失败");
                                            return res;
                                        }
                                    }
                                } else {
                                    log.info("退料任务编号为空");
                                    return res;
                                }
                            } else {
                                log.info("创建退料任务失败,或退料明细为空");
                                return res;
                            }
                        }
                    } else {
                        log.info("创建任务失败，缺少数据");
                        return res;
                    }
                } else {
                    log.info("创建任务失败");
                    return res;
                }
            } else {
                log.info("创建任务失败");
                return res;
            }
        } catch (Exception e) {
            log.info("创建任务失败");
            return res;
        }
        res = 1;
        return res;
    }

    @Override
    public int insertTmTaskByBackInfo(BackApplyInfo backApplyInfo) {
        int res = 0;
        if (StringUtils.isNull(backApplyInfo)) {
            return res;
        }
        // 创建任务
        int i = tmTaskService.insertTmTaskByBackInfo(backApplyInfo);
        if (i < 1) {
            return res;
        } else {
            res = 1;
            return res;
        }
    }

    @Override
    public int insertAgreementByBackInfo(BackApplyInfo backApplyInfo) {
        return tmTaskService.insertAgreementByBackInfo(backApplyInfo);
    }

    @Override
    public int insertBackCheckDetails(List<BackApplyInfo> backApplyDetails) {
        //插入back_check_details
        return insertBcd(backApplyDetails);
    }

    @Override
    public DirectApplyInfo getInfoById(SltAgreementInfo sltAgreementInfo) {
        DirectApplyInfo directApplyInfo = workSiteDirectManageMapper.getInfoById(sltAgreementInfo);
        List<DirectApplyDetails> detailById = workSiteDirectManageMapper.getDetailById(sltAgreementInfo);
        directApplyInfo.setDirectApplyDetails(detailById);
        return directApplyInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int passDirectApplyInfoDetails(DirectPassApplyInfoDetails directApplyInfoDetails) {
        int res = 0;
        try {
            // 修改状态为通过
            res = updateDirectApplyInfo(directApplyInfoDetails);
            if (res == 0) {
                throw new RuntimeException("updateDirectApplyInfo异常");
            }

            //创建领料信息和详情
            res = createLeaseInfo(directApplyInfoDetails);
            if (res == 0) {
                throw new RuntimeException("createLeaseInfo异常");
            }

            //创建退料信息和详情
            res = createBackInfo(directApplyInfoDetails);
            if (res == 0) {
                throw new RuntimeException("createBackInfo异常");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    private int createBackInfo(DirectPassApplyInfoDetails directApplyInfoDetails) {
        int res = 0;
        try {
            BackApplyInfo backApplyInfo = directApplyInfoDetails.getBackApplyInfo();
            // 创建退料任务(1、创建tm_task )
            res = createTmTaskByBackInfo(backApplyInfo);
            if (res == 0) {
                throw new RuntimeException("createBackTmTask异常");
            }
            //2.创建协议tm_task_agreement
            res = createAgreementByBackInfo(backApplyInfo);
            if (res == 0) {
                throw new RuntimeException("createBackAgreement异常");
            }
            // 3、创建back_apply_info和back_apply_details和出库记录back_check_details和计算结算数据
            res = createtBackApplyInfoAndDetails(backApplyInfo);
            if (res == 0) {
                throw new RuntimeException("createBackApplyInfoAndDetails异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;

    }

    private int createtBackApplyInfoAndDetails(BackApplyInfo backApplyInfo) {
        int res = 0;
        //新增退料信息和详情（back_apply_info、back_apply_details）
        res = insertBackApplyInfoAndDetails(backApplyInfo);
        if (res == 0) {
            return res;
        }

        List<BackApplyInfo> backApplyDetails = backApplyInfo.getBackApplyDetails();
        if (CollUtil.isEmpty(backApplyDetails)) {
            return res;
        }
        //新增退料核查（back_check_details）
        Integer taskId = backApplyInfo.getTaskId();
        List<BackApplyInfo> backApplyInfoList = backApplyService.selectIdByTaskId(taskId);
        List<BackApplyInfo> list = new ArrayList();
        for (BackApplyInfo backApplyInfo1 : backApplyDetails) {
            BackApplyInfo backCheckDetails = new BackApplyInfo();
            for (BackApplyInfo backApplyInfo2 : backApplyInfoList) {
                if (backApplyInfo1.getCompanyId().equals(backApplyInfo2.getCompanyId())) {
                    backCheckDetails.setParentId(backApplyInfo2.getId().intValue());
                    backCheckDetails.setTypeId(backApplyInfo1.getTypeId());
                    backCheckDetails.setMaId(backApplyInfo1.getMaId());
                    backCheckDetails.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                    backCheckDetails.setBackNum(backApplyInfo1.getDirectNum());
                }
            }
            list.add(backCheckDetails);
        }
        res = insertBackCheckDetails(list);
        if (res == 0) {
            return res;
        }
        for (BackApplyInfo applyInfo : list) {
            List<BackApplyInfo> allList = backRecordMapper.getAllList(applyInfo);
            if (allList != null && allList.size() > 0) {
                res = updateSlt(applyInfo, allList);
                if (res == 0) {
                    return res;
                }
            }
        }
        return res;
    }

    private int updateSlt(BackApplyInfo record, List<BackApplyInfo> hgList) {
        for (BackApplyInfo bean : hgList) {
            List<SltAgreementInfo> infoList = backRecordMapper.getStlInfo(bean);
            if (infoList.size() > 0) {
                Double backNum = Double.valueOf(bean.getBackNum());
                for (SltAgreementInfo info : infoList) {
                    Double num = Double.valueOf(info.getNum());
                    if (backNum.equals(num)) {
                        backRecordMapper.updateStlInfo(info, record);
                        break;
                    } else if (backNum > num) {
                        backNum = backNum - num;
                        backRecordMapper.updateStlInfo(info, record);
                    } else if (backNum < num) {
                        Double many = num - backNum;
                        backRecordMapper.updateStlInfoTwo(info, record, backNum);
                        backRecordMapper.insStlInfoTwo(info, many);
                        break;
                    }
                }
            } else {
                return 0;
            }
        }
        return 1;
    }

    private int createAgreementByBackInfo(BackApplyInfo backApplyInfo) {
        int res = 0;
        res = insertAgreementByBackInfo(backApplyInfo);
        if (res == 0) {
            return res;
        }
        return res;
    }

    private int createTmTaskByBackInfo(BackApplyInfo backApplyInfo) {
        int res = 0;
        if (backApplyInfo == null) {
            return res;
        }
        // 生成退料code
        String tcode = tmTaskService.genderBackCode();
        backApplyInfo.setCode(tcode);
        //创建退料任务（tm_task）
        backApplyInfo.setTaskType(36);
        backApplyInfo.setTaskStatus("40");
        res = insertTmTaskByBackInfo(backApplyInfo);
        if (res == 0) {
            return res;
        }
        return res;
    }

    private int createLeaseInfo(DirectPassApplyInfoDetails directApplyInfoDetails) {
        int res = 0;
        try {
            TmTask lTask = directApplyInfoDetails.getLeaseApplyInfo();
            // 创建领料任务(1、创建tm_task )
            int leaseTaskId = createTmTask(lTask, "1");
            if (leaseTaskId == 0) {
                throw new RuntimeException("createLeaseTmTask异常");
            }
            //2.创建协议tm_task_agreement
            lTask.setId(leaseTaskId + "");
            res = createAgreementInfo(lTask);
            if (res == 0) {
                throw new RuntimeException("createAgreementInfo异常");
            }
            // 3、创建lease_apply_info和lease_apply_details和出库记录lease_out_details
            res = createLeaseDetails(lTask);
            if (res == 0) {
                throw new RuntimeException("createLeaseDetails异常");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return res;

    }

    private int createLeaseDetails(TmTask lTask) {
        int res = 0;
        //新增领料信息和详情（lease_apply_info、lease_apply_details）
        int res3 = insertApplyInfoAndDetails(lTask);
        if (res3 == 0) {
            return res;
        }

        List<LeaseApplyDetails> leaseApplyDetails = lTask.getLeaseApplyDetails();
        if (CollUtil.isEmpty(leaseApplyDetails)) {
            return res;
        }
        List<LeaseApplyInfo> leaseApplyInfoList = applyInfoService.selectIdByTaskId(Integer.parseInt(lTask.getId()));
        List<LeaseOutDetails> list = new ArrayList();
        for (LeaseApplyDetails leaseApplyDetail : leaseApplyDetails) {
            LeaseOutDetails leaseOutDetails = new LeaseOutDetails();
            for (LeaseApplyInfo leaseApplyInfo : leaseApplyInfoList) {
                if (leaseApplyInfo.getCompanyId().equals(leaseApplyDetail.getCompanyId())) {
                    leaseOutDetails.setParentId(leaseApplyInfo.getId());
                }
            }
            leaseOutDetails.setTypeId(leaseApplyDetail.getTypeId());
            leaseOutDetails.setMaId(leaseApplyDetail.getMaId());
            leaseOutDetails.setOutNum(leaseApplyDetail.getPreNum());
            leaseOutDetails.setCompanyId(leaseApplyDetail.getCompanyId());
            list.add(leaseOutDetails);
        }
        // 新增领料出库记录
        res = insertLeaseOutDetail(list, lTask);
        if (res == 0) {
            return res;
        }
        return res;

    }

    private int createAgreementInfo(TmTask task) {
        //任务与协议建立关联关系 (tm_task_agreement)
        int res = 0;
        try {
            res = insertAgreement(task);
            if (res == 0) {
                throw new RuntimeException("insertAgreement异常");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    private int createTmTask(TmTask task, String taskType) {
        int taskId = 0;
        int res = 0;
        try {
            if ("1".equals(taskType)) {
                // 生成领料code
                String lcode = tmTaskService.genderLeaseCode();
                if (StringUtils.isEmpty(lcode)) {
                    return res;
                }
                task.setCode(lcode);
                task.setTaskStatus(35);
                // 创建领料任务（tm_task）
                res = insertTmTask(task);
                if (res == 0) {
                    throw new RuntimeException("insertTmTask异常");
                }
                taskId = Integer.valueOf(task.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return taskId;

    }

    private int updateDirectApplyInfo(DirectPassApplyInfoDetails directApplyInfoDetails) {
        int res = 0;
        if (StringUtils.isNotBlank(directApplyInfoDetails.getId())) {
            DirectApplyInfo directApplyInfos = getDirectApplyInfoById(directApplyInfoDetails.getId());
            directApplyInfos.setStatus("1");
            directApplyInfos.setAuditor(SecurityUtils.getLoginUser().getUsername());
            directApplyInfos.setAuditTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            res = refuseDirectApplyInfo(directApplyInfos);
        } else {
            return res;
        }
        return res;
    }

    public int insertBcd(List<BackApplyInfo> backApplyDetails) {
        int res = 0;
        for (BackApplyInfo backApplyDetail : backApplyDetails) {
            backApplyDetail.setBackStatus("1");
            res = backRecordMapper.insertCheckDetails(backApplyDetail);
        }
        return res;
    }
}
