package cn.exploring.engine.server.admin.web;

import cn.exploring.engine.server.admin.annotation.RequiresPermissionsDesc;
import cn.exploring.engine.server.core.qcode.QCodeService;
import cn.exploring.engine.server.core.storage.StorageService;
import cn.exploring.engine.server.core.util.FileUploadUtil;
import cn.exploring.engine.server.core.util.ImageUtil;
import cn.exploring.engine.server.core.util.ResponseUtil;
import cn.exploring.engine.server.core.validator.Order;
import cn.exploring.engine.server.core.validator.Sort;
import cn.exploring.engine.server.db.domain.WxStorage;
import cn.exploring.engine.server.db.domain.vo.ShareQrcodeVo;
import cn.exploring.engine.server.db.service.WxStorageService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/storage")
@Validated
public class AdminStorageController {
    private final Log logger = LogFactory.getLog(AdminStorageController.class);

    @Autowired
    private StorageService storageService;
    @Autowired
    private WxStorageService wxStorageService;
    @Autowired
    private QCodeService qCodeService;

    @Value("${projectRedis.keyPrefix.share}")
    private String projectRedisKeyShare;

    @RequiresPermissions("admin:storage:list")
    @RequiresPermissionsDesc(menu={"系统管理" , "对象存储"}, button="查询")
    @GetMapping("/list")
    public Object list(String key, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<WxStorage> storageList = wxStorageService.querySelective(key, name, page, limit, sort, order);
        long total = PageInfo.of(storageList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", storageList);

        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:storage:create")
    @RequiresPermissionsDesc(menu={"系统管理" , "对象存储"}, button="上传")
    @PostMapping("/create")
    public Object create(@RequestParam("file") MultipartFile file) throws IOException {
        String url = ImageUtil.storeSrcAndCompress(storageService, file);
        if (url == null) {
            return ResponseUtil.badArgumentValue();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("url", url);
        return ResponseUtil.ok(data);
    }

    /**
     * 上传本地，不压缩
     * @param file
     * @return
     * @throws IOException
     */
    @RequiresPermissions("admin:storage:createAny")
    @RequiresPermissionsDesc(menu={"系统管理" , "对象存储"}, button="上传任意格式文件")
    @PostMapping("/createAny")
    public Object createAny(@RequestParam("file") MultipartFile file) throws IOException {
        String url = FileUploadUtil.store(storageService, file);
        if (url == null) {
            return cn.exploring.engine.server.db.util.ResponseUtil.badArgumentValue();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("url", url);
        return cn.exploring.engine.server.db.util.ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:storage:read")
    @RequiresPermissionsDesc(menu={"系统管理" , "对象存储"}, button="详情")
    @PostMapping("/read")
    public Object read(@NotNull Integer id) {
        WxStorage storageInfo = wxStorageService.findById(id);
        if (storageInfo == null) {
            return ResponseUtil.badArgumentValue();
        }
        return ResponseUtil.ok(storageInfo);
    }

    @RequiresPermissions("admin:storage:update")
    @RequiresPermissionsDesc(menu={"系统管理" , "对象存储"}, button="编辑")
    @PostMapping("/update")
    public Object update(@RequestBody WxStorage storage) {
        if (wxStorageService.update(storage) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok(storage);
    }

    @RequiresPermissions("admin:storage:delete")
    @RequiresPermissionsDesc(menu={"系统管理" , "对象存储"}, button="删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody WxStorage wxStorage) {
        String key = wxStorage.getKey();
        if (StringUtils.isEmpty(key)) {
            return ResponseUtil.badArgument();
        }
        wxStorageService.deleteByKey(key);
        storageService.delete(key);
        return ResponseUtil.ok();
    }

    /**
     * 用户分享图片
     * @param vo
     * @return
     */
    @RequiresPermissions("admin:storage:share")
    @RequiresPermissionsDesc(menu={"系统管理" , "对象存储"}, button="分享")
    @PostMapping("/share")
    public Object share(@RequestBody ShareQrcodeVo vo) {
        if (vo == null || vo.getId() == null || vo.getUrl() == null) {
            return ResponseUtil.badArgument();
        }

        Integer oid = Integer.parseInt(vo.getId().split("_")[1]);


        String result = qCodeService.createShareQrcodeImage(vo.getId(), vo.getUrl(), QCodeService.INVOTE, "url", "name");  // todo

        Map<String, Object> data = new HashMap<>();
        data.put("url", result);
        return ResponseUtil.ok(data);
    }

    /**
     * 访问存储对象
     *
     * @param key 存储对象key
     * @return
     */
    @GetMapping("/fetch/{path}/{key:.+}")
    public ResponseEntity<Resource> fetch(@PathVariable String path, @PathVariable String key) throws UnsupportedEncodingException {
        String filePathAndName = path + "/" + key;

        if (filePathAndName == null) {
            return ResponseEntity.notFound().build();
        }
        WxStorage storage = wxStorageService.findByKey(filePathAndName);
        if (storage == null) {
            return ResponseEntity.notFound().build();
        }

        String type = storage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.getLocalStorage().loadAsResource(filePathAndName);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=%s",  java.net.URLEncoder.encode(key, "UTF-8")));

        return ResponseEntity.ok().headers(headers).contentType(mediaType).body(file);
    }

    @GetMapping("/fetch/{key:.+}")
    public ResponseEntity<Resource> fetch(@PathVariable String key) {
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        WxStorage storage = wxStorageService.findByKey(key);
        if (storage == null) {
            return ResponseEntity.notFound().build();
        }

        String type = storage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.getLocalStorage().loadAsResource(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }
}
