package cn.iocoder.yudao.module.cash.controller.admin.refundinfo;

import cn.hutool.core.util.StrUtil;
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.cash.controller.admin.refundinfo.vo.RefundInfoPageReqVO;
import cn.iocoder.yudao.module.cash.controller.admin.refundinfo.vo.RefundInfoRespVO;
import cn.iocoder.yudao.module.cash.controller.admin.refundinfo.vo.RefundInfoSaveReqVO;
import cn.iocoder.yudao.module.cash.dal.dataobject.refundinfo.RefundInfoDO;
import cn.iocoder.yudao.module.cash.service.refundinfo.RefundInfoService;
import cn.iocoder.yudao.module.contract.api.customercontract.CustomerContractApi;
import cn.iocoder.yudao.module.contract.api.customercontract.dto.CustomerContractDTO;
import cn.iocoder.yudao.module.customer.api.info.CustomerInfoApi;
import cn.iocoder.yudao.module.customer.api.info.dto.CustomerInfoDTO;
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 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.List;
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/cash/refund-info")
@Validated
public class RefundInfoController {

    @Resource
    private RefundInfoService refundInfoService;

    @Resource
    private FileApi fileApi;

    @Resource
    private EmployeeApi employeeApi;

    @Resource
    private CustomerInfoApi customerInfoApi;

    @Resource
    private CustomerContractApi customerContractApi;

    @PostMapping("/create")
    @Operation(summary = "创建回款信息")
    @ApiOperationSupport(order = 1)
    // @PreAuthorize("@ss.hasPermission('cash:refund-info:create')")
    public CommonResult<Long> createRefundInfo(@Valid @RequestBody RefundInfoSaveReqVO createReqVO) {
        return success(refundInfoService.createRefundInfo(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新回款信息")
    @ApiOperationSupport(order = 2)
    // @PreAuthorize("@ss.hasPermission('cash:refund-info:update')")
    public CommonResult<Boolean> updateRefundInfo(@Valid @RequestBody RefundInfoSaveReqVO updateReqVO) {
        refundInfoService.updateRefundInfo(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除回款信息")
    @ApiOperationSupport(order = 3)
    @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('cash:refund-info:delete')")
    public CommonResult<Boolean> deleteRefundInfo(@RequestParam("id") Long id) {
        refundInfoService.deleteRefundInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得回款信息")
    @ApiOperationSupport(order = 4)
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    // @PreAuthorize("@ss.hasPermission('cash:refund-info:query')")
    public CommonResult<RefundInfoRespVO> getRefundInfo(@RequestParam("id") Long id) {
        RefundInfoDO refundInfo = refundInfoService.getRefundInfo(id);
        RefundInfoRespVO refundInfoRespVO = BeanUtils.toBean(refundInfo, RefundInfoRespVO.class);

        // 客户名称
        Long customerId = refundInfo.getCustomerId();
        if (customerId != null) {
            CustomerInfoDTO customerInfo = customerInfoApi.getCustomerInfo(customerId);
            if (customerInfo != null) {
                refundInfoRespVO.setCustomerName(customerInfo.getCustomerName());
                refundInfoRespVO.setCustomerCode(customerInfo.getCustomerCode());
            }
        }

        // 合同名称
        Long contractId = refundInfo.getContractId();
        if (contractId != null) {
            CustomerContractDTO customerContract = customerContractApi.getCustomerContract(contractId);
            if (customerContract != null) {
                refundInfoRespVO.setContractName(customerContract.getCustomerContractName());
                refundInfoRespVO.setContractCode(customerContract.getCustomerContractCode());
            }
        }

        // 创建人姓名
        String creator = refundInfo.getCreator();
        if (StrUtil.isNotBlank(creator)) {
            EmployeeRespDTO creatorName = employeeApi.getEmployeeById(Long.valueOf(creator));
            refundInfoRespVO.setCreatorName(creatorName.getName());
        }

        // 附件列表
        List<FileDTO> fileList = fileApi.getFileDTOListByBiz(refundInfoRespVO.getRefundInfoUuid());
        refundInfoRespVO.setFileList(fileList);
        List<Long> fileIdList = fileList.stream().map(FileDTO::getId).collect(Collectors.toList());
        refundInfoRespVO.setFileIdList(fileIdList);

        return success(refundInfoRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得回款信息分页")
    @ApiOperationSupport(order = 5)
    // @PreAuthorize("@ss.hasPermission('cash:refund-info:query')")
    public CommonResult<PageResult<RefundInfoRespVO>> getRefundInfoPage(@Valid @ParameterObject RefundInfoPageReqVO pageReqVO) {
        PageResult<RefundInfoRespVO> pageResult = refundInfoService.getRefundInfoPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出回款信息 Excel")
    @ApiOperationSupport(order = 6)
    // @PreAuthorize("@ss.hasPermission('cash:refund-info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportRefundInfoExcel(@Valid @ParameterObject RefundInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<RefundInfoRespVO> list = refundInfoService.getRefundInfoPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "回款信息.xls", "数据", RefundInfoRespVO.class,
                        list);
    }

}