package com.yizhi.application.international.service;

import com.alibaba.fastjson.JSON;
import com.yizhi.application.course.util.OssUpload;
import com.yizhi.core.application.context.TaskContext;
import com.yizhi.core.application.file.constant.FileConstant;
import com.yizhi.core.application.file.task.AbstractDefaultTask;
import com.yizhi.site.application.feign.PortalManageFeignClients;
import com.yizhi.site.application.vo.domain.SiteDicVo;
import com.yizhi.site.application.vo.site.InternationalVO;
import com.yizhi.util.application.date.DateUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lingye
 * @date 2020-8-24
 */

@Component
@Log4j2
public class InternationalExportService extends AbstractDefaultTask<String, Map<String, Object>> {


    @Value("${ACTIVE}")
    public String active;
    @Autowired
    private PortalManageFeignClients portalManageFeignClients;


    @Override
    protected String execute(Map<String, Object> map) {

        log.info("国际化导出异步处理开始");
        String upload = null;

        Long companyId = (Long) map.get("companyId");
        Long siteId = (Long) map.get("siteId");
        String taskLogSerialNo = (String) map.get("taskLogSerialNo");
        int type = (Integer) map.get("type");
        Long languageId = (Long) map.get("languageId");
        Long taskId = System.currentTimeMillis();
        Long accountId = (Long) map.get("accountId");
        List<InternationalVO> list = (List<InternationalVO>) map.get("list");
        log.info("国际化导出异步处理开始:" + list);

        String terminalName = "";

        switch (type) {
            case 0:
                terminalName = "管理端";
                break;
            case 1:
                terminalName = "移动端";
                break;
            case 2:
                terminalName = "PC端";
                break;
        }
        String language = "";
        SiteDicVo siteDic = null;
        if (languageId != null) {
            siteDic = new SiteDicVo();
            siteDic.setId(languageId);
            siteDic = portalManageFeignClients.get(siteDic);
            if (siteDic != null) {
                language = siteDic.getName();
            }
        }
        String taskName = "导出翻译_" + terminalName + "_" + language;
        map.put("taskLogSerialNo", taskLogSerialNo);
        map.put("taskName", taskName);

        //任务id   任务名字   操作人id  操作时间
        TaskContext taskContext = new TaskContext(taskId, taskLogSerialNo, taskName, accountId, new Date(), siteId,
                companyId);
        log.info("taskContext:" + taskContext);
        working(taskContext);

        try {
            String[] headers = new String[]{"key值", "中文字段", "翻译", "备注"};
            StringBuffer fileNameSb = new StringBuffer().append(terminalName)
                    .append("_").append(siteDic.getName())
                    .append("_").append(DateUtil.getYMDHMSS())
                    .append(".xls");
            String fileName = fileNameSb.toString();
            String path = new StringBuffer().append(FileConstant.SAVE_PATH).append(File.separator).append(fileNameSb).toString();
            File fileDir = new File(path);
            if (!fileDir.exists()) {
                fileDir.createNewFile();
            }

            HSSFWorkbook workBook = null;
            FileOutputStream os = null;
            File file = null;
            try {
                os = new FileOutputStream(path);
                // 创建新的Excel 工作簿
                workBook = new HSSFWorkbook();

                // 在Excel工作簿中建一工作表，其名为缺省值
                HSSFSheet sheet = workBook.createSheet("国际化库");

                // 第一行
                HSSFRow row = sheet.createRow(0);
                for (int i = 0; i < headers.length; i++) {
                    row.createCell(i).setCellValue(headers[i]);
                }

                InternationalVO internationalVO = null;
                // 填充数据
                for (int i = 0; i < list.size(); i++) {
                    internationalVO = list.get(i);
                    row = sheet.createRow(1 + i);
                    row.createCell(0).setCellValue(internationalVO.getKey());
                    row.createCell(1).setCellValue(internationalVO.getPreTranslation());
                    row.createCell(2).setCellValue(internationalVO.getPostTranslation());
                    row.createCell(3).setCellValue(internationalVO.getTranslateRemark());

                }
                workBook.write(os);
                upload = OssUpload.upload(path, fileName, active);
                file = new File(path);
                success(taskContext, upload);
                System.out.println(upload);
            } catch (Exception e1) {
                fail(taskContext, upload);
                log.info(JSON.toJSONString(e1));
            } finally {
                if (os != null) {
                    os.close();
                }
                if (workBook != null) {
                    workBook.close();
                }
                if (file != null) {
                    file.delete();
                }
            }
            //阿里云返回url
        } catch (IOException e1) {

            fail(taskContext, upload);
            log.info(JSON.toJSONString(e1));
        }
        log.info("国际化库导出异步处理结束");
        return upload;
    }


}
