package com.ruoyi.web.controller.finance;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.Invoice;
import com.ruoyi.system.domain.InvoiceSplit;
import com.ruoyi.system.mapper.BillKPMapper;
import com.ruoyi.system.mapper.InvoiceMapper;
import com.ruoyi.system.mapper.InvoiceSplitMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author Shawn
 */
@RestController
@RequestMapping("/finance/bill")
public class BillController {

    @Autowired
    private BillKPMapper billKPMapper;

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Autowired
    private InvoiceSplitMapper invoiceSplitMapper;

    @RequestMapping("/KPdownload")
    public String downloadBillFile(HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
//            String path = "C:\\Users\\Eric\\Desktop\\新建文件夹 (2)\\模板\\开票表-模板.xlsx";
            String path = "/usr/local/src/templates/开票表-模板.xlsx";
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/KPCFdownload")
    public String downloadBillCFFile(HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
//            String path = "C:\\Users\\Eric\\Desktop\\新建文件夹 (2)\\模板\\开票拆分表-模板.xlsx";
            String path = "/usr/local/src/templates/开票拆分表-模板.xlsx";
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }


    @PreAuthorize("@ss.hasPermi('finance:bill:upload')")
    @PostMapping("/uploadBillInfo")
    @Transactional
    public AjaxResult uploadBillInfo(@RequestBody String jsona){
//        System.out.println(jsona);
        Map<String,String> mapType = JSON.parseObject(jsona,Map.class);
        String substring = mapType.get("KP").substring(1, mapType.get("KP").length() - 1);
        for (String s : substring.split(Constants.GROUPSPLIT)) {
            Invoice invoice = new Invoice();
            String[] split = s.substring(1, s.length() - 1).split(Constants.SMALLSPLIT);
            invoice.setXunWangIndoorInvoiceNumber(split[0]);
            invoice.setFirstPartInvoice(split[1]);
            invoice.setFirstPartSectionNumber(split[2]);
            invoice.setFirstPartInvoiceConfirmNumber(split[3]);
            invoice.setProjectName(split[4]);
            BigDecimal orderConfirmMoney = new BigDecimal(split[5]);
            invoice.setOrderConfirmMoney(orderConfirmMoney);
            BigDecimal invoiceMoneyThisTime = new BigDecimal(split[6]);
            invoice.setInvoiceMoneyThisTime(invoiceMoneyThisTime);
            invoice.setTaxRate(split[7]);
            invoice.setFirstPartContact(split[8]);
            invoice.setOrderInformCount(split[9]);
            BigDecimal orderProgress = new BigDecimal(split[10]);
            invoice.setOrderProgress(orderProgress);
            invoice.setFirstPartInformTime(split[11]);
            invoice.setClearingMode(split[12]);
            invoice.setFirstPartFullName(split[13]);
            invoice.setSecondPartFullName(split[14]);
            invoice.setInvoiceIsSplit(split[15]);
            invoice.setXunWangProjectNumber(split[16]);
            invoice.setExplainInfo(split[17]);
            invoice.setApplicant(split[18]);
            invoice.setUploadPerson(split[19]);
            invoice.setCorrespondingIncomeNumber(split[20]);
            invoiceMapper.insertOne(invoice);
        }
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('finance:bill:upload')")
    @PostMapping("/uploadBillSplitInfo")
    @Transactional
    public AjaxResult uploadBillSplitInfo(@RequestBody String jsona2){
//        System.out.println(jsona2);
        Map<String,String> mapType = JSON.parseObject(jsona2,Map.class);
        String substring = mapType.get("KPCF").substring(1, mapType.get("KPCF").length() - 1);
        for (String s : substring.split(Constants.GROUPSPLIT)) {
            InvoiceSplit invoiceSplit = new InvoiceSplit();
            String[] split = s.substring(1, s.length() - 1).split(Constants.SMALLSPLIT);
            invoiceSplit.setInvoiceNumber(split[0]);
            BigDecimal invoiceIndoorSplit = new BigDecimal(split[1]);
            invoiceSplit.setInvoiceIndoorSplit(invoiceIndoorSplit);
            invoiceSplit.setIncludeXunWangProjectNumber(split[2]);
            invoiceSplit.setExplainInfo(split[3]);
            invoiceSplit.setApplicant(split[4]);
            invoiceSplit.setUploadPerson(split[5]);
            invoiceSplitMapper.insertOne(invoiceSplit);
        }
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('finance:bill:upload')")
    @GetMapping("/getHistoryTime/{userName}")
    @Transactional
    public AjaxResult getHistoryTime(@PathVariable String userName){
        String s = billKPMapper.selectKPTimeByName(userName);
        String s1 = billKPMapper.selectKPCFTimeByName(userName);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("KPLastTime",s);
        ajaxResult.put("KPCFLastTime",s1);
        return ajaxResult;
    }

}
