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.file.FileTypeUtil;
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.security.annotation.RequiresPermissions;
import com.xueyi.common.web.entity.controller.BaseController;
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.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.InputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

/**
 * 静态资源管理 业务处理
 *
 * @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";
    /**
     * 头像上传
     */
    @PostMapping("/upload")
    @Log(title = "资源管理 - 上传资源", businessType = BusinessType.UPDATE)
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String extension = FileTypeUtil.getExtension(file);
            if (!CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.IMAGE_EXTENSION)
                    && !CharSequenceUtil.equalsAnyIgnoreCase(extension, MimeTypeUtil.VIDEO_EXTENSION)) {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtil.IMAGE_EXTENSION) + Arrays.toString(MimeTypeUtil.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.upload(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);
            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());

            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;
        }
        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);
            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("上传图片异常，请联系管理员！");
    }

    /**
     * 头像上传
     */
    @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.upload(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;
    }
}
