package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.info.collection.domain.dto.CcdiAccountInfoAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiAccountInfoEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiAccountInfoQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiAccountInfoExcel;
import com.ruoyi.info.collection.domain.vo.AccountInfoImportFailureVO;
import com.ruoyi.info.collection.domain.vo.CcdiAccountInfoVO;
import com.ruoyi.info.collection.domain.vo.CcdiBaseStaffOptionVO;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.service.ICcdiAccountInfoService;
import com.ruoyi.info.collection.service.ICcdiBaseStaffService;
import com.ruoyi.info.collection.utils.EasyExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账户库Controller
 *
 * @author ruoyi
 * @date 2026-04-13
 */
@Tag(name = "账户库管理")
@RestController
@RequestMapping("/ccdi/accountInfo")
public class CcdiAccountInfoController extends BaseController {

    @Resource
    private ICcdiAccountInfoService accountInfoService;

    @Resource
    private ICcdiBaseStaffService baseStaffService;

    /**
     * 查询账户库列表
     */
    @Operation(summary = "查询账户库列表")
    @PreAuthorize("@ss.hasPermi('ccdi:accountInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiAccountInfoQueryDTO queryDTO) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiAccountInfoVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiAccountInfoVO> result = accountInfoService.selectAccountInfoPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    /**
     * 查询账户库详情
     */
    @Operation(summary = "查询账户库详情")
    @PreAuthorize("@ss.hasPermi('ccdi:accountInfo:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(accountInfoService.selectAccountInfoById(id));
    }

    /**
     * 新增账户
     */
    @Operation(summary = "新增账户")
    @PreAuthorize("@ss.hasPermi('ccdi:accountInfo:add')")
    @Log(title = "账户库管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CcdiAccountInfoAddDTO addDTO) {
        return toAjax(accountInfoService.insertAccountInfo(addDTO));
    }

    /**
     * 修改账户
     */
    @Operation(summary = "修改账户")
    @PreAuthorize("@ss.hasPermi('ccdi:accountInfo:edit')")
    @Log(title = "账户库管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CcdiAccountInfoEditDTO editDTO) {
        return toAjax(accountInfoService.updateAccountInfo(editDTO));
    }

    /**
     * 删除账户
     */
    @Operation(summary = "删除账户")
    @PreAuthorize("@ss.hasPermi('ccdi:accountInfo:remove')")
    @Log(title = "账户库管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(accountInfoService.deleteAccountInfoByIds(ids));
    }

    /**
     * 查询账户归属员工下拉
     */
    @Operation(summary = "查询账户归属员工下拉")
    @PreAuthorize("@ss.hasPermi('ccdi:accountInfo:list')")
    @GetMapping("/staffOptions")
    public AjaxResult getStaffOptions(@RequestParam(required = false) String query) {
        List<CcdiBaseStaffOptionVO> list = baseStaffService.selectStaffOptions(query);
        return success(list);
    }

    /**
     * 查询关系人下拉
     */
    @Operation(summary = "查询关系人下拉")
    @PreAuthorize("@ss.hasPermi('ccdi:accountInfo:list')")
    @GetMapping("/relationOptions")
    public AjaxResult getRelationOptions(@RequestParam Long staffId) {
        return success(accountInfoService.selectRelationOptionsByStaffId(staffId));
    }

    /**
     * 下载导入模板
     */
    @Operation(summary = "下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateExcel(response, CcdiAccountInfoExcel.class, "账户库管理");
    }

    /**
     * 导入账户库信息
     */
    @Operation(summary = "导入账户库信息")
    @PreAuthorize("@ss.hasPermi('ccdi:accountInfo:import')")
    @Log(title = "账户库管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        List<CcdiAccountInfoExcel> list = EasyExcelUtil.importExcel(file.getInputStream(), CcdiAccountInfoExcel.class);
        if (list == null || list.isEmpty()) {
            return error("至少需要一条数据");
        }
        ImportResult result = accountInfoService.importAccountInfo(list, updateSupport);
        List<AccountInfoImportFailureVO> failures = accountInfoService.getLatestImportFailures();
        Map<String, Object> data = new HashMap<>(4);
        data.put("totalCount", result.getTotalCount());
        data.put("successCount", result.getSuccessCount());
        data.put("failureCount", result.getFailureCount());
        data.put("failures", failures);
        String message = "导入完成，共 " + result.getTotalCount() + " 条，成功 " + result.getSuccessCount()
            + " 条，失败 " + result.getFailureCount() + " 条";
        return AjaxResult.success(message, data);
    }
}
