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.Salary1;
import com.ruoyi.system.domain.Salary2;
import com.ruoyi.system.domain.Salary3;
import com.ruoyi.system.mapper.Salary1Mapper;
import com.ruoyi.system.mapper.Salary2Mapper;
import com.ruoyi.system.mapper.Salary3Mapper;
import com.ruoyi.system.mapper.SalaryMapper;
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.Arrays;
import java.util.Map;

/**
 * @author Shawn
 */
@RequestMapping("/finance/salary")
@RestController
public class SalaryController {

    @Autowired
    private SalaryMapper salaryMapper;

    @Autowired
    private Salary1Mapper salary1Mapper;

    @Autowired
    private Salary2Mapper salary2Mapper;

    @Autowired
    private Salary3Mapper salary3Mapper;

    @PreAuthorize("@ss.hasPermi('finance:salary:upload')")
    @GetMapping("/getSalaryStatus/{userName}/{unitId}/{monthId}")
    public AjaxResult getSalaryStatus(@PathVariable String userName, @PathVariable String unitId, @PathVariable String monthId){
        String s = salaryMapper.getFinanceSalaryStatus(userName, unitId, monthId);
        return AjaxResult.success(s);
    }

    @PreAuthorize("@ss.hasPermi('finance:salary:upload')")
    @PostMapping("/setSalaryInfo/{userName}/{unitId}/{monthId}")
    @Transactional
    public AjaxResult setSalaryInfo(@RequestBody String jsona,@PathVariable String userName,@PathVariable String unitId,@PathVariable String monthId){
//        System.out.println(jsona);
        salaryMapper.SetSalaryStatusInfo(userName,unitId,monthId);
        Map<String,String> mapType = JSON.parseObject(jsona,Map.class);
//        System.out.println(mapType);
        for (Object obj : mapType.keySet()) {
            if (obj == "CGZ"){
                String CGZ = mapType.get("CGZ").substring(1, mapType.get("CGZ").length() - 1);
                for (String s : CGZ.split(Constants.GROUPSPLIT)) {
                    String[] CGZsplit = s.substring(1, s.length() - 1).split(Constants.SMALLSPLIT);
//                    System.out.println(Arrays.toString(CGZsplit));
                    Salary1 salary1 = new Salary1();
                    salary1.setUnitNumber(CGZsplit[0]);
                    salary1.setYearAndMonth(CGZsplit[1]);
                    salary1.setName(CGZsplit[2]);
                    BigDecimal salary = new BigDecimal(CGZsplit[3]);
                    salary1.setSalary(salary);
                    BigDecimal advanceBonus = new BigDecimal(CGZsplit[4]);
                    salary1.setAdvanceBonus(advanceBonus);
                    BigDecimal transportationFee = new BigDecimal(CGZsplit[5]);
                    salary1.setTransportationFee(transportationFee);
                    BigDecimal communicationFee = new BigDecimal(CGZsplit[6]);
                    salary1.setCommunicationFee(communicationFee);
                    BigDecimal onlineOfficeAllowance = new BigDecimal(CGZsplit[7]);
                    salary1.setOnlineOfficeAllowance(onlineOfficeAllowance);
                    BigDecimal  others= new BigDecimal(CGZsplit[8]);
                    salary1.setOthers(others);
                    BigDecimal award = new BigDecimal(CGZsplit[9]);
                    salary1.setAward(award);
                    BigDecimal fine = new BigDecimal(CGZsplit[10]);
                    salary1.setFine(fine);
                    BigDecimal subtotal = new BigDecimal(CGZsplit[11]);
                    salary1.setSubtotal(subtotal);
                    BigDecimal provideForAged = new BigDecimal(CGZsplit[12]);
                    salary1.setProvideForAged(provideForAged);
                    BigDecimal medicalInsurance = new BigDecimal(CGZsplit[13]);
                    salary1.setMedicalInsurance(medicalInsurance);
                    BigDecimal unemploymentInsurance = new BigDecimal(CGZsplit[14]);
                    salary1.setUnemploymentInsurance(unemploymentInsurance);
                    BigDecimal subtotalOnInsurance = new BigDecimal(CGZsplit[15]);
                    salary1.setSubtotalOnInsurance(subtotalOnInsurance);
                    BigDecimal provideFund = new BigDecimal(CGZsplit[16]);
                    salary1.setProvideFund(provideFund);
                    BigDecimal taxThisMonth = new BigDecimal(CGZsplit[17]);
                    salary1.setTaxThisMonth(taxThisMonth);
                    BigDecimal deductTotal = new BigDecimal(CGZsplit[18]);
                    salary1.setDeductTotal(deductTotal);
                    BigDecimal actualSalary = new BigDecimal(CGZsplit[19]);
                    salary1.setActualSalary(actualSalary);
                    salary1.setRemark(CGZsplit[20]);
                    salary1.setExplainInfo(CGZsplit[21]);
                    BigDecimal companySocialSecurity = new BigDecimal(CGZsplit[22]);
                    salary1.setCompanySocialSecurity(companySocialSecurity);
                    BigDecimal companyProvideFund = new BigDecimal(CGZsplit[23]);
                    salary1.setCompanyProvideFund(companyProvideFund);
                    salary1.setUploadPerson(CGZsplit[24]);
                    salary1Mapper.insertOne(salary1);
                }
            }//CGZ

            if (obj == "CQT"){
                String CQT = mapType.get("CQT").substring(1, mapType.get("CQT").length() - 1);
                for (String s : CQT.split(Constants.GROUPSPLIT)) {
                    String[] CQTsplit = s.substring(1, s.length() - 1).split(Constants.SMALLSPLIT);
                    Salary2 salary2 = new Salary2();
                    salary2.setUnitNumber(CQTsplit[0]);
                    salary2.setYearAndMonth(CQTsplit[1]);
                    BigDecimal employeeWelfare = new BigDecimal(CQTsplit[2]);
                    salary2.setEmployeeWelfare(employeeWelfare);
                    BigDecimal lowValueConsumable = new BigDecimal(CQTsplit[3]);
                    salary2.setLowValueConsumable(lowValueConsumable);
                    BigDecimal employeeEducationFee = new BigDecimal(CQTsplit[4]);
                    salary2.setEmployeeEducationFee(employeeEducationFee);
                    BigDecimal othersFee = new BigDecimal(CQTsplit[5]);
                    salary2.setOthersFee(othersFee);
                    salary2.setOthersFeeInfo(CQTsplit[6]);
                    salary2.setUploadPerson(CQTsplit[7]);
                    salary2Mapper.insertOne(salary2);
                }
            }//CQT

            if (obj == "CJT"){
                String CJT = mapType.get("CJT").substring(1, mapType.get("CJT").length() - 1);
                for (String s : CJT.split(Constants.GROUPSPLIT)) {
                    String[] CJTsplit = s.substring(1, s.length() - 1).split(Constants.SMALLSPLIT);
                    Salary3 salary3 = new Salary3();
                    salary3.setUnitNumber(CJTsplit[0]);
                    salary3.setYearAndMonth(CJTsplit[1]);
                    salary3.setName(CJTsplit[2]);
                    salary3.setPostLevel(CJTsplit[3]);
                    BigDecimal yearEndBonus = new BigDecimal(CJTsplit[4]);
                    salary3.setYearEndBonus(yearEndBonus);
                    salary3.setMark(CJTsplit[5]);
                    salary3.setUploadPerson(CJTsplit[6]);
                    salary3Mapper.insertOne(salary3);
                }
            }//CJT
        }
        return AjaxResult.success();
    }

    @RequestMapping("/Salarydownload")
    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;
    }

}
