package com.zg.project.wisdom.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.zg.common.exception.ServiceException;
import com.zg.common.utils.MinioUtil;
import com.zg.common.utils.SecurityUtils;
import com.zg.project.wisdom.domain.vo.AuditSignatureReviewVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zg.framework.aspectj.lang.annotation.Log;
import com.zg.framework.aspectj.lang.enums.BusinessType;
import com.zg.project.wisdom.domain.AuditSignature;
import com.zg.project.wisdom.service.IAuditSignatureService;
import com.zg.framework.web.controller.BaseController;
import com.zg.framework.web.domain.AjaxResult;
import com.zg.common.utils.poi.ExcelUtil;
import com.zg.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 审批记录Controller
 * 
 * @author zg
 * @date 2025-07-11
 */
@RestController
@RequestMapping("/wisdom/signature")
public class AuditSignatureController extends BaseController
{
    @Autowired
    private IAuditSignatureService auditSignatureService;

    @Autowired
    private MinioUtil minioUtil;

    /**
     * 上传签字图片到 MinIO
     */
    @PostMapping("/upload")
    public AjaxResult uploadSignature(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        try {
            String url = minioUtil.upload(file, "jaz", "signature/");
            return AjaxResult.success("上传成功").put("url", url);
        } catch (Exception e) {
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }
    //    上传图片，接收base64格式  zhangjinbo
    @PostMapping("/uploadBase64")
    public AjaxResult uploadSignatureBase64(@RequestBody Map<String, String> param) {
        String imgStr =  param.get("imgStr");
//        return AjaxResult.success("上传成功").put("url", imgStr);
        if (imgStr == null) {
            return AjaxResult.error("上传文件不能为空");
        }
        String url = minioUtil.uploadBase64(imgStr, "jaz","signature/");
        return AjaxResult.success("上传成功").put("url", url);

    }
    /**
     * 查询待审批记录列表
     */
//    @PreAuthorize("@ss.hasPermi('wisdom:signature:list')")
    @GetMapping("/list")
    public TableDataInfo list(AuditSignature auditSignature) {
        startPage();
        List<AuditSignatureReviewVO> list = auditSignatureService.selectAuditSignatureReviewList(auditSignature);
        return getDataTable(list);
    }

    /**
     * 查询个人提交审批记录
     */
//    @PreAuthorize("@ss.hasPermi('wisdom:signature:list')")
    @GetMapping("/user/list")
    public TableDataInfo listMySubmitRecords(AuditSignature auditSignature)
    {
        startPage();
        auditSignature.setSignerId(SecurityUtils.getUserId().toString()); // 当前用户
        List<AuditSignatureReviewVO> list = auditSignatureService.selectMySubmittedAuditList(auditSignature);
        return getDataTable(list);
    }

    /**
     * 导出审批记录列表
     */
    @PreAuthorize("@ss.hasPermi('wisdom:signature:export')")
    @Log(title = "审批记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AuditSignature auditSignature)
    {
        List<AuditSignature> list = auditSignatureService.selectAuditSignatureList(auditSignature);
        ExcelUtil<AuditSignature> util = new ExcelUtil<AuditSignature>(AuditSignature.class);
        util.exportExcel(response, list, "审批记录数据");
    }

    /**
     * 获取审批记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('wisdom:signature:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(auditSignatureService.selectAuditSignatureById(id));
    }


    /**
     * 审批
     */
    @PreAuthorize("@ss.hasPermi('wisdom:signature:edit')")
    @Log(title = "审批记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult approve(@RequestBody AuditSignature auditSignature) {
        return toAjax(auditSignatureService.approveAuditSignature(auditSignature));
    }

    /**
     * 删除审批记录
     */
    @PreAuthorize("@ss.hasPermi('wisdom:signature:remove')")
    @Log(title = "审批记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(auditSignatureService.deleteAuditSignatureByIds(ids));
    }

    /**
     * 当前用户待审核列表条数
     * @return
     */
    @GetMapping("/count")
    public AjaxResult getPending(AuditSignature auditSignat) {
        String approverId = auditSignat.getApproverId();
        int total = auditSignatureService.countPendingByUser(approverId);
        return AjaxResult.success(total);
    }

    /**
     * 审核操作（通过 / 驳回）
     */
    @PostMapping("/audit")
    public AjaxResult audit(@RequestBody AuditSignature audit) {
        try {
            auditSignatureService.audit(audit);
            return AjaxResult.success("审核成功");
        } catch (ServiceException e) {
            return AjaxResult.error("审核失败：" + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("系统异常，请联系管理员");
        }
    }
}
