package com.jeeplus.finance.contractRegistration.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.finance.contractRegistration.domain.ContractInfo;
import com.jeeplus.finance.contractRegistration.service.ContractInfoService;
import com.jeeplus.finance.invoice.util.EasyPoiUtil;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
//import com.jeeplus.pubmodules.oss.service.dto.WorkAttachmentDto;
import com.jeeplus.sys.service.dto.UserDTO;
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 王强
 * @create: 2022-11-08 10:52
 **/
@RestController
@Api(tags ="财务合同登记管理")
@RequestMapping(value = "/contract/registration")
public class ContractInfoController {

    @Autowired
    private ContractInfoService service;

    @Resource
    private IFlowableApi flowTaskService;

    /**
     * 列表查询
     * @param info
     * @return
     */
    @ApiOperation(value = "列表查询")
    // @PreAuthorize("hasAnyAuthority('cw_work_contract_info:list')")
    @GetMapping("/list")
    public ResponseEntity<IPage<ContractInfo>> list(ContractInfo info, Page<ContractInfo> page) throws Exception {
        QueryWrapper<ContractInfo> wrapper = QueryWrapperGenerator.buildQueryCondition(info, ContractInfo.class);
        IPage<ContractInfo> list = service.list(page,info,wrapper);
        list.getRecords().stream().forEach(i -> {
            // 项目登记
            if (StringUtils.isNotBlank(i.getTaskId()) && StringUtils.isNotBlank(i.getStatus())) {
                if ("2".equals(i.getStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIds(flowTaskService.getTaskAuditUsers(i.getTaskId()));  // 获取数据审核人
                }
            }
            // 纸质归档
            if (StringUtils.isNotBlank(i.getFilePaperTaskId()) && StringUtils.isNotBlank(i.getFiledPaperType())) {
                if ("2".equals(i.getFiledPaperType())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsFP(flowTaskService.getTaskAuditUsers(i.getFilePaperTaskId()));  // 获取数据审核人
                }
            }
        });
        return ResponseEntity.ok(list);
    }

    /**
     * 合同登记新增/修改    cw:workContract:add
     */
    @ApiOperation(value = "合同登记新增/修改")
    @PreAuthorize("hasAnyAuthority('cw:workContract:add','cw:workContract:edit')")
    @PostMapping(value = "save")
    public ResponseEntity<String> save(@RequestBody ContractInfo info) throws Exception{
        String id = service.saveInfo(info);
        return ResponseUtil.newInstance().add("businessTable", "cw_work_contract_info").add("businessId", id).ok ("操作成功");
    }

    /**
     * 合同登记信息删除
     */
    @ApiOperation(value = "合同登记删除")
    @GetMapping(value = "remove")
    public ResponseEntity remove(@RequestParam String id) {
        return service.removeById(id);
    }

    /**
     * 合同登记查询
     */
    @ApiOperation(value = "合同登记查询")
    @GetMapping(value = "findById")
    public ContractInfo findById(@RequestParam String id) {
        return service.findById(id);
    }

    /**
     * 合同登记查询附件信息
     */
    @ApiOperation(value = "合同登记查询")
    @GetMapping(value = "findFileInfoById")
    public ContractInfo findFileInfoById(@RequestParam String id) {
        return service.findFileInfoById(id);
    }

    /**
     * 合同登记查询
     */
    @ApiOperation(value = "根据归档id查询")
    @GetMapping(value = "findByContractId")
    public ContractInfo findByContractId(@RequestParam String id) {
        return service.findByContractId(id);
    }

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

    /**
     * 根据id修改合同实际金额
     */
    @ApiOperation(value = "根据id修改合同实际金额")
    @PostMapping(value = "updateInfo")
    public void updateInfo(@RequestBody ContractInfo info) {
        service.updateInfo(info);
    }

    /**
     * 根据id修改纸质归档状态
     */
    @ApiOperation(value = "根据id修改纸质归档状态")
    @PostMapping(value = "updatePaperInfo")
    public void updatePaperInfo(@RequestBody ContractInfo info) {
        service.updatePaperInfo(info);
    }

    @ApiOperation(value = "根据客户id查询关联的项目")
    @GetMapping("/getByClientId")
    public ResponseEntity<List<ContractInfo>> getByClientId(String contractId, ContractInfo contractInfo) {
        List<ContractInfo> list = service.getByClientId(contractId,contractInfo);
        return ResponseEntity.ok(list);
    }


    @ApiLog(value = "兴光会计合同数据导出", type = LogTypeEnum.EXPORT)
    @GetMapping("exportFile")
    @ApiOperation(value = "兴光会计合同数据导出")
    public void exportFile(ContractInfo info, Page <ContractInfo> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        QueryWrapper<ContractInfo> wrapper = QueryWrapperGenerator.buildQueryCondition(info, ContractInfo.class);
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<ContractInfo> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = service.list (page,info,wrapper).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = service.list (page,info,wrapper).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = service.list (page,info,wrapper).getRecords();
        }
        try {
            EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, ContractInfo.class, fileName, response );
        }catch (Exception e){
            System.out.println(e);
        }

    }
}
