package com.sysu.admin.site.lz;

import com.alibaba.excel.EasyExcel;
import com.mysql.jdbc.StringUtils;
import com.sysu.admin.controller.lz.everyday.LzEveryExcelListener;
import com.sysu.admin.controller.lz.everyday.LzEverydayExcel;
import com.sysu.admin.controller.lz.everyday.LzEverydayService;
import com.sysu.admin.controller.lz.everyday.LzEverydayImgService;
import com.sysu.admin.controller.lz.tree.LzTreeService;
import com.sysu.admin.site.CommonVo;
import com.sysu.admin.support.system.config.ConfigContext;
import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

@RequestMapping("/site/lz_everyday")
@RestController
public class LzEverydayController {

    @Autowired
    ConfigContext configContext;
    @Autowired
    LzTreeService lzTreeService;
    @Autowired
    LzEverydayService everydayService;
    @Autowired
    LzEverydayImgService lzEverydayImgService;

    /**
     * 把base64转化为文件.
     * @param base64   base64
     * @return boolean isTrue
     */
    public String decryptByBase64(String base64, String sign) {
        if (StringUtils.isNullOrEmpty(base64)) {
            return null;
        }
        int index = base64.indexOf(",");
        if(index > -1){
            base64 = base64.substring(index + 1);
        }
        String imageDirPath = configContext.getImageDirPath();
        String newFileName = imageDirPath + System.currentTimeMillis() + "_"+"_"+sign+".xlsx";
        try {
            Files.write(Paths.get(newFileName),
                    Base64.decodeBase64(base64), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFileName;
    }

    @RequestMapping("/updateData")
    public BaseResult uploadData(@RequestBody CommonVo commonVo){
        String filename = decryptByBase64(commonVo.base64,"lzxt_data");
        LzEveryExcelListener everyExcelListener = new LzEveryExcelListener(lzTreeService, everydayService, lzEverydayImgService);
        EasyExcel.read(new File(filename), LzEverydayExcel.class, everyExcelListener).doReadAllSync();;
        return R.succ();
    }
}
