package com.dayou.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dayou.annotation.IgnoreAuth;
import com.dayou.common.BaseEntity;
import com.dayou.common.DownloadModel;
import com.dayou.dto.NameUrlDTO;
import com.dayou.dto.TaskRecordDTO;
import com.dayou.entity.BusinessReply;
import com.dayou.entity.PersonalProduction;
import com.dayou.exception.ErrorCode;
import com.dayou.utils.HttpKit;
import com.dayou.workflow.annotation.FinishTask;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dayou.service.IPersonalProductionService;
import com.dayou.common.RestResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import static com.dayou.exception.ErrorCode.DEFAULTERROR;

/**
 * 个贷产品
 *
 * @author wucl
 * @since 2024-03-18
 */
@RestController
@RequestMapping("personalProduction")
@Slf4j
public class PersonalProductionController extends BaseController {
    @Autowired
    private IPersonalProductionService personalProductionService;


    /**
     * 个贷产品文档生成
     */
    @GetMapping("/{personalId}/{tag}")
    public RestResponse<Boolean> genFile(@PathVariable("personalId") Long personalId,@PathVariable("tag") Integer tag) throws JsonProcessingException {
        Boolean ret = personalProductionService.genFile(personalId,tag);
        return RestResponse.data(ret);
     }

    /**
     * 个贷产品文档一键生成
     */
    @GetMapping("/gen/{personalId}")
    public RestResponse<Boolean> genFile(@PathVariable("personalId") Long personalId){
        Boolean ret = personalProductionService.genFile(personalId);
        return RestResponse.data(ret);
    }

    /**
     * 产品包
     * @param targetId
     * @return
     */
    @GetMapping("/{targetId}")
     public RestResponse<List<PersonalProduction>> getProductions(@PathVariable("targetId") Long targetId){
        List<PersonalProduction> list = personalProductionService.list(new LambdaQueryWrapper<PersonalProduction>().eq(PersonalProduction::getTargetId, targetId).eq(BaseEntity::getDeleted, Boolean.FALSE));
        return RestResponse.data(list);
    }

    /**
     * 上传产品文档
     */
    @IgnoreAuth
    @PostMapping("/upload/{targetId}/{tag}")
    public RestResponse<Boolean> upload(MultipartFile file,@PathVariable("targetId") Long targetId,@PathVariable("tag") Integer tag) {
        try {
            // 上传文件路径
            String filePath = dfsConfig.getPath();
            Boolean ret = personalProductionService.upload(filePath, file,targetId,tag);
            return RestResponse.data(ret);
        } catch (Exception e) {
            log.error("upload error", e);
            ErrorCode.throwBusinessException(DEFAULTERROR);
        }

        return RestResponse.error();
    }

    /**
     * 移除文件
     * @param id
     * @return
     */
    @GetMapping("/remove/{id}")
    public RestResponse<Boolean> removeFile(@PathVariable("id") Long id){
        Boolean ret = personalProductionService.removeFile(id);
        return RestResponse.data(ret);
    }

    @GetMapping("/downloadPkg/{targetId}")
    public void downloadPkg(@PathVariable("targetId") Long targetId) throws IOException {
        List<PersonalProduction> productions = personalProductionService.list(new LambdaQueryWrapper<PersonalProduction>().
                select(PersonalProduction::getFilePath).isNotNull(PersonalProduction::getFilePath).
                eq(PersonalProduction::getTargetId,targetId).eq(BaseEntity::getDeleted,Boolean.FALSE));
        List<DownloadModel> downloadModels = productions.stream().map(x -> {
            DownloadModel downloadModel = new DownloadModel();
            NameUrlDTO nameUrl = JSON.parseObject(x.getFilePath(), NameUrlDTO.class);
            downloadModel.setDownloadUrl(nameUrl.getUrl());
            downloadModel.setNewFileName(nameUrl.getName());
            return downloadModel;
        }).collect(Collectors.toList());
        String newFileName = downloadModels.get(0).getNewFileName();
        String orderId = newFileName.substring(0, 10);
        packageFile2Zip(orderId+"产品包", HttpKit.getResponse(), downloadModels);
    }

    /**
     * 审核产品
     * @param taskRecordDTO
     * @return
     */
    @FinishTask
    @PutMapping("/pass")
    public RestResponse<Boolean> checkPass(@RequestBody TaskRecordDTO<PersonalProduction> taskRecordDTO){
        Boolean ret = personalProductionService.checkPass(taskRecordDTO);
        return RestResponse.data(ret);
    }

    /**
     * 产品入库
     * @param taskRecordDTO
     * @return
     */
    @FinishTask
    @PostMapping("/in")
    public RestResponse<Boolean> repertoryIn(@RequestBody @Valid TaskRecordDTO<PersonalProduction> taskRecordDTO){
        Boolean ret = personalProductionService.repertoryIn(taskRecordDTO);
        return RestResponse.data(ret);
    }

    /**
     * 产品出库
     * @param taskRecordDTO
     * @return
     */
    @FinishTask
    @PostMapping("/out")
    public RestResponse<Boolean> repertoryOut(@RequestBody @Valid TaskRecordDTO<PersonalProduction> taskRecordDTO){
        Boolean ret = personalProductionService.repertoryOut(taskRecordDTO);
        return RestResponse.data(ret);
    }
}

