package com.yd.csf.api.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.base.feign.client.relobjectcertificate.ApiRelObjectCertificateFeignClient;
import com.yd.base.feign.request.relobjectcertificate.ApiRelObjectCertificateListAddRequest;
import com.yd.common.enums.CommonEnum;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.csf.api.service.ApiTaxationService;
import com.yd.csf.feign.dto.taxation.ApiObjectTaxationDto;
import com.yd.csf.feign.dto.taxation.ApiTaxationDto;
import com.yd.csf.service.common.ErrorCode;
import com.yd.csf.service.dto.CustomerAddRequest;
import com.yd.csf.service.dto.CustomerQueryRequest;
import com.yd.csf.service.dto.CustomerUpdateRequest;
import com.yd.csf.service.model.Customer;
import com.yd.csf.service.service.CustomerService;
import com.yd.csf.service.vo.CustomerVO;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * customer接口
 *
 * @author jianan
 * @since 2025-07-31
 */
@RestController
@RequestMapping("/Customer")
@Tag(name = "客户接口")
public class ApiCustomerController {

    @Resource
    private CustomerService customerService;
    @Resource
    private ApiTaxationService apiTaxationService;
    @Resource
    private ApiRelObjectCertificateFeignClient apiRelObjectCertificateFeignClient;

    /**
     * 创建客户
     *
     * @param customerAddRequest
     * @param request
     * @return
     */
    @Operation(summary = "创建客户")
    @PostMapping("/add")
    public Result<Map<String, Object>> addCustomer(@RequestBody CustomerAddRequest customerAddRequest, HttpServletRequest request) {
        if (customerAddRequest == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), ResultCode.PARAMS_ERROR.getMessage());
        }
        if (ObjectUtils.isEmpty(customerAddRequest.getFnaBizId())) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), "fnaBizId不能为空");
        }

        Map<String, Object> resultMap = customerService.addCustomer(customerAddRequest);
        String customerBizId = (String) resultMap.get("customerBizId");

        // 添加客户税务列表信息
        if (CollUtil.isNotEmpty(customerAddRequest.getApiTaxationDtoList())) {
            List<ApiTaxationDto> apiTaxationDtoList = customerAddRequest.getApiTaxationDtoList().stream().map(d -> {
                ApiTaxationDto apiTaxationDto = new ApiTaxationDto();
                apiTaxationDto.setTaxCountry(d.getTaxCountry());
                apiTaxationDto.setTaxId(d.getTaxId());
                return apiTaxationDto;
            }).collect(Collectors.toList());
            apiTaxationService.saveTaxationList(ApiObjectTaxationDto.builder()
                    .objectBizId(customerBizId)
                    .objectName(CommonEnum.UID_TYPE_CUSTOMER.getName())
                    .objectTableName(CommonEnum.UID_TYPE_CUSTOMER.getCode())
                    .objectType(CommonEnum.UID_TYPE_CUSTOMER.getCode())
                    .apiTaxationDtoList(apiTaxationDtoList)
                    .build());
        }

        // 添加客户证件列表信息
        if (CollUtil.isNotEmpty(customerAddRequest.getApiCertificateDtoList())) {
            apiRelObjectCertificateFeignClient.addRelObjectCertificateList(ApiRelObjectCertificateListAddRequest.builder()
                    .objectBizId(customerBizId)
                    .objectName(CommonEnum.UID_TYPE_CUSTOMER.getName())
                    .objectTableName(CommonEnum.UID_TYPE_CUSTOMER.getCode())
                    .objectType(CommonEnum.UID_TYPE_CUSTOMER.getCode())
                    .apiCertificateDtoList(customerAddRequest.getApiCertificateDtoList())
                    .build());
        }
        return Result.success(resultMap);
    }

    /**
     * 删除fna
     *
     * @param deleteRequest
     * @param request
     * @return
     */
//    @PostMapping("/delete")
//    public Result<Boolean> deleteFna(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
//        if (deleteRequest == null || deleteRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User user = userService.getLoginUser(request);
//        long id = deleteRequest.getId();
//        // 判断是否存在
//        Customer oldFna = customerService.getById(id);
//        ThrowUtils.throwIf(oldFna == null, ErrorCode.NOT_FOUND_ERROR);
//        // 仅本人或管理员可删除
//        if (!oldFna.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        }
//        // 操作数据库
//        boolean result = customerService.removeById(id);
//        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
//        return Result.success(true);
//    }

    /**
     * 更新客户
     *
     * @param customerUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "更新客户信息")
    public Result<Boolean> updateCustomer(@RequestBody CustomerUpdateRequest customerUpdateRequest) {
        String customerBizId = customerUpdateRequest.getCustomerBizId();
        if (ObjectUtils.isEmpty(customerBizId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR.getCode(), "customerBizId不能为空");
        }
        if (ObjectUtils.isEmpty(customerUpdateRequest.getFnaBizId())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR.getCode(), "fnaBizId不能为空");
        }

        boolean result = customerService.updateCustomer(customerUpdateRequest);

        // 添加客户税务列表信息
        if (CollUtil.isNotEmpty(customerUpdateRequest.getApiTaxationDtoList())) {
            List<ApiTaxationDto> apiTaxationDtoList = customerUpdateRequest.getApiTaxationDtoList().stream().map(d -> {
                ApiTaxationDto apiTaxationDto = new ApiTaxationDto();
                apiTaxationDto.setTaxCountry(d.getTaxCountry());
                apiTaxationDto.setTaxId(d.getTaxId());
                return apiTaxationDto;
            }).collect(Collectors.toList());
            apiTaxationService.saveTaxationList(ApiObjectTaxationDto.builder()
                    .objectBizId(customerBizId)
                    .objectName(CommonEnum.UID_TYPE_CUSTOMER.getName())
                    .objectTableName(CommonEnum.UID_TYPE_CUSTOMER.getCode())
                    .objectType(CommonEnum.UID_TYPE_CUSTOMER.getCode())
                    .apiTaxationDtoList(apiTaxationDtoList)
                    .build());
        }

        // 添加客户证件列表信息
        if (CollUtil.isNotEmpty(customerUpdateRequest.getApiCertificateDtoList())) {
            apiRelObjectCertificateFeignClient.addRelObjectCertificateList(ApiRelObjectCertificateListAddRequest.builder()
                    .objectBizId(customerBizId)
                    .objectName(CommonEnum.UID_TYPE_CUSTOMER.getName())
                    .objectTableName(CommonEnum.UID_TYPE_CUSTOMER.getCode())
                    .objectType(CommonEnum.UID_TYPE_CUSTOMER.getCode())
                    .apiCertificateDtoList(customerUpdateRequest.getApiCertificateDtoList())
                    .build());
        }

        return Result.success(result);
    }

    /**
     * 根据 customerBizId 获取客户（封装类）
     *
     * @param customerBizId
     * @return
     */
    @GetMapping("/get/vo")
    @Operation(summary = "根据 customerBizId 获取客户详情")
    public Result<CustomerVO> getCustomerVOByCustomerBizId(@RequestParam("customerBizId") String customerBizId, HttpServletRequest request) {
        if (customerBizId == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), "customerBizId 不能为空");
        }
        // 查询数据库
        Customer customer = customerService.getByCustomerBizId(customerBizId);
        if (customer == null) {
            return Result.fail(ResultCode.NULL_ERROR.getCode(), ResultCode.NULL_ERROR.getMessage());
        }
        // 查询受供养人数量
        customerService.queryDependentsNum(customer);

        // 获取封装类
        return Result.success(customerService.getCustomerVO(customer));
    }

    /**
     * 分页获取客户列表（仅管理员可用）
     *
     * @param fnaQueryRequest
     * @return
     */
//    @PostMapping("/list/page")
//    public Result<Page<Customer>> listFnaByPage(@RequestBody FnaQueryRequest fnaQueryRequest) {
//        long current = fnaQueryRequest.getPageNo();
//        long size = fnaQueryRequest.getPageSize();
//        // 查询数据库
//        Page<Customer> fnaPage = customerService.page(new Page<>(current, size),
//                customerService.getQueryWrapper(fnaQueryRequest));
//        return Result.success(fnaPage);
//    }

    /**
     * 分页获取客户列表（VO）
     *
     * @param customerQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @Operation(summary = "分页获取客户列表")
    public Result<Page<CustomerVO>> listCustomerVOByPage(@RequestBody CustomerQueryRequest customerQueryRequest,
                                                         HttpServletRequest request) {
        long current = customerQueryRequest.getPageNo();
        long size = customerQueryRequest.getPageSize();

        // 查询数据库
        Page<Customer> customerPage = customerService.page(new Page<>(current, size),
                customerService.getQueryWrapper(customerQueryRequest));
        // 获取封装类
        return Result.success(customerService.getCustomerVOPage(customerPage));
    }

}
