package cn.iocoder.yudao.module.asset.controller.admin.contract;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.asset.controller.admin.contract.vo.*;
import cn.iocoder.yudao.module.asset.convert.contract.ContractConvert;
import cn.iocoder.yudao.module.asset.dal.dataobject.contract.*;
import cn.iocoder.yudao.module.asset.dal.mysql.contract.*;
import cn.iocoder.yudao.module.asset.service.contract.ContractService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 车辆租赁合同 Controller
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 车辆租赁合同管理")
@RestController
@RequestMapping("/asset/contract")
@Validated
public class ContractController {

    @Resource
    private ContractService contractService;

    @Resource
    private ContractVehicleMapper contractVehicleMapper;

    @Resource
    private ContractVehicleServiceMapper contractVehicleServiceMapper;

    @Resource
    private ContractAuthorizedMapper contractAuthorizedMapper;

    @Resource
    private ContractChangeHistoryMapper contractChangeHistoryMapper;

    @PostMapping("/create")
    @Operation(summary = "创建合同")
    @PreAuthorize("@ss.hasPermission('asset:contract:create')")
    public CommonResult<Long> createContract(@Valid @RequestBody ContractSaveReqVO createReqVO) {
        return success(contractService.createContract(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新合同")
    @PreAuthorize("@ss.hasPermission('asset:contract:update')")
    public CommonResult<Boolean> updateContract(@Valid @RequestBody ContractSaveReqVO updateReqVO) {
        contractService.updateContract(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除合同")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('asset:contract:delete')")
    public CommonResult<Boolean> deleteContract(@RequestParam("id") Long id) {
        contractService.deleteContract(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Operation(summary = "批量删除合同")
    @Parameter(name = "ids", description = "编号列表", required = true)
    @PreAuthorize("@ss.hasPermission('asset:contract:delete')")
    public CommonResult<Boolean> deleteContractList(@RequestParam("ids") List<Long> ids) {
        for (Long id : ids) {
            contractService.deleteContract(id);
        }
        return success(true);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出合同 Excel")
    @PreAuthorize("@ss.hasPermission('asset:contract:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportContractExcel(HttpServletResponse response, @Valid ContractPageReqVO exportReqVO) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ContractDO> list = contractService.getContractPage(exportReqVO).getList();
        // 输出
        ExcelUtils.write(response, "车辆租赁合同.xls", "合同数据", ContractExcelVO.class,
                BeanUtils.toBean(list, ContractExcelVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "获得合同详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('asset:contract:query')")
    public CommonResult<ContractDetailRespVO> getContract(@RequestParam("id") Long id) {
        return success(contractService.getContractDetail(id));
    }

    @GetMapping("/page")
    @Operation(summary = "获得合同分页")
    @PreAuthorize("@ss.hasPermission('asset:contract:query')")
    public CommonResult<PageResult<ContractRespVO>> getContractPage(@Valid ContractPageReqVO pageReqVO) {
        PageResult<ContractDO> pageResult = contractService.getContractPage(pageReqVO);
        PageResult<ContractRespVO> voPage = ContractConvert.INSTANCE.convertPage(pageResult);
        // 填充车辆数和已交车辆数
        for (ContractRespVO vo : voPage.getList()) {
            List<ContractVehicleDO> vehicles = contractVehicleMapper.selectListByContractId(vo.getId());
            vo.setVehicleCount(vehicles.size());
            vo.setDeliveredCount((int) vehicles.stream()
                    .filter(v -> Integer.valueOf(1).equals(v.getVehicleStatus()))
                    .count());
        }
        return success(voPage);
    }

    @GetMapping("/change-history")
    @Operation(summary = "获得合同变更历史")
    @Parameter(name = "contractId", description = "合同ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('asset:contract:query')")
    public CommonResult<List<ContractChangeHistoryDO>> getChangeHistory(@RequestParam("contractId") Long contractId) {
        return success(contractChangeHistoryMapper.selectListByContractId(contractId));
    }

    @PostMapping("/submit-approval")
    @Operation(summary = "提交合同审批")
    @Parameter(name = "id", description = "合同ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('asset:contract:update')")
    public CommonResult<String> submitApproval(@RequestParam("id") Long id) {
        return success(contractService.submitContractApproval(id));
    }

    @PostMapping("/withdraw-approval")
    @Operation(summary = "撤回合同审批")
    @Parameter(name = "id", description = "合同ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('asset:contract:update')")
    public CommonResult<Boolean> withdrawApproval(@RequestParam("id") Long id) {
        contractService.withdrawContractApproval(id);
        return success(true);
    }

    @PostMapping("/terminate")
    @Operation(summary = "终止合同")
    @PreAuthorize("@ss.hasPermission('asset:contract:update')")
    public CommonResult<Boolean> terminateContract(@RequestParam("id") Long id,
                                                    @RequestParam("reason") String reason) {
        contractService.terminateContract(id, reason);
        return success(true);
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获得合同精简列表", description = "用于下拉选择")
    public CommonResult<List<ContractSimpleRespVO>> getContractSimpleList() {
        List<ContractDO> list = contractService.getContractSimpleList();
        return success(BeanUtils.toBean(list, ContractSimpleRespVO.class));
    }

    @PostMapping("/renew")
    @Operation(summary = "续签合同")
    @PreAuthorize("@ss.hasPermission('asset:contract:create')")
    public CommonResult<Long> renewContract(@RequestParam("id") Long id,
                                            @Valid @RequestBody ContractSaveReqVO newContractReqVO) {
        return success(contractService.renewContract(id, newContractReqVO));
    }

    @PostMapping("/convert-to-third-party")
    @Operation(summary = "变更为三方合同")
    @PreAuthorize("@ss.hasPermission('asset:contract:update')")
    public CommonResult<Long> convertToThirdParty(@RequestParam("id") Long id,
                                                   @Valid @RequestBody ContractSaveReqVO newContractReqVO) {
        return success(contractService.convertToThirdParty(id, newContractReqVO));
    }

    @PostMapping("/convert-to-formal")
    @Operation(summary = "试用合同转正式")
    @PreAuthorize("@ss.hasPermission('asset:contract:update')")
    public CommonResult<Long> convertToFormal(@RequestParam("id") Long id,
                                               @Valid @RequestBody ContractSaveReqVO newContractReqVO) {
        return success(contractService.convertToFormal(id, newContractReqVO));
    }

    @PostMapping("/add-vehicle")
    @Operation(summary = "往现有合同追加车辆")
    @PreAuthorize("@ss.hasPermission('asset:contract:update')")
    public CommonResult<Boolean> addVehicle(@RequestParam("id") Long id,
                                             @Valid @RequestBody List<ContractSaveReqVO.ContractVehicleSaveVO> vehicles) {
        contractService.addVehiclesToContract(id, vehicles);
        return success(true);
    }

    @PostMapping("/upload-seal")
    @Operation(summary = "上传盖章合同附件")
    @PreAuthorize("@ss.hasPermission('asset:contract:update')")
    public CommonResult<Boolean> uploadSeal(@RequestParam("id") Long id,
                                             @RequestParam("fileUrl") String fileUrl,
                                             @RequestParam("fileName") String fileName) {
        contractService.uploadSealedContract(id, fileUrl, fileName);
        return success(true);
    }

}
