package com.nasc.web.controller.custom;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.zxing.WriterException;
import com.nasc.common.annotation.Log;
import com.nasc.common.core.controller.BaseController;
import com.nasc.common.core.domain.AjaxResult;
import com.nasc.common.core.page.TableDataInfo;
import com.nasc.common.core.text.Convert;
import com.nasc.common.enums.BusinessType;
import com.nasc.common.utils.StringUtils;
import com.nasc.custom.domain.*;
import com.nasc.custom.service.INascRecordService;
import com.nasc.framework.web.domain.server.Sys;
import com.nasc.web.controller.tool.BarcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Jianq Yu
 * @Date: 2024/6/4 16:23
 * @Description: 审查事项记录
 */
@RestController
@RequestMapping("/nasc/record")
public class NascRecordController extends BaseController {

    @Autowired
    private INascRecordService recordService;

    /**
     * @Author: Yujianq
     * @Date: 2024/6/5 10:17
     * @Description: 新增打印日志
     * @param printLog
     * @return: com.nasc.common.core.domain.AjaxResult
     */
    @Log(title = "新增打印日志", businessType = BusinessType.INSERT)
    @PostMapping("addPrintLog")
    public AjaxResult addPrintLog(@Validated @RequestBody NascPrintLog printLog) {
        printLog.setUserId(getUserId());
        printLog.setUserName(getUsername());
        return toAjax(recordService.insertPrintLog(printLog));
    }

    @GetMapping("/getSerialNumber")
    public AjaxResult getSerialNumber() {
        String serialNumber = new StringBuilder(Convert.toStr(new Date().getTime())).reverse().toString();
        return AjaxResult.success("success", BarcodeGenerator.shuffleString(serialNumber));
    }

    @GetMapping("/getSerialNumberBarcode")
    public AjaxResult getSerialNumberBarcode() {
        String serialNumber = new StringBuilder(Convert.toStr(new Date().getTime())).reverse().toString();
        serialNumber = BarcodeGenerator.shuffleString(serialNumber);
        Map<String, String> result = new HashMap<>();
        result.put("serialNumber", serialNumber);
        try {
            String barcode = BarcodeGenerator.generateBarcodeWithTextAsBase64(serialNumber, 300, 100, 20, 10, "Arial");
            result.put("barcode", barcode);
            return AjaxResult.success("success", result);
        } catch (Exception e) {
            return AjaxResult.error("生成条形码失败");
        }
    }

    /**
     * @Author: Yujianq
     * @Date: 2024/6/5 10:17
     * @Description: 新增受理记录
     * @param dealRecord
     * @return: com.nasc.common.core.domain.AjaxResult
     */
    @Log(title = "新增受理记录", businessType = BusinessType.INSERT)
    @PostMapping("addDealRecord")
    public AjaxResult addDealRecord(@Validated @RequestBody NascDealRecord dealRecord) {
        dealRecord.setDealUser(getUserId());
        if (StrUtil.isEmpty(dealRecord.getSerialNumber())) {
            String serialNumber = new StringBuilder(Convert.toStr(new Date().getTime())).reverse().toString();
            dealRecord.setSerialNumber(BarcodeGenerator.shuffleString(serialNumber));
        }
        try {
//            dealRecord.setBarcode(BarcodeGenerator.generateBarcodeAsBase64(dealRecord.getSerialNumber(), 300, 100));
            dealRecord.setBarcode(BarcodeGenerator.generateBarcodeWithTextAsBase64(
                    dealRecord.getSerialNumber(), 300, 100, 20, 10, "Arial"));
        } catch (Exception e) {
        }
        return AjaxResult.success(recordService.addDealRecord(dealRecord));
    }

    @GetMapping("/listDealRecord")
    public TableDataInfo listDealRecord(NascDealRecord dealRecord) {
        startPage();
        List<Map<String, Object>> list = recordService.selectDealRecordList(dealRecord);
        return getDataTable(list);
    }

    @GetMapping("/getDealRecordById")
    public AjaxResult getDealRecordById(Long id) {
        return AjaxResult.success(recordService.getDealRecordById(id));
    }

    @Log(title = "修改受理记录状态", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDealRecordStatus")
    public AjaxResult updateDealRecordStatus(@RequestBody NascDealRecord dealRecord) {
        dealRecord.setWithStatus(1l);
        return AjaxResult.success(recordService.updateDealRecordStatus(dealRecord));
    }

    /**
     * @Author: Yujianq
     * @Date: 2024/6/5 10:17
     * @Description: 新增人工核验记录
     * @param manualVerify
     * @return: com.nasc.common.core.domain.AjaxResult
     */
    @Log(title = "新增人工核验记录", businessType = BusinessType.INSERT)
    @PostMapping("addManualVerify")
    public AjaxResult addManualVerify(@Validated @RequestBody NascManualVerify manualVerify) {
        return AjaxResult.success(recordService.addManualVerify(manualVerify));
    }

    @Log(title = "核验记录提交", businessType = BusinessType.UPDATE)
    @PostMapping("updateManualVerify")
    public AjaxResult updateManualVerify(@Validated @RequestBody NascManualVerify manualVerify) {
        manualVerify.setDealUser(getUserId());
        return AjaxResult.success(recordService.updateManualVerify(manualVerify));
    }

    @GetMapping("/listManualVerify")
    public TableDataInfo listManualVerify(String serialNumber, Integer dealStatus) {
        startPage();
        List<Map<String, Object>> list = recordService.selectManualVerifyList(serialNumber, dealStatus);
        return getDataTable(list);
    }

    /**
     * @Author: Yujianq
     * @Date: 2024/12/4 15:50
     * @Description: 根据ID获取所有人工审核信息
     * @param ids
     * @return: com.nasc.common.core.domain.AjaxResult
     */
    @GetMapping("/getManualVerifyByIds")
    public AjaxResult getManualVerifyByIds(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return AjaxResult.error("参数不能为空");
        }
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<NascManualVerify> list = recordService.getManualVerifyByIds(idList);
        return AjaxResult.success(list);
    }

    @Log(title = "上传证照", businessType = BusinessType.INSERT)
    @PostMapping("importCertificate")
    public AjaxResult importCertificate(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("文件内容为空，请核对后再试");
        }
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<NascCertificate> certificateList = reader.readAll(NascCertificate.class);
            int total = 0, unknown = 0, success = 0, fail = 0;
            total = certificateList.size();
            for (int i = certificateList.size() - 1; i >= 0; i --) {
                NascCertificate certificate = certificateList.get(i);
                if (StrUtil.isEmpty(certificate.getCertificateName()) || StrUtil.isEmpty(certificate.getCertificateNo())
                        || StrUtil.isEmpty(certificate.getPhone())) {
                    unknown ++;
                    certificateList.remove(i);
                    continue;
                }
                if ("个人".equals(certificate.getCertificateTypeName())) {
                    certificate.setCertificateType(1l);
                } else if ("企业".equals(certificate.getCertificateTypeName())) {
                    certificate.setCertificateType(2l);
                } else {
                    unknown ++;
                    certificateList.remove(i);
                }
            }
            success = recordService.insertCertificate(certificateList);
            fail = total - success - unknown;
            return AjaxResult.success("上传成功" + success + "条，失败" + fail + "条，格式错误" + unknown + "条");
        } catch (Exception e) {
            return AjaxResult.error("文件上传失败： " + e.getMessage());
        }
    }

    @GetMapping("/listCertificate")
    public TableDataInfo listCertificate(NascCertificate certificate) {
        startPage();
        List<NascCertificate> list = recordService.selectCertificateList(certificate);
        return getDataTable(list);
    }

    @Log(title = "新增发放证书记录", businessType = BusinessType.INSERT)
    @PostMapping("addCertificateSend")
    public AjaxResult addCertificateSend(@Validated @RequestBody List<NascCertificateSend> certificateSendList) {
        if (certificateSendList == null || certificateSendList.isEmpty()) {
            return AjaxResult.error("参数错误");
        }
        certificateSendList.forEach((certificateSend -> {
            certificateSend.setPrintUser(getUserId());
            certificateSend.setCertStatus(0l);
        }));
        return AjaxResult.success(recordService.addCertificateSend(certificateSendList));
    }

    @Log(title = "发放证书", businessType = BusinessType.UPDATE)
    @PostMapping("sendCertificate")
    public AjaxResult sendCertificate(@Validated @RequestBody List<NascCertificateSend> certificateSendList) {
        if (certificateSendList == null || certificateSendList.isEmpty()) {
            return AjaxResult.error("参数错误");
        }
        certificateSendList.forEach((certificateSend -> {
            certificateSend.setSendUser(getUserId());
            certificateSend.setCertStatus(1l);
        }));
        return AjaxResult.success(recordService.sendCertificate(certificateSendList));
    }

    @GetMapping("/listCertificateSend")
    public TableDataInfo listCertificateSend(NascCertificateSend certificateSend) {
        startPage();
        List<Map<String, Object>> list = recordService.selectCertificateSendList(certificateSend);
        return getDataTable(list);
    }

    @GetMapping("/listPrintLogList")
    public TableDataInfo listPrintLogList(NascPrintLog printLog) {
        startPage();
        List<Map<String, Object>> list = recordService.selectPrintLogList(printLog);
        return getDataTable(list);
    }

}
