package com.usky.vpp.controller.web;

import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.vpp.domain.VppCustomerContact;
import com.usky.vpp.service.VppCustomerService;
import com.usky.vpp.service.vo.CustomerAccessAuditRequest;
import com.usky.vpp.service.vo.CustomerAccessRequestVO;
import com.usky.vpp.service.vo.CustomerAccessResponseVO;
import com.usky.vpp.service.vo.CustomerContactRequest;
import com.usky.vpp.service.vo.CustomerRequestVO;
import com.usky.vpp.service.vo.CustomerResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 客户管理接口
 * <p>分为两大类：准入管理 和 客户管理</p>
 * 网关前缀: /prod-api/service-vpp/customer
 *
 * @author fyc
 * @email yuchuan.fu@chinausky.com
 * @date 2026/7/6
 */
@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private VppCustomerService vppCustomerService;

    // ==================== 准入管理 ====================

    /**
     * 提交准入申请
     */
    @PostMapping("/access")
    public ApiResult<Boolean> submitAccess(@RequestBody CustomerAccessRequestVO vo) {
        return vppCustomerService.submitAccess(vo)
                ? ApiResult.success(true)
                : ApiResult.error("提交准入申请失败，请重试！");
    }

    /**
     * 分页查询准入申请
     * <ul>
     *   <li>id           主键ID 精确匹配</li>
     *   <li>accessStatus 准入状态 0待审核 1通过 2拒绝</li>
     *   <li>customerName 客户名称 模糊匹配</li>
     *   <li>current      页码</li>
     *   <li>size         页大小</li>
     * </ul>
     */
    @GetMapping("/access")
    public ApiResult<CommonPage<CustomerAccessResponseVO>> pageAccess(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "accessStatus", required = false) Integer accessStatus,
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start = startTime != null && !startTime.isEmpty()
                ? LocalDateTime.parse(startTime, formatter) : null;
        LocalDateTime end = endTime != null && !endTime.isEmpty()
                ? LocalDateTime.parse(endTime, formatter) : null;
        return ApiResult.success(vppCustomerService.pageAccess(id, accessStatus, customerName, start, end, current, size));
    }

    /**
     * 审核准入申请（通过/拒绝）
     */
    @PutMapping("/access/audit")
    public ApiResult<Void> auditAccess(@RequestBody CustomerAccessAuditRequest body) {
        vppCustomerService.auditAccess(body);
        return ApiResult.success();
    }

    /**
     * 修改准入申请（仅已驳回状态可修改，修改后重新进入待审核）
     */
    @PutMapping("/access")
    public ApiResult<Boolean> updateAccess(@RequestBody CustomerAccessRequestVO vo) {
        return vppCustomerService.updateAccess(vo)
                ? ApiResult.success(true)
                : ApiResult.error("修改准入申请失败，请重试！");
    }

    /**
     * 删除准入申请（软删除）
     */
    @DeleteMapping("/access/{id}")
    public ApiResult<Boolean> deleteAccess(@PathVariable("id") Long id) {
        return vppCustomerService.deleteAccess(id)
                ? ApiResult.success(true)
                : ApiResult.error("删除准入申请失败，请重试！");
    }

    /**
     * 导出准入申请数据（Excel）
     * <ul>
     *   <li>scope = "current"：导出当前页，需传 current + size</li>
     *   <li>scope = "all"：导出当前租户全部未删除准入申请</li>
     *   <li>scope = "filtered"：导出筛选结果，需至少传一个筛选条件</li>
     * </ul>
     */
    @GetMapping("/access/export")
    public void exportAccess(
            @RequestParam("scope") String scope,
            @RequestParam("fileName") String fileName,
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "accessStatus", required = false) Integer accessStatus,
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "current", required = false) Integer current,
            @RequestParam(value = "size", required = false) Integer size,
            HttpServletResponse response) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start = startTime != null && !startTime.isEmpty()
                ? LocalDateTime.parse(startTime, formatter) : null;
        LocalDateTime end = endTime != null && !endTime.isEmpty()
                ? LocalDateTime.parse(endTime, formatter) : null;
        vppCustomerService.exportAccess(scope, fileName, id, accessStatus, customerName,
                start, end, current, size, response);
    }

    // ==================== 客户管理 ====================

    /**
     * 直接新增客户（跳过准入流程）
     */
    @PostMapping
    public ApiResult<Boolean> createCustomer(@RequestBody CustomerRequestVO vo) {
        return vppCustomerService.createCustomer(vo)
                ? ApiResult.success(true)
                : ApiResult.error("新增客户失败，请重试！");
    }

    /**
     * 分页查询客户（含关联合同）
     * <ul>
     *   <li>id               主键ID 精确匹配</li>
     *   <li>customerName     客户名称 模糊匹配</li>
     *   <li>accountNo        电力户号 精确匹配</li>
     *   <li>lifecycleStatus  签约状态</li>
     *   <li>customerType     客户类型</li>
     *   <li>current          页码</li>
     *   <li>size             页大小</li>
     * </ul>
     */
    @GetMapping
    public ApiResult<CommonPage<CustomerResponseVO>> pageCustomer(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "accountNo", required = false) String accountNo,
            @RequestParam(value = "lifecycleStatus", required = false) Integer lifecycleStatus,
            @RequestParam(value = "customerType", required = false) Integer customerType,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        return ApiResult.success(vppCustomerService.pageCustomer(
                id, customerName, accountNo, lifecycleStatus, customerType, current, size));
    }

    /**
     * 查询客户详情（含关联合同）
     */
    @GetMapping("/{id}")
    public ApiResult<CustomerResponseVO> getCustomer(@PathVariable("id") Long id) {
        return ApiResult.success(vppCustomerService.getCustomer(id));
    }

    /**
     * 更新客户信息
     */
    @PutMapping()
    public ApiResult<Boolean> updateCustomer(@RequestBody CustomerRequestVO vo) {
        return vppCustomerService.updateCustomer(vo)
                ? ApiResult.success(true)
                : ApiResult.error("更新客户信息失败，请重试！");
    }

    /**
     * 删除客户（软删除）
     */
    @DeleteMapping("/{id}")
    public ApiResult<Boolean> deleteCustomer(@PathVariable("id") Long id) {
        return vppCustomerService.deleteCustomer(id)
                ? ApiResult.success(true)
                : ApiResult.error("删除客户失败，请重试！");
    }

    /**
     * 导出客户数据（Excel）
     * <ul>
     *   <li>scope = "current"：导出当前页，需传 current + size</li>
     *   <li>scope = "all"：导出当前租户全部未删除客户</li>
     *   <li>scope = "filtered"：导出筛选结果，需至少传一个筛选条件</li>
     * </ul>
     */
    @GetMapping("/export")
    public void exportCustomers(
            @RequestParam("scope") String scope,
            @RequestParam("fileName") String fileName,
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "lifecycleStatus", required = false) Integer lifecycleStatus,
            @RequestParam(value = "current", required = false) Integer current,
            @RequestParam(value = "size", required = false) Integer size,
            HttpServletResponse response) {
        vppCustomerService.exportCustomers(scope, fileName, customerName, lifecycleStatus, current, size, response);
    }

    // ==================== 联系人管理 ====================

    /**
     * 分页查询联系人
     */
    @GetMapping("/{id}/contact")
    public ApiResult<CommonPage<VppCustomerContact>> listContact(
            @PathVariable("id") Long id,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        return ApiResult.success(vppCustomerService.listContact(id, current, size));
    }

    /**
     * 新增联系人
     */
    @PostMapping("/{id}/contact")
    public ApiResult<VppCustomerContact> addContact(@PathVariable("id") Long id,
                                                    @RequestBody CustomerContactRequest body) {
        return ApiResult.success(vppCustomerService.addContact(id, body));
    }

    /**
     * 更新联系人
     */
    @PutMapping("/{id}/contact/{contactId}")
    public ApiResult<Void> updateContact(@PathVariable("id") Long id,
                                         @PathVariable("contactId") Long contactId,
                                         @RequestBody CustomerContactRequest body) {
        vppCustomerService.updateContact(id, contactId, body);
        return ApiResult.success();
    }

    /**
     * 删除联系人
     */
    @DeleteMapping("/{id}/contact/{contactId}")
    public ApiResult<Void> deleteContact(@PathVariable("id") Long id,
                                         @PathVariable("contactId") Long contactId) {
        vppCustomerService.deleteContact(id, contactId);
        return ApiResult.success();
    }
}
