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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.domain.lease.LeaseApplyInfo;
import com.bonus.common.biz.enums.HttpCodeEnum;
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.material.lease.domain.vo.LeaseApplyRequestVo;
import com.bonus.material.lease.domain.vo.LeaseOutVo;
import com.bonus.material.lease.mapper.LeaseApplyDetailsMapper;
import com.bonus.material.lease.mapper.LeaseApplyInfoMapper;
import com.bonus.material.ma.domain.Type;
import com.bonus.material.ma.domain.vo.MachineVo;
import com.bonus.material.ma.domain.vo.SampleSync;
import com.bonus.material.purchase.config.RemoteConfig;
import com.bonus.material.scrap.domain.ScrapApplyDetails;
import com.bonus.material.scrap.mapper.ScrapApplyDetailsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.bonus.material.ma.mapper.MachineMapper;
import com.bonus.material.ma.domain.Machine;
import com.bonus.material.ma.service.IMachineService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.bonus.common.core.web.domain.AjaxResult.error;
import static com.bonus.common.core.web.domain.AjaxResult.success;

/**
 * 机具设备管理Service业务层处理
 *
 * @author xsheng
 * @date 2024-09-27
 */
@Service
@Slf4j
public class MachineServiceImpl implements IMachineService
{
    @Resource
    private MachineMapper machineMapper;

    @Resource
    private RemoteConfig remoteConfig;

    @Resource
    private ScrapApplyDetailsMapper scrapApplyDetailsMapper;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    /**
     * 查询机具设备管理
     *
     * @param maId 机具设备管理主键
     * @return 机具设备管理
     */
    @Override
    public MachineVo selectMachineByMaId(Long maId)
    {
        MachineVo machineVo = machineMapper.selectMachineByMaId(maId);
        Map<String, String> machineStatus = remoteConfig.getDictValue("ma_machine_status");
        if (StringUtils.isNotBlank(machineVo.getMaStatus())) {
            machineVo.setStatusName(StringUtils.isBlank(machineStatus.get(machineVo.getMaStatus())) ? "" : machineStatus.get(machineVo.getMaStatus()));
        }
        return machineVo;
    }

    /**
     * 查询机具设备管理列表
     *
     * @param machine 机具设备管理
     * @return 机具设备管理
     */
    @Override
    public List<MachineVo> selectMachineList(Machine machine)
    {
        try {
            List<MachineVo> list = machineMapper.selectMachineList(machine);
            Map<String, String> machineStatus = remoteConfig.getDictValue("ma_machine_status");
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(machineVo -> {
                    if (StringUtils.isNotBlank(machineVo.getMaStatus())) {
                        machineVo.setStatusName(StringUtils.isBlank(machineStatus.get(machineVo.getMaStatus())) ? "" : machineStatus.get(machineVo.getMaStatus()));
                    }
                });
            }
            return list;
        } catch (Exception e){
            return new ArrayList<>();
        }

    }

    /**
     * 新增机具设备管理
     *
     * @param machine 机具设备管理
     * @return 结果
     */
    @Override
    public int insertMachine(Machine machine)
    {
        machine.setCreateTime(DateUtils.getNowDate());
        return machineMapper.insertMachine(machine);
    }

    /**
     * 修改机具设备管理
     *
     * @param machine 机具设备管理
     * @return 结果
     */
    @Override
    public AjaxResult updateMachine(Machine machine)
    {
        machine.setUpdateTime(DateUtils.getNowDate());
        int result = machineMapper.updateMachine(machine);
        if (result > 0) {
            return success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 批量删除机具设备管理
     *
     * @param maIds 需要删除的机具设备管理主键
     * @return 结果
     */
    @Override
    public int deleteMachineByMaIds(Long[] maIds)
    {
        return machineMapper.deleteMachineByMaIds(maIds);
    }

    /**
     * 删除机具设备管理信息
     *
     * @param maId 机具设备管理主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteMachineByMaId(Long maId)
    {
        int result = machineMapper.deleteMachineByMaId(maId);
        if (result > 0) {
            return success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 根据类型查询
     * @param type
     * @return
     */
    @Override
    public AjaxResult selectByTypeList(Type type) {
        List<Type> typeList = machineMapper.selectByTypeList(type);
        return success(typeList);
    }

    /**
     * todo 查询在库机具编号，存在数据拼接，盘点报废专用
     * @param type
     * @return
     */
    @Override
    public AjaxResult getMachineList(Type type) {
        List<Machine> typeList = machineMapper.getMachineList(type);
        if (type.getTaskId() != null && type.getTypeId() != null) {
            ScrapApplyDetails scrapApplyDetails = new ScrapApplyDetails();
            scrapApplyDetails.setTaskId(type.getTaskId());
            scrapApplyDetails.setTypeId(type.getTypeId());
            List<ScrapApplyDetails> list = scrapApplyDetailsMapper.getDetailsList(scrapApplyDetails);
            if (CollectionUtils.isNotEmpty(list)) {
                for (ScrapApplyDetails details : list) {
                    if (StringUtils.isNotBlank(details.getMaIds())) {
                        String[] maIds = details.getMaIds().split(",");
                        for (String maId : maIds) {
                            Machine machine = new Machine();
                            MachineVo machineVo = machineMapper.selectMachineByMaId(Long.parseLong(maId));
                            machine.setMaId(machineVo.getMaId());
                            machine.setMaCode(machineVo.getMaCode());
                            typeList.add(machine);
                        }
                    }
                }
            }
        }
        return success(typeList);
    }

    /**
     * 查询电子标签信息
     * @param machine
     * @return
     */
    @Override
    public List<Machine> getElectronicLabel(Machine machine) {
        List<Machine> list = machineMapper.getElectronicLabel(machine);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Machine dto : list) {
                // 根据typeId查询信息
                Machine info = machineMapper.selectHouse(dto);
                if (info != null) {
                    if ("机具库".equals(info.getOwnHouse())) {
                        dto.setIsJj(0);
                    } else {
                        dto.setIsJj(1);
                    }
                }
                // 获取领料单详情
                List<LeaseOutVo> details = leaseApplyDetailsMapper.selectByMaId(dto.getMaId());
                if (CollectionUtils.isNotEmpty(details)) {
                    Long id = details.get(0).getId();
                    dto.setId(id);
                }
            }
        }
        return list;
    }

    /**
     * 根据标签信息查询出库单
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public LeaseApplyRequestVo getInfoByMaId(LeaseApplyInfo leaseApplyInfo) {
        try {
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();
            // 根据maCode查询maId
            Long maId = machineMapper.selectMaId(leaseApplyInfo);
            // 获取领料单详情
            List<LeaseOutVo> details = leaseApplyDetailsMapper.selectByMaId(maId);
            if (CollectionUtils.isNotEmpty(details)) {
                leaseApplyRequestVo.setLeaseOutVoList(details);
                Long id = details.get(0).getId();
                leaseApplyInfo.setId(id);
            }
            LeaseApplyInfo optionalInfo = leaseApplyInfoMapper.selectLeaseApplyInfoById(leaseApplyInfo);
            if (optionalInfo != null) {
                leaseApplyRequestVo.setLeaseApplyInfo(optionalInfo);
            }
            return leaseApplyRequestVo;
        } catch (Exception e) {
            // 记录异常日志
            throw new RuntimeException("Failed to select lease apply info", e);
        }
    }

    /**
     * 电子标签编码查询
     * @param machine
     * @return
     */
    @Override
    public List<Machine> getByMaCode(Machine machine) {
        return machineMapper.getByMaCode(machine);
    }

    @Override
    @Transactional
    public AjaxResult synchReport(Machine machine)
    {
        try {
            String pdfUrl = machine.getPdf();
            String checkTime = machine.getCheckTimeSynch()+ " 00:00:00";
            String nextCheckTime = machine.getNextCheckTimeSynch()+ " 00:00:00";
            String reportName = machine.getReportName();
            String reportNum = machine.getReportNum();
            if(machine.getSamples()!=null && machine.getSamples().size()>0){
                int numAll = 0;
                for(SampleSync sample : machine.getSamples()){
                    sample.setCheckTimeSynch(checkTime);
                    sample.setNextCheckTimeSynch(nextCheckTime);
                    sample.setPdf(pdfUrl);
                    sample.setReportName(reportName);
                    sample.setReportNum(reportNum);
                    int result = machineMapper.updateSynchReport(sample);
                    numAll += result;
                }
                if(numAll>0){
                    return success("同步成功");
                }else{
                    return error("同步失败，暂无相关的机具编码");
                }
            }
            return error("同步失败，暂无相关的机具编码");
        } catch (Exception e) {
            return error("同步报告失败：" + e.getMessage());
        }
    }

    @Override
    public int editAssetsCode(Machine machine)
    {
        machine.setCreateTime(DateUtils.getNowDate());
        return machineMapper.editAssetsCode(machine);
    }

    @Override
    public AjaxResult getHisByQrcode(Machine machine) {
        //1根据二维码查询基础信息
        Machine baseInfo = machineMapper.getInfoByQrcode(machine);
        machine.setMaId(baseInfo.getMaId());
        //2根据二维码查询初次入库时间
        Machine inTime = machineMapper.getInTimeByQrcode(machine);
        //服务工程次数，检验次数
        Machine serviceNum = machineMapper.getServiceNumByQrcode(machine);
        //更换配件次数
        Machine checkNum = machineMapper.getCheckNumByQrcode(machine);
        //报废时间
        Machine scrapTime = machineMapper.getScrapTimeByQrcode(machine);
        //3根据机具id查询领退工程
        Machine leaseInfo = machineMapper.getLeaseInfoByQrcode(machine);
        if (inTime != null){
            Integer taskId = inTime.getTaskId();
            if(taskId != null){
                baseInfo.setInTime(inTime.getInTime()+"新购");
            }else{
                baseInfo.setInTime(inTime.getInTime());
            }

        }

        if(serviceNum != null){
            baseInfo.setServiceNum(serviceNum.getServiceNum());
        }else{
            baseInfo.setServiceNum(0);
        }

        if(checkNum != null){
            baseInfo.setCheckNum(checkNum.getCheckNum());
        }else{
            baseInfo.setCheckNum(0);
        }

        if (scrapTime != null){
            baseInfo.setScrapTime(scrapTime.getScrapTime());
        }else{
            baseInfo.setScrapTime("暂无");
        }

        if(leaseInfo != null){
            baseInfo.setLeaseTime(leaseInfo.getLeaseTime());
            baseInfo.setLeaseUnit(leaseInfo.getLeaseUnit());
            baseInfo.setLeaseProject(leaseInfo.getLeaseProject());
            baseInfo.setBackTime(leaseInfo.getBackTime());
            baseInfo.setBackUnit(leaseInfo.getBackUnit());
            baseInfo.setBackProject(leaseInfo.getBackProject());
        }
        return success(baseInfo);
    }

}
