package com.jeeplus.assess.assessSignatureDaily.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.assess.assessSignatureDaily.domain.AssessSignatureProjectReportRelation;
import com.jeeplus.assess.assessSignatureDaily.service.AssessSignatureProjectReportService;
import com.jeeplus.assess.assessSignatureDaily.service.dto.AssessSignatureProjectReportRelationDTO;
import com.jeeplus.assess.projectRecords.Utils.EasyPoiUtil;
import com.jeeplus.assess.utils.SignaturePostUtil;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.common.utils.ResponseUtil;

import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.feign.IUserApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Api(tags ="报告签章")
@RequestMapping(value = "/assess/signatureReport")
public class AssessSignatureProjectReportController {

    @Resource
    private AssessSignatureProjectReportService signatureProjectReportService;

    @Autowired
    private RedisUtils redisUtils;



    /**
     * 列表查询
     * @param
     * @return
     */
    @ApiOperation(value = "列表查询")
    @GetMapping("/list")
    public ResponseEntity<IPage<AssessSignatureProjectReportRelationDTO>> list(Page<AssessSignatureProjectReportRelationDTO> page, AssessSignatureProjectReportRelationDTO dto) throws Exception{
        IPage<AssessSignatureProjectReportRelationDTO> iPage = signatureProjectReportService.list(page, dto);
        return ResponseEntity.ok(iPage);
    }

    /**
     * 根据id查询数据
     */
    @ApiOperation(value = "查询")
    @GetMapping("/findById")
    public ResponseEntity<AssessSignatureProjectReportRelationDTO> findById(@RequestParam String id) throws Exception{
        AssessSignatureProjectReportRelationDTO dto = signatureProjectReportService.findById(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 新增/修改
     * @param dto
     * @return
     */
    @ApiOperation(value = "新增、修改")
    @PostMapping("/save")
    public ResponseEntity<String> save(@RequestBody AssessSignatureProjectReportRelationDTO dto) throws Exception{
        AssessSignatureProjectReportRelation s = signatureProjectReportService.save(dto);
        return ResponseUtil.newInstance().add("businessTable", "signature_project_report_relation")
                .add("businessId", s.getId())
                .add("number", s.getNumber())
                .ok ("操作成功");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @GetMapping("/remove")
    public ResponseEntity<String> remove(@RequestParam String id){
        String s = signatureProjectReportService.remove(id);
        return ResponseEntity.ok(s);
    }

    /**
     * 根据id修改状态status
     */
    @ApiOperation(value = "根据id修改状态status")
    @PostMapping(value = "updateStatusById")
    public void updateStatusById(@RequestBody AssessSignatureProjectReportRelationDTO dto) {
        signatureProjectReportService.updateStatusById(dto);
    }

    @ApiLog(value = "报告签章数据", type = LogTypeEnum.EXPORT)
    @GetMapping("exportFile")
    @ApiOperation(value = "报告签章数据")
    public void exportFile(Page<AssessSignatureProjectReportRelationDTO> page, AssessSignatureProjectReportRelationDTO dto, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<AssessSignatureProjectReportRelationDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = signatureProjectReportService.list2 (page,dto).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = signatureProjectReportService.list2 (page,dto).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = signatureProjectReportService.list2 (page,dto).getRecords();
        }
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, AssessSignatureProjectReportRelationDTO.class, fileName, response );

    }

    /**
     * 根据报告签章id查询签章审核节点信息
     * @param id
     * @return
     */
    @ApiLog("根据报告签章id查询签章审核节点信息")
    @GetMapping("getAuditNodeById")
    public ResponseEntity getAuditNodeById(@RequestParam("id") String id) {
        Map<String, Object> auditNodeByReportId = signatureProjectReportService.getAuditNodeById(id);
        return ResponseEntity.ok (auditNodeByReportId);
    }

    /**
     * 根据报告签章id查询签章审核节点信息
     * @param id
     * @return
     */
    @ApiLog("根据报告签章id查询签章审核节点信息")
    @GetMapping("getSignatureTypeById")
    public ResponseEntity getSignatureTypeById(@RequestParam("id") String id) {
        Map<String, Object> signatureTypeById = signatureProjectReportService.getSignatureTypeById(id);
        return ResponseEntity.ok (signatureTypeById);
    }

    /**
     * 签章链接
     * @param dto
     * @return
     */
    @ApiLog(value = "签章链接", type = LogTypeEnum.SAVE)
    @PostMapping("saveFlowableParam")
    public ResponseEntity<String> saveFlowableParam(@Valid @RequestBody AssessSignatureProjectReportRelationDTO dto) {

        AssessSignatureProjectReportRelationDTO relationDTO = signatureProjectReportService.findById(dto.getId());
        // 获取签章页面url
        String mobile = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken()).getMobile();
        String signatureContractUrl = SignaturePostUtil.getSignatureContractUrl(relationDTO.getSignatureContractId(), mobile);
        // 将数据存储到redis中，key为contractId
        redisUtils.set("assess_signature_report_" + relationDTO.getSignatureContractId(),relationDTO.getId());
        redisUtils.expire("assess_signature_report_" + relationDTO.getSignatureContractId(),24, TimeUnit.HOURS);
        return ResponseEntity.ok(signatureContractUrl);
    }


}
