package com.ruoyi.klk.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.annotations.UserLoginToken;
import com.ruoyi.common.utils.PdfUtil;
import com.ruoyi.frequency.agreement.entity.Agreement;
import com.ruoyi.frequency.agreement.service.AgreementService;
import com.ruoyi.klk.controller.req.AddOrUpdateBankCardReq;
import com.ruoyi.klk.controller.req.AgreementReq;
import com.ruoyi.klk.controller.req.GetBankNameReq;
import com.ruoyi.klk.controller.resp.GetBankInfoResp;
import com.ruoyi.klk.service.KlkService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.RyController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api/klk")
@Api(tags = "拉卡拉相关")
public class KlkController extends RyController {

    @Autowired
    private KlkService klkService;

    @Value("${lalkla.filePath}")
    private String filePath;

    /**
     * 查询开户行名称
     */
    @GetMapping("/test")
    @ApiOperation(value = "查询开户行名称", notes = "查询开户行名称")
    public ResponseData test() throws FileNotFoundException {
        PdfUtil.doc2pdf(filePath+"1.docx", filePath+"1.pdf", filePath + "license.xml");
        return ResponseData.success();
    }

    /**
     * 查询开户行名称
     */
    @PostMapping("/getBankName")
    @UserLoginToken
    @ApiOperation(value = "查询开户行名称", notes = "查询开户行名称")
    public ResponseData getBankName(@RequestBody GetBankNameReq req) {
        return klkService.getBankName(req);
    }


    /**
     * 添加或修改银行卡信息
     */
    @PostMapping("/addOrUpdateBankCard")
    @UserLoginToken
    @ApiOperation(value = "添加或修改银行卡信息", notes = "添加或修改银行卡信息")
    public ResponseData addOrUpdateBankCard(@RequestBody AddOrUpdateBankCardReq req) {
        return klkService.addOrUpdateBankCard(req, getUserVo());
    }

    @Autowired
    private AgreementService agreementService;

    /**
     * 获取分账协议
     */
    @PostMapping("/agreement")
    @UserLoginToken
    @ApiOperation(value = "添加或修改银行卡信息", notes = "获取分账协议")
    public ResponseData agreement(@RequestBody AgreementReq req) {

        if ("fzxy".equals(req.getCode())) {

            Agreement agreement = agreementService.getOne(new QueryWrapper<Agreement>().lambda().eq(Agreement::getCode, req.getCode()));
            if (agreement == null) {
                return ResponseData.success();
            }
            String agreementStr = agreement.getContent();

            Integer year = 5;
            agreementStr = agreementStr.replace("${store.name}", (req.getAcctName() == null ? "" : req.getAcctName()));
            agreementStr = agreementStr.replace("${store.idno}", (req.getAcctCertificateNo() == null ? "" : req.getAcctCertificateNo()));
            agreementStr = agreementStr.replace("${year}", (year + ""));
            agreementStr = agreementStr.replace("${beginYear}", (DateUtil.year(new Date()) + ""));
            agreementStr = agreementStr.replace("${beginMonth}", (DateUtil.month(new Date()) + 1) + "");
            agreementStr = agreementStr.replace("${beginDay}", (DateUtil.dayOfMonth(new Date()) + ""));

            Date date = DateUtil.offsetMonth(new Date(), year * 12);

            agreementStr = agreementStr.replace("${endYear}", (DateUtil.year(date) + ""));
            agreementStr = agreementStr.replace("${endMonth}", (DateUtil.month(date) + 1) + "");
            agreementStr = agreementStr.replace("${endDay}", (DateUtil.dayOfMonth(date) + ""));

            return ResponseData.success(agreementStr);
        } else if ("sale_fzxy".equals(req.getCode())) {
            Agreement agreement = agreementService.getOne(new QueryWrapper<Agreement>().lambda().eq(Agreement::getCode, req.getCode()));
            if (agreement == null) {
                return ResponseData.success();
            }
            String agreementStr = agreement.getContent();
            Integer year = 5;
            agreementStr = agreementStr.replace("${store.name}", (req.getAcctName() == null ? "" : req.getAcctName()));
            agreementStr = agreementStr.replace("${store.idno}", (req.getAcctCertificateNo() == null ? "" : req.getAcctCertificateNo()));
            agreementStr = agreementStr.replace("${year}", (year + ""));
            agreementStr = agreementStr.replace("${beginYear}", (DateUtil.year(new Date()) + ""));
            agreementStr = agreementStr.replace("${beginMonth}", (DateUtil.month(new Date()) + 1) + "");
            agreementStr = agreementStr.replace("${beginDay}", (DateUtil.dayOfMonth(new Date()) + ""));

            Date date = DateUtil.offsetMonth(new Date(), year * 12);

            agreementStr = agreementStr.replace("${endYear}", (DateUtil.year(date) + ""));
            agreementStr = agreementStr.replace("${endMonth}", (DateUtil.month(date) + 1) + "");
            agreementStr = agreementStr.replace("${endDay}", (DateUtil.dayOfMonth(date) + ""));

            return ResponseData.success(agreementStr);
        } else {
            return ResponseData.success();
        }
    }

    /**
     * 获取银行卡信息
     */
    @PostMapping("/getBankInfo")
    @UserLoginToken
    @ApiOperation(value = "获取银行卡信息", notes = "获取银行卡信息")
    public ResponseData<GetBankInfoResp> getBankInfo() {
        return klkService.getBankInfo(getUserVo());
    }


    public static void convertHtmlToImage(String input, String outPut) throws Exception {

        // 创建XWPFDocument对象，加载Word文档
        XWPFDocument doc = new XWPFDocument(new FileInputStream(input));
        // 获取文档中的所有段落
        List<XWPFParagraph> paragraphs = doc.getParagraphs();

        Integer year = 5;

        Date date = DateUtil.offsetMonth(new Date(), year * 12);

        // 遍历所有段落，找到需要修改的内容
        for (XWPFParagraph paragraph : paragraphs) {
            if (StrUtil.isBlank(paragraph.getText())) {
                continue;
            }
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String text = run.text();
                if (StrUtil.isBlank(text)) {
                    continue;
                }
                String newText = text;
                if (newText.contains("${store.name}")) {
                    newText = newText.replace("${store.name}", "张三");
                }
                if (newText.contains("${store.idno}")) {
                    newText = newText.replace("${store.idno}", "342222199609110817");
                }
                if (newText.contains("${year}")) {
                    newText = newText.replace("${year}", (year + ""));
                }
                if (newText.contains("${beginYear}")) {
                    newText = newText.replace("${beginYear}", (DateUtil.year(new Date()) + ""));
                }
                if (newText.contains("${beginMonth}")) {
                    newText = newText.replace("${beginMonth}", (DateUtil.month(new Date()) + 1) + "");
                }
                if (newText.contains("${beginDay}")) {
                    newText = newText.replace("${beginDay}", (DateUtil.dayOfMonth(new Date()) + ""));
                }
                if (newText.contains("${endYear}")) {
                    newText = newText.replace("${endYear}", (DateUtil.year(date) + ""));
                }
                if (newText.contains("${endMonth}")) {
                    newText = newText.replace("${endMonth}", (DateUtil.month(date) + 1) + "");
                }
                if (newText.contains("${endDay}")) {
                    newText = newText.replace("${endDay}", (DateUtil.dayOfMonth(date) + ""));
                }
                if (newText.contains("${endDay}")) {
                    newText = newText.replace("${endDay}", (DateUtil.dayOfMonth(date) + ""));
                }
                if (newText.contains("${date-qy}")) {
                    newText = newText.replace("${date-qy}", (DateUtil.formatDate(date) + ""));
                }
                run.setText(newText, 0);
            }
            String text = paragraph.getText();
            if (StrUtil.isNotBlank(text) && text.contains("签字/盖章")) {
                // 图片文件
                FileInputStream imageStream = new FileInputStream("C:\\Users\\Administrator\\Pictures\\背.png");
                XWPFRun provincialInfoPicRun = paragraph.createRun();
                provincialInfoPicRun.addPicture(imageStream, 5, "", Units.toEMU(80), Units.toEMU(40));
            }

        }
        // 保存修改后的文档
        FileOutputStream out = new FileOutputStream(outPut);
        doc.write(out);
        out.close();
    }


    public static void main(String[] args) throws Exception {
        String htmlFile = "G:\\input.docx";

        String outputFile = "G:\\out.docx";
        convertHtmlToImage(htmlFile, outputFile);
    }
}
