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.AssessSignatureDailyOfficeWork;
import com.jeeplus.assess.assessSignatureDaily.service.AssessSignatureDailyOfficeWorkService;
import com.jeeplus.assess.assessSignatureDaily.service.dto.AssessSignatureDailyOfficeWorkDTO;
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.apache.commons.lang3.StringUtils;
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/signatureDaily")
public class AssessSignatureDailyOfficeWorkController {

    @Resource
    private AssessSignatureDailyOfficeWorkService signatureDaulyOfficeWorkService;

    @Autowired
    private RedisUtils redisUtils;


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

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

    /**
     * 新增/修改
     * @param dto
     * @return
     */
    @ApiOperation(value = "新增、修改")
    @PostMapping("/save")
    public ResponseEntity<String> save(@RequestBody AssessSignatureDailyOfficeWorkDTO dto) throws Exception{
        AssessSignatureDailyOfficeWork s = signatureDaulyOfficeWorkService.save(dto);
        return ResponseUtil.newInstance().add("businessTable", "signature_daily_office_work")
                .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 = signatureDaulyOfficeWorkService.remove(id);
        return ResponseEntity.ok(s);
    }

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

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

    }

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

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

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

}
