package com.securitycontrol.background.service.impl;

import com.securitycontrol.background.mapper.EmergencyMapper;
import com.securitycontrol.background.service.EmergencyService;
import com.securitycontrol.background.service.SourceFileService;
import com.securitycontrol.common.core.constant.SecurityConstants;
import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.utils.aes.ListHelper;
import com.securitycontrol.common.core.utils.aes.StringHelper;
import com.securitycontrol.entity.background.vo.DeviceVo;
import com.securitycontrol.entity.background.vo.EmergencyPlanVo;
import com.securitycontrol.entity.file.FileExportVo;
import com.securitycontrol.entity.system.SystemGlobal;
import com.securitycontrol.system.api.RemoteFileService;
import com.securitycontrol.system.api.domain.SysFile;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 应急预案流程管理
 * @author 黑子
 */
@Service
@Slf4j
public class EmergencyServiceImpl implements EmergencyService {

    /**
     * 匹配电话号码的正则表达式
      */
    private static final Pattern PHONE_PATTERN = Pattern.compile("^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$");
    /**
     * 匹配手机号码的正则表达式
     */
    private static final Pattern MOBILE_PATTERN = Pattern.compile("^\\+?[1-9]\\d{1,14}$");

    @Autowired
    private EmergencyMapper mapper;

    @Resource
    private RemoteFileService remoteFileService;
    @Resource
    private SourceFileService sourceFileService;
    /**
     * 查询信息列表
     * @param dto
     * @return
     */
    @Override
    public List<EmergencyPlanVo> getList(EmergencyPlanVo dto) {
        List<EmergencyPlanVo> list= mapper.getList(dto);
        if(!SystemGlobal.EME_TYPE.equals(dto.getEmergencyType())){
            list.forEach(vo->{
                List<FileExportVo> source=sourceFileService.getSourceList(vo.getId(),dto.getSourceType());
                vo.setSourceIds(source);
            });
        }
        return list;
    }

    /**
     *
     * @param dto
     * @return
     */
    @Override
    public Result<String> addTelData(EmergencyPlanVo dto) {
       try{
           String result=checkData(dto);
           if(StringHelper.isNotEmpty(result)){
               return   Result.fail(result);
           }

          int num= mapper.addTelData(dto);
           if(num==SystemGlobal.SUCCESS_NUM){
               return   Result.ok("新增成功","新增成功");
           }
           return   Result.fail("新增失败,请联系管理员");
       }catch (Exception e){
           log.error(e.toString(),e);
           return Result.fail("系统升级中,请稍后重试!");
       }
    }

    /**
     *
     * @param dto
     * @return
     */
    @Override
    public Result<String> updTelData(EmergencyPlanVo dto) {
        try{
            String result=checkData(dto);
            if(StringHelper.isNotEmpty(result)){
                return   Result.fail(result);
            }
            int num= mapper.updTelData(dto);
            if(num==SystemGlobal.SUCCESS_NUM){
                return   Result.ok("修改成功","修改成功");
            }
            return   Result.fail("修改失败,请联系管理员");
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail("系统升级中,请稍后重试!");
        }
    }

    /**
     * 删除数据
     * @param dto
     * @return
     */
    @Override
    public Result<String> deleteData(EmergencyPlanVo dto) {
        try{
            if(StringHelper.isEmpty(dto.getId())){
                return  Result.fail("数据不存在");
            }
            EmergencyPlanVo vo=mapper.getDetail(dto);
            String type=vo.getEmergencyType();
            if(!SystemGlobal.EME_TYPE.equals(type)){
                String sourceType="";
                if(SystemGlobal.EME_TYPE2.equals(type)){
                    sourceType=SystemGlobal.YA_NAME;
                }else{
                    sourceType=SystemGlobal.LC_NAME;
                }

                List<FileExportVo> fileId=sourceFileService.getSourceList(dto.getId(),sourceType);
                if(ListHelper.isNotEmpty(fileId)){
                    fileId.forEach(file->{
                        //删除资源数据
                        sourceFileService.deleteSource(file.getFileId());
                        //删除文件
                        remoteFileService.delFile(file.getFileId(),SecurityConstants.INNER);
                    });
                }
            }

            int num=mapper.deleteData(dto);
            if(num==1) {
                return   Result.ok("删除成功","删除成功");
            }else {
                return   Result.fail("数据已被删除或不存在","数据已被删除或不存在");
            }
        }catch (Exception e){
            log.error(e.toString(),e);
            return   Result.fail("删除失败");
        }
    }

    /**
     * 上传文件
     * @param files
     * @param dto
     * @return
     */
    @Override
    public  Result<String> addYaFile(MultipartFile[] files, EmergencyPlanVo dto) {
        try{
              String uploadFile=uploadFile(files);
              if(StringHelper.isNotEmpty(uploadFile)){
                return   Result.fail(uploadFile);
              }
            int num= mapper.addTelData(dto);
            if(num==SystemGlobal.SUCCESS_NUM){
                Result uploadResult = remoteFileService.mostUploadFile(files, SecurityConstants.INNER);
                if(uploadResult.getCode()!=SystemGlobal.SUCCESS_CODE){
                    mapper.deleteData(dto);
                    Result.fail("文件服务未连接，文件上传失败");
                }
                List<Object> list= (List<Object>) uploadResult.getData();
                Result<String>  result= sourceFileService.addSourceList(list, dto.getId(),dto.getSourceType(),"0");
                if(result.getCode()!=SystemGlobal.SUCCESS_CODE){
                    return result;
                }
                return Result.ok("新增成功","新增成功");
            }
            return   Result.fail("新增失败，文件上传失败");
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail("系统升级中,请稍后重试!");
        }
    }

    /**
     *
     * @param files
     * @param dto
     * @return
     */
    @Override
    public Result<String> updateYaFile(MultipartFile[] files, EmergencyPlanVo dto) {
       try{
               int num= mapper.updTelData(dto);
                if(files!=null){
                    String uploadFile=uploadFile(files);
                    if(StringHelper.isNotEmpty(uploadFile)){
                        return Result.fail(uploadFile);
                    }
                    Result uploadResult = remoteFileService.mostUploadFile(files, SecurityConstants.INNER);
                    if(uploadResult.getCode()!=SystemGlobal.SUCCESS_CODE){
                        Result.fail("文件服务未连接，文件上传失败");
                    }
                    List<Object> list= (List<Object>) uploadResult.getData();
                    Result<String>  result= sourceFileService.addSourceList(list, dto.getId(),dto.getSourceType(),"0");
                    if(result.getCode()!=SystemGlobal.SUCCESS_CODE){
                        return result;
                    }
                }
                if(StringHelper.isNotEmpty(dto.getDelFile())){
                    List<String> ids= Arrays.asList(dto.getDelFile().split("@"));
                    ids.forEach(id->{
                            remoteFileService.delFile(id,SecurityConstants.INNER);
                    });
                    Result<String>  result2= sourceFileService.deleteSource(dto.getDelFile());
                    if(result2.getCode()!=SystemGlobal.SUCCESS_CODE){
                        return result2;
                    }
                }
                return Result.ok("修改成功","修改成功");

       }catch (Exception e){
           log.error(e.toString(),e);
           return Result.fail("系统升级中,请稍后重试!");
       }
    }

    public String uploadFile(MultipartFile[] files){
        if(files!=null){
            for (int i = 0; i < files.length; i++) {
                String fileName=   files[i].getOriginalFilename();
                String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
                if(!SystemGlobal.PDF_FIX.equals(extension) && !SystemGlobal.WORLD2_FIX.equals(extension) && !SystemGlobal.WORLD_FIX.equals(extension) ){
                    return  "文件上传只支持pdf和world文档";
                }
            }
        }
        return null;
    }
    /**
     * 查看文件详情
     * @param dto
     * @return
     */
    @Override
    public Result<List<FileExportVo>> getFileDetails(EmergencyPlanVo dto) {
        try{
            List<FileExportVo> list=sourceFileService.getSourceList(dto.getId(),dto.getSourceType());
            list.forEach(file->{
            Result<SysFile>  result=remoteFileService.getFileBast64(file.getFileId(),SecurityConstants.INNER);
                file.setFile(result.getData().getUrl());
            });
            return  Result.ok(list);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return  Result.fail(new ArrayList<FileExportVo>());
    }

    /**
     *
     * @param fileId
     * @return
     */
    @Override
    public byte[] downLoadSgFile(String fileId) {
        return remoteFileService.getFileByte(fileId,SecurityConstants.INNER).getData();
    }


    private String checkData(EmergencyPlanVo dto) {
        if(StringHelper.isEmpty(dto.getEmergencyName())){
           return  "联系人不能为空";
        }
        if(StringHelper.isEmpty(dto.getEmergencySource())){
            return  "联系方式不能为空";
        }
        int num=mapper.getNumByData(dto);
        if(num> SystemGlobal.MIN_NUM){
            return  "联系方式已存在";
        }
        if(!PHONE_PATTERN.matcher(dto.getEmergencySource()).matches() &&  !MOBILE_PATTERN.matcher(dto.getEmergencySource()).matches()){
            return  "联系方式不正确";
        }
        return null;
    }



}
