package com.dsk.biz.goview.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.plugins.IgnoreStrategy;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsk.biz.goview.common.base.BaseController;
import com.dsk.biz.goview.common.bean.AjaxResult;
import com.dsk.biz.goview.common.domain.*;
import com.dsk.biz.goview.config.GoviewProperties;
import com.dsk.biz.goview.mapper.GoviewProjectDataMapper;
import com.dsk.biz.goview.mapper.GoviewProjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目表Controller
 *
 * @author fuce
 * @ClassName: GoviewProjectController
 * @date 2022-05-18 21:43:25
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/goview/project")
public class GoViewProjectAPIController extends BaseController {
    private final GoviewProjectDataMapper projectDataMapper;

    private final GoviewProjectMapper projectMapper;

    private final GoviewProperties goviewProperties;

    @GetMapping("/list")
    public ResultTable list(Tablepar tablepar, GoviewProject goviewProject) {
        Page page = new Page(tablepar.getPage(), tablepar.getLimit());
        Page result = projectMapper.selectPage(page, Wrappers.query(goviewProject));
        ResultTable resultTable = pageTable(result.getRecords(), result.getTotal());
        resultTable.setCode(200);
        return resultTable;
    }

    /**
     * 新增保存
     *
     * @param
     * @return
     */
    @PostMapping("/create")
    public AjaxResult add(@RequestBody GoviewProject goviewProject) {
        projectMapper.insert(goviewProject);
        return AjaxResult.successData(200, goviewProject).put("msg", "创建成功");
    }

    /**
     * 项目表删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/delete")
    public AjaxResult delete(String ids) {
        projectMapper.deleteById(ids);
        return success();
    }

    @PostMapping("/edit")
    public AjaxResult editSave(@RequestBody GoviewProject goviewProject) {
        projectMapper.updateById(goviewProject);
        return success();
    }

    @PostMapping("/rename")
    public AjaxResult rename(@RequestBody GoviewProject goviewProject) {
        projectMapper.updateById(goviewProject);
        return success();
    }

    // 发布/取消项目状态
    @PutMapping("/publish")
    @ResponseBody
    public AjaxResult updateVisible(@RequestBody GoviewProject goviewProject) {
        projectMapper.updateById(goviewProject);
        return success();
    }

    /**
     * 获取项目存储数据
     *
     * @param id   项目id
     * @param mmap
     * @return
     */
    @GetMapping("/getData")
    public AjaxResult getData(String projectId, ModelMap map) {
        InterceptorIgnoreHelper.handle(IgnoreStrategy.builder().tenantLine(true).build());
        GoviewProject goviewProject = projectMapper.selectById(projectId);

        if (goviewProject == null) {
            return AjaxResult.successData(200, null).put("msg", "无数据");
        }

        List<GoviewProjectData> goviewProjectDataList = projectDataMapper
                .selectList(Wrappers.<GoviewProjectData>lambdaQuery().eq(GoviewProjectData::getProjectId, projectId));
        if (CollUtil.isNotEmpty(goviewProjectDataList)) {
            goviewProject.setContent(goviewProjectDataList.get(0).getContent());
            return AjaxResult.successData(200, goviewProject).put("msg", "获取成功");
        }
        return AjaxResult.successData(200, null).put("msg", "无数据");

    }

    @PostMapping("/save/data")
    public AjaxResult saveData(@RequestBody GoviewProjectData data) {
        boolean exists = projectDataMapper
        	.exists(Wrappers.<GoviewProjectData>lambdaQuery().eq(GoviewProjectData::getProjectId, data.getProjectId()));

        if (exists) {
        	projectDataMapper.update(data,
        			Wrappers.<GoviewProjectData>lambdaQuery().eq(GoviewProjectData::getProjectId, data.getProjectId()));
        }
        else {
        	projectDataMapper.insert(data);
        }

        return AjaxResult.success("操作成功");
    }

    /**
     * 模拟请求
     *
     * @return
     */
    @PostMapping("/magicHttp")
    public AjaxResult magicHttp(@RequestBody MagicHttp magicHttp) {
        return AjaxResult.successNullData("参数异常为null");
    }

    /**
     * 上传文件
     *
     * @param file 文件流对象
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult upload(@RequestBody MultipartFile object) throws IOException {

        File dest = new File(goviewProperties.getImgPath() + object.getOriginalFilename());
        object.transferTo(dest);
        Map<String, String> map = new HashMap(4);

        String url;
        if (StrUtil.isNotBlank(goviewProperties.getHost())) {
            url = goviewProperties.getHost() + goviewProperties.getGatewayPrefix() + "/api/project/get-file/"
                    + object.getOriginalFilename();
        } else {
            url = goviewProperties.getGatewayPrefix() + "/api/project/get-file/" + object.getOriginalFilename();
        }
        map.put("link", url);

        return AjaxResult.successData(200, map);

    }

    /**
     * 文件获取
     *
     * @param fileName 文件名
     */
    @GetMapping("/get-file/{fileName}")
    public ResponseEntity<byte[]> getFile(@PathVariable String fileName) {
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载文件方式打开
        ContentDisposition contentDisposition = ContentDisposition.builder("attachment").filename(fileName).build();
        headers.setContentDisposition(contentDisposition);
        try {
            return new ResponseEntity<>(
                    FileCopyUtils.copyToByteArray(new File(goviewProperties.getImgPath() + fileName)), headers,
                    HttpStatus.OK);
        } catch (IOException e) {
            log.warn(e.getLocalizedMessage());
        }
        return null;
    }


}
