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

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.enums.GeneralStatusEnum;
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.contract.controller.admin.suppliercontract.vo.*;
import cn.iocoder.yudao.module.contract.dal.dataobject.suppliercontract.SupplierContractDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.suppliercontract.SupplierContractHistoryDO;
import cn.iocoder.yudao.module.contract.enums.ContractStatusEnum;
import cn.iocoder.yudao.module.contract.service.suppliercontract.SupplierContractService;
import cn.iocoder.yudao.module.employee.api.EmployeeApi;
import cn.iocoder.yudao.module.employee.api.dto.EmployeeRespDTO;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.infra.api.file.dto.FileDTO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

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

@Tag(name = "管理后台 - 采购合同信息")
@RestController
@RequestMapping("/finance/contract/supplier-contract")
@Validated
public class SupplierContractController {

    @Resource
    private SupplierContractService supplierContractService;

    @Resource
    private EmployeeApi employeeApi;

    @Resource
    private DeptApi deptApi;

    @Resource
    private FileApi fileApi;

    @GetMapping("/getSupplierContractCode")
    @Operation(summary = "获取采购合同编号")
    @ApiOperationSupport(order = 1)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:create')")
    public CommonResult<String> getSupplierContractCode() {
        return success(supplierContractService.getSupplierContractCode());
    }

    @PostMapping("/create")
    @Operation(summary = "创建采购合同信息")
    @ApiOperationSupport(order = 2)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:create')")
    public CommonResult<Long> createSupplierContract(@Valid @RequestBody SupplierContractSaveReqVO createReqVO) {
        return success(supplierContractService.createSupplierContract(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新采购合同信息")
    @ApiOperationSupport(order = 3)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:update')")
    public CommonResult<Boolean> updateSupplierContract(@Valid @RequestBody SupplierContractSaveReqVO updateReqVO) {
        supplierContractService.updateSupplierContract(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除采购合同信息")
    @ApiOperationSupport(order = 4)
    @Parameter(name = "id", description = "主键id", required = true)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:delete')")
    public CommonResult<Boolean> deleteSupplierContract(@RequestParam("id") Long id) {
        supplierContractService.deleteSupplierContract(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得采购合同信息")
    @ApiOperationSupport(order = 5)
    @Parameter(name = "id", description = "主键id", required = true, example = "1")
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:query')")
    public CommonResult<SupplierContractRespVO> getSupplierContract(@RequestParam("id") Long id) {
        SupplierContractDO supplierContract = supplierContractService.getSupplierContract(id);
        if (Objects.isNull(supplierContract)) {
            return success(null);
        }
        SupplierContractRespVO supplierContractRespVO = BeanUtils.toBean(supplierContract, SupplierContractRespVO.class);
        // 是否描述集合
        Map<Integer, String> generalStatusMap = Arrays.stream(GeneralStatusEnum.values())
                .collect(Collectors.toMap(GeneralStatusEnum::getStatus, GeneralStatusEnum::getName));
        // 是否框架合同
        supplierContractRespVO.setIsFrameContractDesc(generalStatusMap.getOrDefault(supplierContract.getIsFrameContract(), "未知"));
        // 负责人名称
        EmployeeRespDTO ownerEmployee = employeeApi.getEmployeeById(supplierContract.getOwnerEmployeeId());
        if (Objects.nonNull(ownerEmployee)) {
            supplierContractRespVO.setOwnerEmployeeName(ownerEmployee.getName());
        }
        // 部门名称
        DeptRespDTO ownerDept = deptApi.getDept(supplierContract.getDeptId());
        if (Objects.nonNull(ownerDept)) {
            supplierContractRespVO.setDeptName(ownerDept.getName());
        }
        // 合同状态描述
        Map<String, String> contractStatusMap = Arrays.stream(ContractStatusEnum.values())
                .collect(Collectors.toMap(ContractStatusEnum::getStatus, ContractStatusEnum::getDesc));
        supplierContractRespVO.setContractStatusDesc(contractStatusMap.getOrDefault(supplierContract.getContractStatus(), "未知"));
        // 是否关闭
        supplierContractRespVO.setClosedDesc(generalStatusMap.getOrDefault(supplierContract.getClosed(), "未知"));
        // 是否终止
        supplierContractRespVO.setTerminateDesc(generalStatusMap.getOrDefault(supplierContract.getTerminate(), "未知"));

        // 附件
        List<FileDTO> fileDTOList = fileApi.getFileDTOListByBiz(supplierContract.getSupplierContractUuid());
        supplierContractRespVO.setFileList(fileDTOList);

        return success(supplierContractRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得采购合同信息分页")
    @ApiOperationSupport(order = 6)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:query')")
    public CommonResult<PageResult<SupplierContractRespVO>> getSupplierContractPage(@Valid @ParameterObject SupplierContractPageReqVO pageReqVO) {
        PageResult<SupplierContractRespVO> pageResult = supplierContractService.getSupplierContractPage(pageReqVO);

        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出采购合同信息 Excel")
    @ApiOperationSupport(order = 7)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSupplierContractExcel(@ParameterObject SupplierContractPageReqVO pageReqVO,
                                            HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<SupplierContractRespVO> list = supplierContractService.getSupplierContractPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "采购合同信息.xls", "数据", SupplierContractRespVO.class,
                list);
    }

    @PutMapping("/open")
    @Operation(summary = "开启采购合同")
    @ApiOperationSupport(order = 8)
    // @Parameter(name = "id", description = "主键id", required = true, example = "1")
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:update')")
    public CommonResult<Boolean> openSupplierContract(@RequestBody SupplierContractOpenReqVO openReqVO) {
        Long id = openReqVO.getId();
        supplierContractService.openSupplierContract(id);
        return success(true);
    }

    @PutMapping("/close")
    @Operation(summary = "关闭采购合同")
    @ApiOperationSupport(order = 9)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:update')")
    public CommonResult<Boolean> closeSupplierContract(@Valid @RequestBody SupplierContractCloseReqVO closeReqVO) {
        supplierContractService.closeSupplierContract(closeReqVO);
        return success(true);
    }

    @PutMapping("/terminate")
    @Operation(summary = "终止采购合同")
    @ApiOperationSupport(order = 10)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:update')")
    public CommonResult<Boolean> terminateSupplierContract(@Valid @RequestBody SupplierContractTerminatedReqVO terminatedReqVO) {
        supplierContractService.terminateSupplierContract(terminatedReqVO);
        return success(true);
    }

    @PutMapping("/editSupplierStatus")
    @Operation(summary = "修改采购合同状态")
    @ApiOperationSupport(order = 11)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:update')")
    public CommonResult<Boolean> editSupplierStatus(@Valid @RequestBody SupplierContractStatusReqVO statusReqVO) {
        supplierContractService.editSupplierStatus(statusReqVO);
        return success(true);
    }

    @PutMapping("/alter")
    @Operation(summary = "变更采购合同信息")
    @ApiOperationSupport(order = 12)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:update')")
    public CommonResult<Boolean> alterSupplierContract(@Valid @RequestBody SupplierContractSaveReqVO updateReqVO) {
        supplierContractService.alterSupplierContract(updateReqVO);
        return success(true);
    }


    // ==================== 子表（采购合同历史信息） ====================

    @GetMapping("/supplier-contract-history/page")
    @Operation(summary = "获得采购合同历史信息分页")
    @ApiOperationSupport(order = 13)
    @Parameter(name = "code", description = "合同编号，年月日+uuid")
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:query')")
    public CommonResult<PageResult<SupplierContractHistoryDO>> getSupplierContractHistoryPage(PageParam pageReqVO,
                                                                                              @RequestParam("code") String code) {
        return success(supplierContractService.getSupplierContractHistoryPage(pageReqVO, code));
    }

    // @PostMapping("/supplier-contract-history/create")
    // @Operation(summary = "创建采购合同历史信息")
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:create')")
    // public CommonResult<Long> createSupplierContractHistory(@Valid @RequestBody SupplierContractHistoryDO supplierContractHistory) {
    //     return success(supplierContractService.createSupplierContractHistory(supplierContractHistory));
    // }

    // @PutMapping("/supplier-contract-history/update")
    // @Operation(summary = "更新采购合同历史信息")
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:update')")
    // public CommonResult<Boolean> updateSupplierContractHistory(@Valid @RequestBody SupplierContractHistoryDO supplierContractHistory) {
    //     supplierContractService.updateSupplierContractHistory(supplierContractHistory);
    //     return success(true);
    // }

    // @DeleteMapping("/supplier-contract-history/delete")
    // @Parameter(name = "id", description = "编号", required = true)
    // @Operation(summary = "删除采购合同历史信息")
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:delete')")
    // public CommonResult<Boolean> deleteSupplierContractHistory(@RequestParam("id") Long id) {
    //     supplierContractService.deleteSupplierContractHistory(id);
    //     return success(true);
    // }

	@GetMapping("/supplier-contract-history/get")
	@Operation(summary = "获得采购合同历史信息")
    @ApiOperationSupport(order = 14)
	@Parameter(name = "id", description = "主键id", required = true)
    // @PreAuthorize("@ss.hasPermission('contract:supplier-contract:query')")
	public CommonResult<SupplierContractRespVO> getSupplierContractHistory(@RequestParam("id") Long id) {
        SupplierContractHistoryDO supplierContractHistory = supplierContractService.getSupplierContractHistory(id);
        if (Objects.isNull(supplierContractHistory)) {
            return CommonResult.success(null);
        }
        SupplierContractRespVO supplierContractRespVO = BeanUtils.toBean(supplierContractHistory, SupplierContractRespVO.class);

        // 是否描述集合
        Map<Integer, String> generalStatusMap = Arrays.stream(GeneralStatusEnum.values())
                .collect(Collectors.toMap(GeneralStatusEnum::getStatus, GeneralStatusEnum::getName));
        // 是否框架合同
        supplierContractRespVO.setIsFrameContractDesc(generalStatusMap.getOrDefault(supplierContractHistory.getIsFrameContract(), "未知"));
        // 负责人名称
        EmployeeRespDTO ownerEmployee = employeeApi.getEmployeeById(supplierContractHistory.getOwnerEmployeeId());
        if (Objects.nonNull(ownerEmployee)) {
            supplierContractRespVO.setOwnerEmployeeName(ownerEmployee.getName());
        }
        // 部门名称
        DeptRespDTO ownerDept = deptApi.getDept(supplierContractHistory.getDeptId());
        if (Objects.nonNull(ownerDept)) {
            supplierContractRespVO.setDeptName(ownerDept.getName());
        }
        // 合同状态描述
        Map<String, String> contractStatusMap = Arrays.stream(ContractStatusEnum.values())
                .collect(Collectors.toMap(ContractStatusEnum::getStatus, ContractStatusEnum::getDesc));
        supplierContractRespVO.setContractStatusDesc(contractStatusMap.getOrDefault(supplierContractHistory.getContractStatus(), "未知"));
        // 是否关闭
        supplierContractRespVO.setClosedDesc(generalStatusMap.getOrDefault(supplierContractHistory.getClosed(), "未知"));
        // 是否终止
        supplierContractRespVO.setTerminateDesc(generalStatusMap.getOrDefault(supplierContractHistory.getTerminate(), "未知"));

        // 附件
        List<FileDTO> fileDTOList = fileApi.getFileDTOListByBiz(supplierContractHistory.getSupplierContractUuid());
        supplierContractRespVO.setFileList(fileDTOList);

        return success(supplierContractRespVO);
	}

}