package cn.iocoder.yudao.module.system.controller.admin.rental;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.smartfactory.api.factoryInfo.FactoryInfoApi;
import cn.iocoder.yudao.module.smartfactory.api.factoryInfo.dto.FactoryInfoDTO;
import cn.iocoder.yudao.module.system.controller.admin.rental.vo.customer.RentalCustomerPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.rental.vo.customer.RentalCustomerRespVO;
import cn.iocoder.yudao.module.system.controller.admin.rental.vo.customer.RentalCustomerSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.rental.vo.customer.RentalCustomerStatusReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.rental.RentalCustomerDO;
import cn.iocoder.yudao.module.system.service.rental.RentalCustomerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 租赁客户")
@RestController
@RequestMapping("/system/rental-customer")
@Validated
public class RentalCustomerController {

    @Resource
    private RentalCustomerService rentalCustomerService;

    @Resource
    private FactoryInfoApi factoryInfoApi;

    @PostMapping("/create")
    @Operation(summary = "创建租赁客户")
    @PreAuthorize("@ss.hasPermission('system:rental-customer:create')")
    public CommonResult<Long> createRentalCustomer(@Valid @RequestBody RentalCustomerSaveReqVO createReqVO) {
        return success(rentalCustomerService.createRentalCustomer(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新租赁客户")
    @PreAuthorize("@ss.hasPermission('system:rental-customer:update')")
    public CommonResult<Boolean> updateRentalCustomer(@Valid @RequestBody RentalCustomerSaveReqVO updateReqVO) {
        rentalCustomerService.updateRentalCustomer(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新租赁客户状态")
    @PreAuthorize("@ss.hasPermission('system:rental-customer:update')")
    public CommonResult<Boolean> updateRentalCustomer(@RequestBody RentalCustomerStatusReqVO updateReqVO) {
        rentalCustomerService.updateRentalCustomerStatus(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除租赁客户")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:rental-customer:delete')")
    public CommonResult<Boolean> deleteRentalCustomer(@RequestParam("id") Long id) {
        rentalCustomerService.deleteRentalCustomer(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得租赁客户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:rental-customer:query')")
    public CommonResult<RentalCustomerRespVO> getRentalCustomer(@RequestParam("id") Long id) {
        RentalCustomerDO rentalCustomer = rentalCustomerService.getRentalCustomer(id);
        return success(BeanUtils.toBean(rentalCustomer, RentalCustomerRespVO.class));
    }

    @GetMapping("/get-list")
    @Operation(summary = "获得开启状态的租赁客户列表")
    @PreAuthorize("@ss.hasPermission('system:rental-customer:query')")
    public CommonResult<List<RentalCustomerRespVO>> getRentalCustomerList() {
        List<RentalCustomerDO> rentalCustomer = rentalCustomerService.getRentalCustomerList();
        return success(BeanUtils.toBean(rentalCustomer, RentalCustomerRespVO.class));
    }

    @GetMapping("/get-list-by-factory")
    @Operation(summary = "获得对应工厂的客户列表")
    @Parameter(name = "userId", description = "用户id", required = true)
    @PreAuthorize("@ss.hasPermission('system:rental-customer:query')")
    public CommonResult<List<RentalCustomerRespVO>> getListByFactory(@RequestParam("userId") Long userId) {
        List<RentalCustomerDO> rentalCustomer = rentalCustomerService.getListByFactory(userId);
        return success(BeanUtils.toBean(rentalCustomer, RentalCustomerRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得租赁客户分页")
    @PreAuthorize("@ss.hasPermission('system:rental-customer:query')")
    public CommonResult<PageResult<RentalCustomerRespVO>> getRentalCustomerPage(@Valid RentalCustomerPageReqVO pageReqVO) {
        PageResult<RentalCustomerDO> pageResult = rentalCustomerService.getRentalCustomerPage(pageReqVO);
        PageResult<RentalCustomerRespVO> respVO = BeanUtils.toBean(pageResult, RentalCustomerRespVO.class);
        if (CollUtil.isNotEmpty(respVO.getList())) {
            // 获取工厂编号
            Set<Long> factoryIds = pageResult.getList().stream()
                    .map(RentalCustomerDO::getFactoryIds)
                    .filter(Objects::nonNull)
                    .flatMap(Set::stream)
                    .collect(Collectors.toSet());
            // 获取工厂信息
            List<FactoryInfoDTO> factoryInfoDTOS = factoryInfoApi.getFactoryInfoList(factoryIds).getCheckedData();
            // 映射工厂名称
            Map<Long, String> factoryMap = factoryInfoDTOS.stream()
                    .collect(Collectors.toMap(FactoryInfoDTO::getId, FactoryInfoDTO::getShortName));

            respVO.getList().forEach(item -> {
                // 设置工厂名称
                Set<Long> itemFactoryIds = item.getFactoryIds();
                if (itemFactoryIds != null) {
                    List<String> factoryNames = itemFactoryIds.stream()
                            .map(factoryMap::get)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    item.setFactoryNames(factoryNames);
                }
            });
        }

        return success(respVO);
    }
}