package shop.alien.lawyer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawFirm;
import shop.alien.entity.store.vo.LawFirmPaymentVO;
import shop.alien.lawyer.service.LawFirmService;
import shop.alien.util.myBaticsPlus.QueryBuilder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 律所表 前端控制器
 * qxy
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"律师平台-律所管理"})
@ApiSort(20)
@CrossOrigin
@RestController
@RequestMapping("/lawyer/firm")
@RequiredArgsConstructor
public class LawFirmController {

    private final LawFirmService lawFirmService;

    @ApiOperation(value = "新增律所", notes = "新增律所信息，支持同时添加收款账号列表。如果统一社会信用代码（creditCode）已存在，将自动执行更新操作。收款账号（payment_account）必须唯一，不能重复添加。")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawFirm", value = "律所信息对象，包含paymentList（收款账号列表）。如果creditCode已存在，将更新现有记录", dataType = "LawFirm", paramType = "body", required = true)
    })
    @PostMapping("/addLawFirm")
    public R<LawFirm> addLawFirm(@RequestBody LawFirm lawFirm) {
        log.info("LawFirmController.addLawFirm?lawFirm={}", lawFirm);
        return lawFirmService.addLawFirm(lawFirm);
    }

    @ApiOperation(value = "编辑律所", notes = "编辑律所信息，支持同时新增、修改、删除收款账号。收款账号（payment_account）必须唯一，不能重复添加。")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawFirm", value = "律所信息对象，必须包含id。paymentList中：有id的为更新，无id的为新增，不在列表中的将被删除", dataType = "LawFirm", paramType = "body", required = true)
    })
    @PostMapping("/editLawFirm")
    public R<LawFirm> editLawFirm(@RequestBody LawFirm lawFirm) {
        log.info("LawFirmController.editLawFirm?lawFirm={}", lawFirm);
        return lawFirmService.editLawFirm(lawFirm);
    }

    @ApiOperation(value = "删除律所", notes = "根据律所子表id删除收款账号。删除后如果该律所没有其他收款账号，将自动删除律所主表")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "律所子表ID（收款账号ID）", dataType = "Integer", paramType = "query", required = true)
    })
    @DeleteMapping("/deleteLawFirm")
    public R<Boolean> deleteLawFirm(@RequestParam(value = "id") Integer id) {
        log.info("LawFirmController.deleteLawFirm?paymentId={}", id);
        return lawFirmService.deleteLawFirm(id);
    }

//    @ApiOperation(value = "保存或更新律所", notes = "根据是否有id判断新增或更新。注意：此接口不支持收款账号的关联操作，建议使用addLawFirm或editLawFirm接口")
//    @ApiOperationSupport(order = 4)
//    @PostMapping("/saveOrUpdate")
//    public R<LawFirm> saveOrUpdate(@RequestBody LawFirm lawFirm) {
//        log.info("LawFirmController.saveOrUpdate?lawFirm={}", lawFirm);
//        boolean result = lawFirmService.saveOrUpdate(lawFirm);
//        if (result) {
//            return R.data(lawFirm);
//        }
//        return R.fail("操作失败");
//    }

    @ApiOperation(value = "通用列表查询", notes = "查询律所列表，包含收款账号列表（paymentList）")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "firmName", value = "律所名称（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "creditCode", value = "统一社会信用代码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "律所状态, 0:禁用, 1:启用", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "certificationStatus", value = "认证状态, 0:未认证, 1:认证中, 2:已认证, 3:认证失败", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "province", value = "所属省份", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "city", value = "所属城市", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_Start", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_End", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getList")
    public R<List<LawFirm>> getList(@ModelAttribute LawFirm lawFirm) {
        log.info("LawFirmController.getList?lawFirm={}", lawFirm);
        List<LawFirm> list = QueryBuilder.of(lawFirm)
                .likeFields("firmName", "creditCode")  // 律所名称和统一社会信用代码支持模糊查询
                .build()
                .list(lawFirmService);
        // 批量填充收款账号列表
        lawFirmService.fillPaymentList(list);
        return R.data(list);
    }

    @ApiOperation(value = "通用分页查询", notes = "分页查询律所列表，包含收款账号列表（paymentList）")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "firmName", value = "律所名称（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "creditCode", value = "统一社会信用代码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "律所状态, 0:禁用, 1:启用", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_Start", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_End", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getPage")
    public R<IPage<LawFirm>> getPage(@ModelAttribute LawFirm lawFirm,
                                     @RequestParam(defaultValue = "1") int page,
                                     @RequestParam(defaultValue = "10") int size) {
        log.info("LawFirmController.getPage?lawFirm={},page={},size={}", lawFirm, page, size);
        int pageNum = page > 0 ? page : 1;
        int pageSize = size > 0 ? size : 10;
        IPage<LawFirm> pageResult = QueryBuilder.of(lawFirm)
                .likeFields("firmName", "creditCode")  // 律所名称和统一社会信用代码支持模糊查询
                .page(pageNum, pageSize)
                .build()
                .page(lawFirmService);
        // 批量填充收款账号列表
        if (pageResult != null && pageResult.getRecords() != null && !pageResult.getRecords().isEmpty()) {
            lawFirmService.fillPaymentList(pageResult.getRecords());
        }
        return R.data(pageResult);
    }

    @ApiOperation(value = "获取律所详情", notes = "获取律所详细信息，包含收款账号列表（paymentList）")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "律所ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getDetail")
    public R<LawFirm> getLawFirmDetail(@RequestParam(value = "id") Integer id) {
        log.info("LawFirmController.getLawFirmDetail?id={}", id);
        return lawFirmService.getLawFirmDetail(id);
    }

    @ApiOperation(value = "导出律所数据到Excel", notes = "导出律所数据到Excel文件，包含收款账号信息。支持按律所ID过滤和分页导出")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "firmId", value = "律所ID（可选，用于过滤特定律所）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页数（可选，默认1，如果pageSize为空则导出全部）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（可选，默认10，如果为空则导出全部数据）", dataType = "int", paramType = "query")
    })
    @GetMapping("/export")
    public void exportLawFirm(HttpServletResponse response,
                              @RequestParam(required = false) Integer firmId,
                              @RequestParam(required = false) Integer page,
                              @RequestParam(required = false) Integer size) throws IOException {
        log.info("LawFirmController.exportLawFirm?firmId={},page={},size={}", firmId, page, size);
        lawFirmService.exportLawFirm(response, firmId, page, size);
    }

    @ApiOperation(value = "从Excel导入律所数据", notes = "从Excel文件导入律所数据，支持批量导入。导入规则：1. 按统一社会信用代码（creditCode）分组，相同信用代码的数据会自动合并；2. 相同信用代码的多行数据会合并收款账号；3. 如果统一社会信用代码已存在，将更新现有记录并合并收款账号；4. 收款账号必须全局唯一，已存在的收款账号将跳过添加")
    @ApiOperationSupport(order = 9)
    @PostMapping("/import")
    public R<String> importLawFirm(MultipartFile file) {
        log.info("LawFirmController.importLawFirm fileName={}", file != null ? file.getOriginalFilename() : "null");
        return lawFirmService.importLawFirm(file);
    }

    @ApiOperation(value = "下载律所Excel导入模板", notes = "下载律所数据导入的Excel模板文件")
    @ApiOperationSupport(order = 10)
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        log.info("LawFirmController.downloadTemplate");
        lawFirmService.downloadTemplate(response);
    }

    @ApiOperation(value = "分页查询律所子表关联律所表", notes = "以律所子表（law_firm_payment）为主表，关联律所表（law_firm）进行分页查询")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "paymentAccount", value = "收款账号（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "firmName", value = "律所名称（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "creditCode", value = "统一社会信用代码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "律所状态, 0:禁用, 1:启用", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "certificationStatus", value = "认证状态, 0:未认证, 1:认证中, 2:已认证, 3:认证失败", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "directorName", value = "负责人姓名（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTimeStart", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTimeEnd", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getPaymentPageWithFirm")
    public R<IPage<LawFirmPaymentVO>> getPaymentPageWithFirm(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer firmId,
            @RequestParam(required = false) String paymentAccount,
            @RequestParam(required = false) String firmName,
            @RequestParam(required = false) String creditCode,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer certificationStatus,
            @RequestParam(required = false) String directorName,
            @RequestParam(required = false) String createdTimeStart,
            @RequestParam(required = false) String createdTimeEnd) {
        log.info("LawFirmController.getPaymentPageWithFirm?page={},size={},firmId={},paymentAccount={},firmName={},creditCode={},status={},certificationStatus={},directorName={},createdTimeStart={},createdTimeEnd={}",
                page, size, firmId, paymentAccount, firmName, creditCode, status, certificationStatus, directorName, createdTimeStart, createdTimeEnd);
        int pageNum = page > 0 ? page : 1;
        int pageSize = size > 0 ? size : 10;
        return lawFirmService.getPaymentPageWithFirm(pageNum, pageSize, firmId, paymentAccount, firmName, creditCode, status, certificationStatus, directorName, createdTimeStart, createdTimeEnd);
    }
}


