package com.nbport.zgwl.partner.controller;

import com.nbport.zgwl.common.PageResult;
import com.nbport.zgwl.common.R;
import com.nbport.zgwl.partner.dto.PartnerManageDto;
import com.nbport.zgwl.partner.dto.PartnerQueryDto;
import com.nbport.zgwl.partner.service.PartnerManageService;
import com.nbport.zgwl.partner.utils.PartnerManageConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 相对方管理 Controller
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(PartnerManageConstants.REQUEST_PREFIX)
public class PartnerManageController {

    private final PartnerManageService partnerManageService;

    /** 分页查询相对方列表 */
    @PostMapping("/list")
    public R<PageResult<PartnerManageDto>> queryList(@RequestBody PartnerQueryDto queryDto) {
        return R.success(partnerManageService.queryPartnerList(queryDto));
    }

    /** 查询单个相对方详情 */
    @GetMapping("/{customerSysid}")
    public R<PartnerManageDto> getInfo(@PathVariable("customerSysid") Long customerSysid) {
        return R.success(partnerManageService.selectPartnerById(customerSysid));
    }

    /** 新增相对方 */
    @PostMapping
    public R<Long> add(@RequestBody PartnerManageDto partner) {
        return R.success(partnerManageService.insertPartner(partner));
    }

    /** 修改相对方 */
    @PutMapping
    public R<String> edit(@RequestBody PartnerManageDto partner) {
        partnerManageService.updatePartner(partner);
        return R.success("保存成功");
    }

    /** 批量删除相对方（逗号分隔多个 ID） */
    @DeleteMapping("/{customerSysids}")
    public R<String> remove(@PathVariable("customerSysids") String customerSysids) {
        List<Long> idList = Arrays.stream(customerSysids.split(","))
                .filter(item -> item != null && !item.isBlank())
                .map(Long::valueOf)
                .collect(Collectors.toList());
        partnerManageService.deletePartnerByIds(idList);
        return R.success("删除成功");
    }

    /** 模拟同步到法务系统 */
    @PostMapping("/{customerSysid}/sync")
    public R<PartnerManageDto> mockSync(@PathVariable("customerSysid") Long customerSysid) {
        return R.success(partnerManageService.mockSyncPartner(customerSysid));
    }
}
