package com.xueyi.system.resource.controller;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xueyi.common.core.utils.core.IdUtil;
import com.xueyi.common.core.utils.file.FileTypeUtil;
import com.xueyi.common.core.utils.file.FileUtil;
import com.xueyi.common.core.utils.file.MimeTypeUtil;
import com.xueyi.common.core.web.result.AjaxResult;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.core.web.validate.V_E;
import com.xueyi.common.log.annotation.Log;
import com.xueyi.common.log.enums.BusinessType;
import com.xueyi.common.redis.utils.RedisUtil;
import com.xueyi.common.security.annotation.RequiresPermissions;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.file.api.domain.ByteArrayMultipartFile;
import com.xueyi.file.api.domain.SysFile;
import com.xueyi.file.api.feign.RemoteFileService;
import com.xueyi.system.api.resource.domain.po.DmResourcesPo;
import com.xueyi.system.resource.domain.dto.DmResourcesDto;
import com.xueyi.system.resource.domain.query.DmResourcesQuery;
import com.xueyi.system.resource.service.IDmFaceFeatureService;
import com.xueyi.system.resource.service.IDmResourcesService;
import com.xueyi.system.resource.service.impl.FaceServiceImpl;
import com.xueyi.system.utils.common.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 静态资源管理 业务处理
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/resources")
public class DmResourcesController extends BaseController<DmResourcesQuery, DmResourcesDto, IDmResourcesService> {

    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "静态资源" ;
    }


    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private IDmResourcesService iDmResourcesService;


    @Autowired
    private IDmFaceFeatureService iDmFaceFeatureService;

    @Autowired
    private FaceServiceImpl faceService;
    /**
     * 查询静态资源列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.DM_RESOURCES_LIST)
    public AjaxResult list(DmResourcesQuery dmResources) {
        return super.list(dmResources);
    }

    /**
     * 查询静态资源详细
     */
    @Override
    @GetMapping(value = "/{id}")
    @RequiresPermissions(Auth.DM_RESOURCES_SINGLE)
    public AjaxResult getInfo(@PathVariable Serializable id) {
        return super.getInfo(id);
    }




    /**
     * 静态资源修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.DM_RESOURCES_EDIT)
    @Log(title = "静态资源管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody DmResourcesDto dmResources) {
        return super.edit(dmResources);
    }

    /**
     * 静态资源批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.DM_RESOURCES_DEL)
    @Log(title = "静态资源管理", businessType = BusinessType.DELETE)
    public AjaxResult batchRemove(@PathVariable List<Long> idList) {
        return super.batchRemove(idList);
    }

    /**
     * 获取静态资源选择框列表
     */
    @Override
    @GetMapping("/option")
    public AjaxResult option() {
        return super.option();
    }

    interface Auth {
        /** 系统 - 静态资源管理 - 列表 */
        String DM_RESOURCES_LIST = "resource:resources:list";
        /** 系统 - 静态资源管理 - 详情 */
        String DM_RESOURCES_SINGLE = "resource:resources:single";
        /** 系统 - 静态资源管理 - 新增 */
        String DM_RESOURCES_ADD = "resource:resources:add";
        /** 系统 - 静态资源管理 - 修改 */
        String DM_RESOURCES_EDIT = "resource:resources:edit";
        /** 系统 - 静态资源管理 - 删除 */
        String DM_RESOURCES_DEL = "resource:resources:delete";
    }


    private static final String PARAM_RESOURCE_ID = "resource_id";
    private static final String PARAM_URL = "url";

    private static final String PARAM_TYPE = "type";



    @PostMapping("/chunkUpload")
    public AjaxResult uploadChunk(
            @RequestParam("file") MultipartFile file,
            @RequestParam("chunkIndex") int chunk,
            @RequestParam("chunkCount") int chunks,
            @RequestParam("uploadUuid") String uuid
    ) throws IOException {
        String folder = "/home/xueyi/upload/temp/";
        String key = "saas:upload:chunk:"+uuid;
        File dir = new File(folder);
        if (!dir.exists()) {
            dir.mkdirs();
        }


        String fileName = FileUtil.getFileNameNoExt(file.getOriginalFilename());
        if (RedisUtil.existed(key+":fileName")) {
            fileName = (String) RedisUtil.getVal(key+":fileName");
        } else {
            RedisUtil.setVal(key+":fileName",fileName);
        }

        logger.info("chunkIndex:{},chunkTotal:{},fileName:{},fileOriginName:{}",chunk,chunks,file.getName(),fileName);

        logger.info("upload 第{}/{} 块",chunk+1,chunks);
        String path = folder + fileName + "_" + chunk + ".part";
        try {
            file.transferTo(new File(path));
            RedisUtil.increment(key,1);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件保存失败");
        }
        if (((Integer) RedisUtil.getVal(key)).longValue() == chunks) {
            // 合并所有分片
            File[] content = new File[chunks];
            for (int i = 0; i < chunks; i++) {
                content[i] = new File(folder + fileName + "_" + i + ".part");
            }
            File destFile = new File(folder + fileName);
            logger.info("合并文件:{},文件数：{}",destFile.getAbsolutePath(), content.length);
            FileUtil.mergeFile(content, destFile);
            // 删除分片文件
            for (int i = 0; i < chunks; i++) {
                new File(folder + fileName + "_" + i + ".part").delete();
            }
            MultipartFile multipartFile = new MockMultipartFile(fileName, new FileInputStream(destFile));

            RedisUtil.expire(key, 5);
            return executeUpload(multipartFile, FileTypeUtil.getExtension(file), uuid);
        }

        return  AjaxResult.success("上传文件成功！");
    }

    private MultipartFile mergeChunks(List<byte[]> byteArrays) {
        // 合并所有分片的byte数组为一个byte数组
        int totalSize = byteArrays.stream().mapToInt(byteArray -> byteArray.length).sum();
        byte[] mergedBytes = new byte[totalSize];
        int currentIndex = 0;
        //byteArrays 顺序颠倒
        for (int i = byteArrays.size()-1; i >= 0; i--) {
            byte[] bytes = byteArrays.get(i);
            System.arraycopy(bytes, 0, mergedBytes, currentIndex, bytes.length);
            currentIndex += bytes.length;
        }
        /*for (byte[] bytes : byteArrays) {
            System.arraycopy(bytes, 0, mergedBytes, currentIndex, bytes.length);
            currentIndex += bytes.length;
        }*/
        logger.info("mergeChunks count:{}", byteArrays.size());
        logger.info("mergeChunks currentIndex:{}", currentIndex);

        // 创建一个新的MultipartFile对象，代表合并后的文件
        return new ByteArrayMultipartFile(mergedBytes);

    }

    /**
     * 头像上传
     */
    @PostMapping("/upload")
    @Log(title = "资源管理 - 上传资源", businessType = BusinessType.UPDATE)
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        logger.info("file contentType:{}, size：{}, name：{}, empty:{}",file.getContentType() ,file.getSize(), file.getOriginalFilename(), file.isEmpty());
        String extension = FileTypeUtil.getExtension(file);
        String uploadUuid = IdUtil.randomUUID();
        if (!file.isEmpty()) {
            logger.info("文件类型：" + extension + ",上传到MINIO开始...");
            if (!CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.EXCEPT_ALLOWED_EXTENSION)) {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtil.EXCEPT_ALLOWED_EXTENSION) + "格式");
            }

            R<SysFile> fileResult = remoteFileService.uploadNoAsync(file, extension, uploadUuid);

            if (ObjectUtil.isNull(fileResult) || ObjectUtil.isNull(fileResult.getData()))
                return error("文件服务异常，请联系管理员！");
            String url = fileResult.getData().getUrl();

            DmResourcesDto dto = new DmResourcesDto();
            dto.setName(file.getOriginalFilename());
            dto.setUrl(url);
            if (CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.IMAGE_EXTENSION)) {
                dto.setType(DmResourcesPo.TYPE_PIC);
            }
            if (CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.VIDEO_EXTENSION)) {
                dto.setType(DmResourcesPo.TYPE_VIDEO);
            }
            dto.setFileSize(fileResult.getData().getSize());
            dto.setFeature("");

            iDmResourcesService.addOne(dto);
            JSONObject jo = new JSONObject();
            jo.put(PARAM_RESOURCE_ID, dto.getId());
            jo.put(PARAM_URL, url);
            jo.put(PARAM_TYPE, dto.getType());

            AjaxResult ajax = success();
            ajax.put(AjaxResult.RESULT_TAG, jo);
            logger.info("上传文件成功，返回数据：" + ajax.toJson().toJSONString());
            return ajax;

        }
        return error("上传文件异常，请联系管理员！");
    }





    @GetMapping("/uploadCallback")
    @Log(title = "资源管理 - 上传资源回调", businessType = BusinessType.UPDATE)
    public AjaxResult pdfUploadCallback(@RequestParam("uploadUuid") String uploadUuid) {

        if (!RedisUtil.existed("saas:upload:result:"+uploadUuid)) {
            return AjaxResult.error("上传操作可能尚未完成，请等待...");
        }

        String result = (String) RedisUtil.getVal("saas:upload:result:"+uploadUuid);
        String fileName = (String) RedisUtil.getVal("saas:upload:filename:"+uploadUuid);
        Integer fileType = (Integer) RedisUtil.getVal("saas:upload:fileType:"+uploadUuid);

        JSONArray res =  JSONArray.parseArray(result);
        List<JSONObject> jsons = res.stream().map(sf -> (JSONObject) sf).collect(Collectors.toList());

        if (RedisUtil.existed("saas:upload:callbackExec:"+uploadUuid)) {
            JSONArray _res = JSONArray.parseArray((String) RedisUtil.getVal("saas:upload:callbackExec:"+uploadUuid));
            return AjaxResult.success(_res);
        }
        JSONArray ja = new JSONArray();
        for (JSONObject sf : jsons) {
            String url = (String) sf.get("url");
            DmResourcesDto dto = new DmResourcesDto();
            dto.setName(fileName);
            dto.setUrl(url);
            dto.setType(fileType);
            dto.setFileSize(((Integer) sf.get("size")).longValue());
            dto.setFeature("");

            iDmResourcesService.addOne(dto);
            JSONObject jo = new JSONObject();
            jo.put(PARAM_RESOURCE_ID, dto.getId());
            jo.put(PARAM_URL, url);
            jo.put(PARAM_TYPE, dto.getType());
            ja.add(jo);
        }

        AjaxResult ajax = success();
        ajax.put(AjaxResult.RESULT_TAG, ja);
        RedisUtil.setVal("saas:upload:callbackExec:"+uploadUuid, ja.toJSONString());

        logger.info("上传文件成功，返回数据：" + ajax.toJson().toJSONString());

        return ajax;
    }

    public AjaxResult executeUpload(MultipartFile file, String extension, String uploadUuid) {
        logger.info("file contentType:{}, size：{}, name：{}, empty:{}",file.getContentType() ,file.getSize(), file.getOriginalFilename(), file.isEmpty());
        if (!file.isEmpty()) {
            logger.info("文件类型：" + extension + ",上传到MINIO开始...");
            if (!CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.EXCEPT_ALLOWED_EXTENSION)) {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtil.EXCEPT_ALLOWED_EXTENSION) + "格式");
            }

            if (MimeTypeUtil.PDF_EXTENSION.equalsIgnoreCase(extension)) {
                remoteFileService.uploadPdf(file, uploadUuid);
                /*if (ObjectUtil.isNull(fileResult) || ObjectUtil.isNull(fileResult.getData()))
                    return error("文件服务异常，请联系管理员！");
                JSONArray ja = new JSONArray();
                for (SysFile sf : fileResult.getData()) {
                    String url = sf.getUrl();
                    DmResourcesDto dto = new DmResourcesDto();
                    dto.setName(file.getOriginalFilename());
                    dto.setUrl(url);
                    dto.setType(DmResourcesPo.TYPE_PIC);
                    dto.setFileSize(sf.getSize());
                    dto.setFeature("");

                    iDmResourcesService.addOne(dto);
                    JSONObject jo = new JSONObject();
                    jo.put(PARAM_RESOURCE_ID, dto.getId());
                    jo.put(PARAM_URL, url);
                    jo.put(PARAM_TYPE, dto.getType());
                    ja.add(jo);
                }*/
                AjaxResult ajax = success();
                ajax.put(AjaxResult.MSG_TAG, "文件后台上传处理中...");
                ajax.put("uploadUuid",  uploadUuid);
                logger.info("异步上传文件...");
                return ajax;
            } else {
                remoteFileService.upload(file, extension, uploadUuid);

                AjaxResult ajax = success();
                ajax.put(AjaxResult.MSG_TAG, "文件后台上传处理中...");
                ajax.put("uploadUuid",  uploadUuid);
                logger.info("异步上传文件...");
                return ajax;
                /*if (ObjectUtil.isNull(fileResult) || ObjectUtil.isNull(fileResult.getData()))
                    return error("文件服务异常，请联系管理员！");
                String url = fileResult.getData().getUrl();*/


                /*DmResourcesDto dto = new DmResourcesDto();
                dto.setName(file.getOriginalFilename());
                dto.setUrl(url);
                if (CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.IMAGE_EXTENSION)) {
                    dto.setType(DmResourcesPo.TYPE_PIC);
                }
                if (CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.VIDEO_EXTENSION)) {
                    dto.setType(DmResourcesPo.TYPE_VIDEO);
                }
                dto.setFileSize(fileResult.getData().getSize());
                dto.setFeature("");

                iDmResourcesService.addOne(dto);
                JSONObject jo = new JSONObject();
                jo.put(PARAM_RESOURCE_ID, dto.getId());
                jo.put(PARAM_URL, url);
                jo.put(PARAM_TYPE, dto.getType());

                AjaxResult ajax = success();
                ajax.put(AjaxResult.RESULT_TAG, jo);
                logger.info("上传文件成功，返回数据：" + ajax.toJson().toJSONString());
                return ajax;*/
            }
        }
        return error("上传文件异常，请联系管理员！");
    }

    /**
     * 头像上传
     */
    @PostMapping("/uploadpdf")
    @Log(title = "资源管理 - 上传资源", businessType = BusinessType.UPDATE)
    public AjaxResult uploadPdf(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String extension = FileTypeUtil.getExtension(file);
            if (!CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.DEFAULT_ALLOWED_EXTENSION)
                    ) {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtil.IMAGE_EXTENSION) + Arrays.toString(MimeTypeUtil.IMAGE_EXTENSION) + "格式");
            }
            R<List<SysFile>> fileResult = remoteFileService.uploadPdf(file, IdUtil.randomUUID());
            if (ObjectUtil.isNull(fileResult) || ObjectUtil.isNull(fileResult.getData()))
                return error("文件服务异常，请联系管理员！");
            JSONArray ja = new JSONArray();
            for (SysFile sf : fileResult.getData()) {
                String url = sf.getUrl();
                // 预留人脸识别与图像质量监测接口，如果监测异常返回错误

                DmResourcesDto dto = new DmResourcesDto();
                dto.setName(file.getOriginalFilename());
                dto.setUrl(url);
                dto.setType(DmResourcesPo.TYPE_PIC);
                dto.setFileSize(sf.getSize());

                iDmResourcesService.addOne(dto);
                JSONObject jo = new JSONObject();
                jo.put(PARAM_RESOURCE_ID, dto.getId());
                jo.put(PARAM_URL, url);
                ja.add(jo);
            }
            AjaxResult ajax = success();
            ajax.put(AjaxResult.RESULT_TAG, ja);
            return ajax;
        }
        return error("上传PDF文件异常，请联系管理员！");
    }

    /**
     * 头像上传
     */
    @PostMapping("/upload-face")
    @Log(title = "资源管理 - 上传资源", businessType = BusinessType.UPDATE)
    public AjaxResult uploadFace(@RequestParam("file") MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                InputStream in = file.getInputStream();
                String bs64 = ImageUtil.convertToBase64(in);

                JSONObject json = faceService.getFaceExtraction("", "", bs64);

                if (0!=json.getInteger("status")) {
                    return error(json.getString("errMsg"));
                } else {
                    JSONArray obj = json.getJSONArray("result").getJSONObject(0).getJSONArray("faces").getJSONObject(0).getJSONArray("feature");

                    String extension = FileTypeUtil.getExtension(file);
                    if (!CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.IMAGE_EXTENSION)) {
                        return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtil.IMAGE_EXTENSION) + "格式");
                    }
                    R<SysFile> fileResult = remoteFileService.uploadFace(file);
                    if (ObjectUtil.isNull(fileResult) || ObjectUtil.isNull(fileResult.getData()))
                        return error("文件服务异常，请联系管理员！");
                    String url = fileResult.getData().getUrl();


                    DmResourcesDto dto = new DmResourcesDto();
                    dto.setName(file.getOriginalFilename());
                    dto.setUrl(url);
                    dto.setFeature(obj.toJSONString());
                    dto.setType(DmResourcesPo.TYPE_PIC);

                    iDmResourcesService.addOne(dto);
                    JSONObject jo = new JSONObject();
                    jo.put(PARAM_RESOURCE_ID, dto.getId());
                    jo.put(PARAM_URL, url);


                    AjaxResult ajax = success();
                    ajax.put(AjaxResult.RESULT_TAG, jo);
                    return ajax;
                }


            }
        } catch (Exception e) {
            return error("上传图片异常，可能获取人脸失败，请重试！");
        }

        return error("上传图片异常，请联系管理员！");
    }

    /**
     * 静态资源新增
     */
    @PostMapping("/init_add")
    @Log(title = "新增初始化静态资源", businessType = BusinessType.UPDATE)
    public AjaxResult initAdd(@Validated({V_E.class}) @RequestBody DmResourcesDto dto) {
        iDmResourcesService.addOne(dto);
        JSONObject jo = new JSONObject();
        jo.put(PARAM_RESOURCE_ID, dto.getId());
        jo.put(PARAM_URL, dto.getUrl());


        AjaxResult ajax = success();
        ajax.put(AjaxResult.RESULT_TAG, jo);
        return ajax;
    }
}
