package com.zjty.inspect.controller;

import com.alibaba.fastjson.JSON;
import com.zjty.inspect.aop.AuthAnnotation;
import com.zjty.inspect.entity.*;
import com.zjty.inspect.service.EvaluationService;
import com.zjty.inspect.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author mcj
 */
@RestController
@RequestMapping("/evaluation")
@Api(value = "评估报告管理接口", description = "评估报告管理接口,提供页面的增、删、改、查")
public class EvaluationController {
    private final EvaluationService evaluationService;

    public EvaluationController(EvaluationService evaluationService) {
        this.evaluationService = evaluationService;
    }


    /**
     * 新增评估报告
     *
     * @param evaluation 评估报告
     * @return
     */
    @PostMapping
    @ApiOperation("新增评估报告")
    public ServerResponse<Evaluation> rule(@RequestBody Evaluation evaluation) {
        Evaluation newEvaluation = evaluationService.save(evaluation);
        return ServerResponse.ok(newEvaluation);
    }

    @ApiOperation("根据用户名查询最新的报告输出")
    @GetMapping(value = "/eva")
    public ServerResponse<AssessmentReport> getName(@RequestParam String name, @RequestParam String id) {
        if (StringUtils.isEmpty(id) || "null".equals(id)) {
            Evaluation e = evaluationService.findByName(name);
            if (e != null) {
                AssessmentReport assessmentReport = JSON.parseObject(e.getOutEva(), AssessmentReport.class);
                return ServerResponse.ok(assessmentReport);
            }
            return ServerResponse.ok(null);
        }
        Evaluation evaluation = evaluationService.findById(id);
        if (evaluation != null) {
            AssessmentReport assessmentReport = JSON.parseObject(evaluation.getOutEva(), AssessmentReport.class);
            return ServerResponse.ok(assessmentReport);
        }
        return ServerResponse.ok(null);
    }

    @ApiOperation("根据id查询输入")
    @GetMapping(value = "/in/{name}")
    public ServerResponse<Reform> getInName(@PathVariable String name) {
        Evaluation evaluation = evaluationService.findById(name);
        if (evaluation != null) {
            Reform reform = JSON.parseObject(evaluation.getInEva(), Reform.class);
            return ServerResponse.ok(reform);
        }
        return ServerResponse.ok(null);
    }

    @ApiOperation("根据id查询输入")
    @GetMapping(value = "/all/{id}")
    @AuthAnnotation(code = {"000800"})
    public ServerResponse<Evaluation> getInId(@PathVariable String id) {
        Evaluation evaluation = evaluationService.findById(id);
        if (evaluation != null) {
            return ServerResponse.ok(evaluation);
        }
        return ServerResponse.ok(null);
    }
    @ApiOperation("根据报告id查询excel输入")
    @GetMapping(value = "/in/excel/{id}")
    public ServerResponse<List<ExcelDataTemp>> exportInName(@PathVariable String id) {
        Evaluation evaluation = evaluationService.findById(id);
        if (evaluation != null) {
            List<ExcelDataTemp> excelDataTemp = ExcelUtil.parseExcel2Entity(evaluation);
            return ServerResponse.ok(excelDataTemp);
        } else {
            return ServerResponse.ok(new ArrayList<>());
        }
    }

    /**
     * 修改评估报告
     *
     * @param evaluation 规则封装
     * @param id         id
     */
    @PostMapping(value = "/{id}")
    @ApiOperation("修改评估报告")
    @AuthAnnotation(code = {"000800"})
    public ServerResponse<Integer> update(@RequestBody Evaluation evaluation, @PathVariable String id) {
        evaluation.setId(id);
        evaluationService.update(evaluation);
        return ServerResponse.ok(200);
    }

    /**
     * 根据id删除评估报告
     *
     * @param id id
     */
    @ApiOperation("根据id删除评估报告")
    @DeleteMapping(value = "/{id}")
    @AuthAnnotation(code = {"000800"})
    public ServerResponse<Integer> deleteById(@PathVariable String id) {
        evaluationService.delete(id);
        return ServerResponse.ok(200);
    }

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @ApiOperation("分页查询页面列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页记录数", required = true, paramType = "path", dataType = "int")
    })
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    @AuthAnnotation(code = {"000800"})
    public ServerResponse<PageResult<Evaluation>> findSearch(@RequestBody Map<String,String> searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Evaluation> pageList = evaluationService.findSearch(searchMap, page, size);
        return ServerResponse.ok(new PageResult<>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 获取评估报告内的输出，转换为map结构
     *
     * @param id id
     * @return wps
     */
    @GetMapping(value = "/map/{id}")
    @ApiOperation("获取评估报告内的map ")
    public ServerResponse<Map<String, String>> findAll(@PathVariable String id) {
        Evaluation evaluation = evaluationService.findById(id);
        Map<String, String> wps = WpsUtil.createWps(evaluation);
        return ServerResponse.ok(wps);
    }
    @ApiOperation("下载报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "报告主键"),
            @ApiImplicitParam(name="danjia",value = "单价"),
            @ApiImplicitParam(name="yusuan",value = "总预算金额"),
            @ApiImplicitParam(name="gong",value = "工作量"),
            @ApiImplicitParam(name="ewai",value = "额外申请"),
            @ApiImplicitParam(name="agree",value = "0不同意 1同意")
    })
    @PostMapping("/downloadWps")
    public ServerResponse download(@RequestBody Download download){
//        return ResponseEntity.ok("http://120.55.57.35:12345/static/uplaods/a36b17568d4e466dacf9f088a29b4dbc.docx");
//        return ResponseEntity.ok("http://120.55.57.35:8078/static/defult.docx");
        Evaluation evaluation = evaluationService.findById(download.getId());
        Map<String, String> wps = WpsUtil.createWps(evaluation);
        wps.put("danjia",download.getDanjia());
        wps.put("yusuan",download.getYusuan());
        wps.put("gong",download.getGong());
        wps.put("ewai",download.getEwai());
        Double aDouble = Double.valueOf(download.getDanjia());
        BigDecimal b1 = BigDecimal.valueOf(aDouble);
        BigDecimal b2 = BigDecimal.valueOf(1.5);
        double v = b1.subtract(b2).doubleValue();
        String format = new DecimalFormat("0.00").format(v);
        wps.put("rgcz",format);
        if(download.getAgree().equals("1")) {
            wps.put("agree", "同意");
        }else{
            wps.put("agree", "不同意");
        }
        Set<String> strings = wps.keySet();
        for (String str : strings) {
            String s = wps.get(str);
            if(!StringUtils.isEmpty(s)&&s.equals("-1")){
                wps.put(str,"0");
            }else if(StringUtils.isEmpty(s)){
                wps.put(str,"无");
            }
        }

        String w = FreeMakerUtils.parseTpl("reportTemplate", wps);
        if(StringUtils.isEmpty(w)){
            return ServerResponse.error(500);
        }
        return ServerResponse.ok(w);
    }
}
