package com.artfess.yhxt.basedata.controller;


import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.util.ZipUtil;
import com.artfess.file.util.MinioUtil;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.yhxt.basedata.model.Accessory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.artfess.base.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


/**
 * 附件表 前端控制器
 *
 * @company 阿特菲斯信息技术有限公司
 * @author wangping
 * @since 2021-08-03
 */
@RestController
@Slf4j
@RequestMapping("/bizAccessory/v1/")
@Api(tags = "附件管理")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
public class AccessoryController extends BaseController<AccessoryManager, Accessory> {
    @Resource
    AccessoryManager accessoryManager;


    @PostMapping("/minioDrawingUpload")
    @ApiOperation(value = "工程图纸文件上传接口")
    public CommonResult<String> minioDrawingUpload(MultipartFile file,
                                                   @ApiParam(name = "sourceId", value = "资源Id", required = true)
                                                   @RequestParam(value = "sourceId", required = true) String sourceId) {

        return new CommonResult<>(this.baseService.minioDrawingUpload(file, sourceId));
    }

    @PostMapping("/minioWorkOrderUpload")
    @ApiOperation(value = "工单施工图片上传")
    public String minioWorkOrderUpload(MultipartFile file,
                                                   @ApiParam(name = "sourceId", value = "资源Id", required = true)
                                                   @RequestParam(value = "sourceId", required = true) String sourceId) {

        return this.baseService.minioDrawingUpload(file, sourceId);
    }


    @RequestMapping(value = "/saveAccessory", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存,修改附件信息", httpMethod = "POST")
    public CommonResult<String> saveAccessory(@ApiParam(name = "bizBridgeInformation", value = "桥梁对象") @RequestBody Accessory accessory) throws Exception {
        String msg = "添加成功";

        if (StringUtils.isEmpty(accessory.getId())) {
            accessory.setIsDele("0");
            baseService.create(accessory);
        } else {
            baseService.update(accessory);
            msg = "修改成功";
        }
        return new CommonResult<String>(msg);
    }

    @RequestMapping(value = "/getJson", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "分页查询附件信息", httpMethod = "POST")
    public PageList<Accessory> getJson(@ApiParam(name = "queryFilter", value = "分页查询信息") @RequestBody QueryFilter<Accessory> queryFilter) {
        queryFilter.addFilter("is_dele_", "0", QueryOP.EQUAL);
        PageList<Accessory> pageList = baseService.query(queryFilter);
        return pageList;
    }


    @GetMapping(value = "get/{id}")
    @ApiOperation(value = "根据ID查询附件信息", httpMethod = "GET", notes = "根据ID查询附件信息")
    public Accessory get(@ApiParam(name = "id", value = "业务对象主键", required = true) @PathVariable String id) throws Exception {
        return baseService.getById(id);
    }

    @GetMapping(value = "getBySourceId/{id}")
    @ApiOperation(value = "根据sourceID查询附件信息", httpMethod = "GET", notes = "根据ID查询附件信息")
    public List<Accessory> getBySourceId(@ApiParam(name = "id", value = "业务对象主键", required = true) @PathVariable String id) throws Exception {


        return this.baseService.getAccessoryBySourceId(id);
    }

    @RequestMapping(value = "/updateBridge", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "逻辑删除附件信息", httpMethod = "POST", notes = "逻辑删除附件信息")
    public CommonResult<String> updateBridge(@ApiParam(name = "ids", value = "可视化分类ID集合以，隔开", required = true)
                                             @RequestParam(value = "ids", required = true) String ids) throws Exception {
        if (StringUtils.isNotBlank(ids)) {
            List<String> idsList = Arrays.asList(ids.split(","));
            UpdateWrapper<Accessory> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("id_", idsList);
            updateWrapper.set("is_dele_", "1");
            baseService.update(null, updateWrapper);
        }
        return new CommonResult<>(true, "删除成功");
    }


    @RequestMapping("/minioDrawingdownFile")
    @ApiOperation(value = "工程图纸文件导出接口", httpMethod = "GET", notes = "工程图纸文件导出接口")
    public void downFile(HttpServletResponse response, @ApiParam(name = "ids", value = "多个主键之间用逗号分隔", required = true) @RequestParam String ids) {
        if (StringUtils.isNotBlank(ids)) {
            try {
                List<String> idsList = Arrays.asList(ids.split(","));
                QueryWrapper<Accessory> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("id_", idsList);
                queryWrapper.ne("is_dele_", "1");
                //文件保存目录
                String path = System.getProperty("user.dir") + "\\access";
                //1.执行sql,查询数据
                List<Accessory> accessoryList = baseService.list(queryWrapper);
                //2.遍历结果，拿到url，从minio上读取文件
                if (null != accessoryList && accessoryList.size() > 0) {
                    for (Accessory accessory : accessoryList) {
                        String url = accessory.getUrl();
                        String name = accessory.getName();
                        InputStream fileStream = MinioUtil.getMinioFile("yhxt", url, false);
                        String filePath = path + "\\" + name;
                        File targetFile = new File(filePath);
                        if (!targetFile.exists()) {
                            if (!targetFile.getParentFile().exists()) {
                                targetFile.getParentFile().mkdir();
                            }
                            targetFile.createNewFile();
                        }
                       // FileWriter fileWriter = new FileWriter(filePath);
                        log.info(String.format("文件的路径%s", filePath));
                        //将流转成File格式
                        FileUtils.copyInputStreamToFile(fileStream, targetFile);
                    }
                    log.info(String.format("文件的导出路径%s", path));
                    //3.压缩文件
                    ZipUtil.zip(path, true);
                    HttpUtil.downLoadFile(response, path + ".zip", "工程图纸文件.zip");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
    @RequestMapping(value = "updateAccessory", method = RequestMethod.DELETE, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "批量逻辑删除", httpMethod = "DELETE", notes = "批量逻辑删除")
    public CommonResult<String> updateAccessory(
            @ApiParam(name = "ids", value = "附件ID集合以，隔开", required = true)
            @RequestParam(value = "ids", required = true) String ids) throws Exception {
        if (StringUtils.isNotBlank(ids)) {
            List<String> idsList = Arrays.asList(ids.split(","));
            UpdateWrapper<Accessory> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("id_", idsList);
            updateWrapper.set("is_dele_", "1");
            accessoryManager.update(null, updateWrapper);

        }

        return new CommonResult<>(true, "批量删除成功");
    }

    @GetMapping("/minIoAllDownFile")
    @ApiOperation(value = "通用下载接口", httpMethod = "POST", notes = "通用下载接口")
    public void downTest( @ApiParam(name = "ids", value = "ids", required = true)
                              @RequestParam(value = "ids", required = true) String ids,
                          @ApiParam(name = "bizPath", value = "bizPath", required = true)
                              @RequestParam(value = "bizPath", required = true)String bizPath,HttpServletResponse response) throws Exception {
//        this.baseService.minIoDownFile(ids,"contract","download/contract","yhxt",response);
        this.baseService.minIoDownFile(ids, bizPath,response);
    }

    @RequestMapping("/minioUpload")
    @ApiOperation(value = "附件上传接口", httpMethod = "POST", notes = "附件上传接口")
    public CommonResult<Accessory> minioUpload(MultipartFile file,String bizPath ,HttpServletResponse response) throws Exception {
        Accessory accessory = this.baseService.minioUpload(file,bizPath, response);
        return new CommonResult<Accessory>(true, "上传成功",accessory);
    }

}
