package com.djhk.uav.equ.service.impl;

//
import com.djhk.common.api.RemoteSystemFileService;
import com.djhk.common.api.domain.SysFile;
import com.djhk.common.api.domain.vo.FileVo;
import com.djhk.common.enums.BizCodeEnum;
import com.djhk.common.exception.ServiceException;
import com.djhk.common.utils.DateUtils;
import com.djhk.common.utils.SecurityUtils;
import com.djhk.common.utils.StringUtils;
import com.djhk.common.utils.bean.BeanUtils;
import com.djhk.uav.equ.domain.EquModel;
import com.djhk.uav.equ.domain.EquModelParam;
import com.djhk.uav.equ.domain.EquType;
import com.djhk.uav.equ.domain.vo.EquModelExportVo;
import com.djhk.uav.equ.mapper.EquModelMapper;
import com.djhk.uav.equ.mapper.EquModelParamMapper;
import com.djhk.uav.equ.mapper.EquTypeMapper;
import com.djhk.uav.equ.service.FileUploadService;
import com.djhk.uav.equ.service.IEquModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备型号Service业务层处理
 * 
 * @author huangqg
 * @date 2023-06-01
 */
@Service
public class EquModelServiceImpl implements IEquModelService
{
    @Autowired
    private EquModelMapper equModelMapper;

    @Autowired
    private RemoteSystemFileService sysFileMapper;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private EquModelParamMapper equModelParamMapper;

    @Autowired
    private RemoteSystemFileService remoteSystemFileService;

    @Autowired
    private EquTypeMapper equTypeMapper;

//    @Value("${minio.endpoint}")
   @Value("${minio.endpoint:http://47.109.103.110:9005}")
    private String baseUrl;
    /**
     * 查询设备型号
     *
     * @param modelId 设备型号主键
     * @return 设备型号
//     */
    @Override
    public EquModel selectEquModelByModelId(Long modelId)
    {
        EquModel equModel = equModelMapper.selectEquModelByModelId(modelId);
        if (equModel != null && equModel.getDynModelFile() != null) {
//            SysFile dynModelFile = remoteSystemFileService.getFileInfo(equModel.getDynModelFile()).getData();
            SysFile dynModelFile = sysFileMapper.getFileInfo(equModel.getDynModelFile()).getData();
            if (dynModelFile != null) {
                equModel.setDynModelFilePath(baseUrl + "/" + dynModelFile.getBucketName() + dynModelFile.getFilePath());
                equModel.setDynModelFileName(dynModelFile.getFileName());
            }

//            SysFile staModelFile = remoteSystemFileService.getFileInfo(equModel.getStaModelFile()).getData();
            SysFile staModelFile = sysFileMapper.getFileInfo(equModel.getStaModelFile()).getData();
            if (staModelFile != null) {
                equModel.setStaModelFilePath(baseUrl + "/" + staModelFile.getBucketName() + staModelFile.getFilePath());
                equModel.setStaModelFileName(staModelFile.getFileName());
            }

//            SysFile iconFile = remoteSystemFileService.getFileInfo(equModel.getIconFile()).getData();
            SysFile iconFile = sysFileMapper.getFileInfo(equModel.getIconFile()).getData();
            if (iconFile != null) {
                equModel.setIconFilePath(baseUrl + "/" + iconFile.getBucketName() + iconFile.getFilePath());
                equModel.setIconFileName(iconFile.getFileName());
            }
        }
        return equModel;
    }

    /**
     * 查询设备型号列表
     * 
     * @param equModel 设备型号
     * @return 设备型号
     */
    @Override
    public List<EquModel> selectEquModelList(EquModel equModel)
    {
        List<EquModel> equModels = equModelMapper.selectEquModelList(equModel);
        if(equModels!=null){
            for (EquModel item : equModels) {
                if(item.getIconFile()!=null){
                    SysFile iconFile = sysFileMapper.getFileInfo(item.getIconFile()).getData();
                    item.setIconFilePath(iconFile!=null?baseUrl+ "/" + iconFile.getBucketName() +iconFile.getFilePath():"");
                }
            }
        }
        return equModels;
    }

    @Override
    public FileVo uploadFile(MultipartFile file) {
        if(file != null){
            return fileUploadService.fileUpload(file, "", "Uav", BizCodeEnum.UAV_INFO.getCode(), "", "");
        }
        return null;
    }

    /**
     * 新增设备型号
     *
     * @param equModel 设备型号
     * @return 结果
     */
    @Override
    public int insertEquModel(EquModel equModel)
    {
        equModel.setCreateTime(DateUtils.getNowDate());
        equModel.setDelMark("0");
        equModel.setCreateBy(SecurityUtils.getUsername().toString());
        return equModelMapper.insertEquModel(equModel);
    }

    /**
     * 查询设备型号编码
     *
     * @param modeCode 型号编码
     * @return 结果
     */
    @Override
    public List<EquModel> checkModelCode(String modeCode) {
        return equModelMapper.checkModelCode(modeCode);
    }

    /**
     * 修改设备型号
     *
     * @param equModel 设备型号
     * @return 结果
     */
    @Override
    public int updateEquModel(EquModel equModel)
    {
        equModel.setUpdateBy(SecurityUtils.getUsername().toString());
        return equModelMapper.updateEquModel(equModel);
    }

    /**
     * 批量删除设备型号
     *
     * @param modelIds 需要删除的设备型号主键
     * @return 结果
     */
    @Override
    public int deleteEquModelByModelIds(Long[] modelIds)
    {
        return equModelMapper.deleteEquModelByModelIds(modelIds);
    }
//
//    /**
//     * 删除设备型号信息
//     *
//     * @param modelId 设备型号主键
//     * @return 结果
//     */
//    @Override
//    public int deleteEquModelByModelId(Long modelId)
//    {
//        return equModelMapper.deleteEquModelByModelId(modelId);
//    }


    /**
     * 新增修改设备型号参数表
     *
     * @param
     * @return 结果
     */
    @Override
    public int updateEqumodelParamList(List<Map> paramList)
    {
        for (Map item:paramList){
            if (item.get("paramSeq") != null && StringUtils.isNotBlank(item.get("paramSeq").toString())){
                // 修改
                EquModelParam equModelParam = new EquModelParam();
                equModelParam.setParamSeq(Long.parseLong(item.get("paramSeq").toString()));
                equModelParam.setParamCode(item.get("param_code").toString());
                equModelParam.setParamName(item.get("param_name").toString());
                equModelParam.setParamValue(item.get("param_value").toString());
                equModelParam.setModelId(Long.parseLong(item.get("modelId").toString()));
                equModelParamMapper.updateEquModelParam(equModelParam);
            }else{
                EquModelParam equModelParam = new EquModelParam();
                equModelParam.setParamCode(item.get("param_code").toString());
                equModelParam.setParamValue(item.get("param_value").toString());
                equModelParam.setModelId(Long.parseLong(item.get("modelId").toString()));
                equModelParamMapper.insertEquModelParam(equModelParam);
            }
        }
        return paramList.size();
    }

    @Override
    public List<EquModel> selectEquInfoExportList(EquModelExportVo equInfoExportVo) {
        List<EquModel> equModels = equModelMapper.selectEquInfoExportList(equInfoExportVo);
        if (!equModels.isEmpty())
        {
            for (EquModel equModel : equModels) {
                EquType equType = equTypeMapper.selectEquTypeByTypeId(equModel.getTypeId());
                if (equType != null)
                {
                    equModel.setTypeId(equType.getTypeName());
                }
            }
        }

        return equModels;
    }

    @Override
    public String importData(List<EquModel> userList, Boolean isUpdateSupport){
        if (userList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！",500);
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<EquType> equTypes = equTypeMapper.selectEquType();
        List<String> typeNameList = equTypes.stream().map(EquType::getTypeName).collect(Collectors.toList());
        for (int i = 0; i < userList.size(); i++) {
            try
            {
                // 验证是否存在数据
                EquModel target = new EquModel();
                BeanUtils.copyBeanProp(target,userList.get(i));
                if (!typeNameList.contains(userList.get(i).getTypeId()))
                {
                    failureNum++;
                    failureMsg.append("第" + (i+1) + "条数据类别标识【"+ userList.get(i).getTypeId()+"】不存在，如要新增请联系管理员");
                    continue;
                }
                for (EquType equType : equTypes) {
                    if (equType.getTypeName().contains(userList.get(i).getTypeId()))
                    {
                        List<EquModel> equModels = equModelMapper.checkModelCode(target.getModelCode());
                        if (equModels.isEmpty())
                        {
                            target.setTypeId(equType.getTypeId());
                            target.setDelMark(String.valueOf(0));
                            equModelMapper.insertEquModel(target);
                            successNum++;
                        }
                        else
                        {
                            failureNum++;
                            failureMsg.append("第" + (i+1) + "条数据" +  "型号编码已存在,");
                        }
                    }
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "第" + (i+1) + "条数据 " + "导入失败,";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "数据导入失败！共" + failureNum + "条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString(),10002);
        }
        else
        {
            successMsg.insert(0, "数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }


}
