package com.jeeplus.finance.signatureDaily.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.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.finance.invoice.util.EasyPoiUtil;
import com.jeeplus.finance.invoice.util.SignaturePostUtil;
import com.jeeplus.finance.projectReport.domain.CwProjectReportData;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.domain.CwReimbursementInfo;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.service.dto.QueryListDto;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.service.dto.RetureListDto;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.service.dto.SaveInfoDto;
import com.jeeplus.finance.signatureDaily.domain.SignatureDailyOfficeWork;
import com.jeeplus.finance.signatureDaily.service.SignatureDaulyOfficeWorkService;
import com.jeeplus.finance.signatureDaily.service.dto.SignatureDailyOfficeWorkDTO;
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 = "/cw/signatureDaily")
public class SignatureDailyOfficeWorkController {

    @Resource
    private SignatureDaulyOfficeWorkService signatureDaulyOfficeWorkService;
    @Autowired
    private RedisUtils redisUtils;

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

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

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

    @ApiLog(value = "日常签章数据", type = LogTypeEnum.EXPORT)
    @GetMapping("exportFile")
    @ApiOperation(value = "日常签章数据")
    public void exportFile(Page<SignatureDailyOfficeWorkDTO> page, SignatureDailyOfficeWorkDTO dto, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<SignatureDailyOfficeWorkDTO> 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, SignatureDailyOfficeWorkDTO.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 SignatureDailyOfficeWorkDTO dto) {

        SignatureDailyOfficeWorkDTO 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("cw_signature_report_" + dailyOfficeWorkDTO.getSignatureContractId(),dailyOfficeWorkDTO.getId());
        redisUtils.expire("cw_signature_report_" + dailyOfficeWorkDTO.getSignatureContractId(),24, TimeUnit.HOURS);
        return ResponseEntity.ok(signatureContractUrl);
    }

}
