package com.ecep.contract.controller.project.satisfaction_survey;

import static com.ecep.contract.util.ExcelUtils.getCellValue;
import static com.ecep.contract.util.ExcelUtils.getRow;
import static com.ecep.contract.util.ExcelUtils.setCellValue;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.ecep.contract.util.ProxyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.MyDateTimeUtils;
import com.ecep.contract.constant.ProjectConstant;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.CustomerSatisfactionSurvey;
import com.ecep.contract.model.Employee;
import com.ecep.contract.model.Project;
import com.ecep.contract.service.CustomerSatisfactionSurveyService;
import com.ecep.contract.service.ProjectService;
import com.ecep.contract.task.Tasker;

import lombok.Setter;

public class ProjectCustomerSatisfactionSurveyExportAsExcelFile extends Tasker<Void> {
    private static final Logger logger = LoggerFactory.getLogger(ProjectCustomerSatisfactionSurveyExportAsExcelFile.class);
    private String name = "顾客满意度调查表";
    File destFile;
    @Setter
    private CustomerSatisfactionSurvey satisfactionSurvey;
    @Setter
    private CustomerSatisfactionSurveyService satisfactionSurveyService;
    @Setter
    private ProjectService projectService;

    CustomerSatisfactionSurveyService getSatisfactionSurveyService() {
        if (satisfactionSurveyService == null) {
            satisfactionSurveyService = getBean(CustomerSatisfactionSurveyService.class);
        }
        return satisfactionSurveyService;
    }

    ProjectService getProjectService() {
        if (projectService == null) {
            projectService = getBean(ProjectService.class);
        }
        return projectService;
    }

    @Override
    protected Void execute(MessageHolder holder) throws Exception {
        updateTitle("根据模板导出" + name);
        String path = getConfService().getString(ProjectConstant.KEY_CUSTOMER_SATISFACTION_SURVEY_TEMPLATE);
        if (!StringUtils.hasText(path)) {
            holder.error(name + "模板文件未设置，请先设置" + name + "模板文件");
            return null;
        }
        File template = new File(path);
        if (!template.exists()) {
            holder.warn(name + "模板文件 " + template.getAbsolutePath() + " 不存在，请检查");
            return null;
        }
        Project project = satisfactionSurvey.getProject();
        if (!ProxyUtils.isInitialized(project)) {
            project = getProjectService().findById(project.getId());
            satisfactionSurvey.setProject(project);
        }
        File dir = getProjectService().searchPath(project);
        LocalDate thatDay = LocalDate.now();
        if (satisfactionSurvey.getApplyTime() != null) {
            thatDay = satisfactionSurvey.getApplyTime().toLocalDate();
        }
        String filename = name + "_" + thatDay;
        String extension = StringUtils.getFilenameExtension(path);
        File destFile = new File(dir, filename + "." + extension);
        int count = 0;
        while (destFile.exists()) {
            holder.warn(destFile.getName() + " 已存在");
            destFile = new File(dir, filename + "_" + (++count) + "." + extension);
        }
        try (
                InputStream inp = new FileInputStream(template);
                Workbook wb = WorkbookFactory.create(inp)
        ) {
            updateProjectCustomerSatisfactionSurvey(wb, destFile, holder);
            holder.info(destFile.getName() + "已创建");
        } catch (Exception e) {
            holder.error(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    private void updateProjectCustomerSatisfactionSurvey(Workbook wb, File destFile, MessageHolder holder) throws IOException {
        Sheet sheet = null;
        if (wb.getNumberOfSheets() == 1) {
            sheet = wb.getSheetAt(0);
        } else {
            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                Sheet s = wb.getSheetAt(i);
                if (s.getSheetName().contains(name)) {
                    sheet = s;
                    break;
                }
            }
            if (sheet == null) {
                holder.error("找不到" + name + " sheet");
                return;
            }
        }
        holder.info("模板版本：" + getCellValue(sheet, "K1"));

        updateProjectCustomerSatisfactionSurvey(sheet, holder);
        wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
        // 输出到文件
        try (OutputStream fileOut = new FileOutputStream(destFile)) {
            wb.write(fileOut);
        } catch (FileNotFoundException e) {
            holder.error("写时发生文件错误，请检查文件是否被打开中, " + e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }

    private void updateProjectCustomerSatisfactionSurvey(Sheet sheet, MessageHolder holder) {
        updateTitle("更新 " + sheet.getSheetName() + " Sheet");
        Project project = satisfactionSurvey.getProject();
        Employee applicant = satisfactionSurvey.getApplicant();


        Company customer = project.getCustomer();
        if (customer != null) {
            if (!ProxyUtils.isInitialized(customer)) {
                customer = getCompanyService().findById(customer.getId());
                project.setCustomer(customer);
            }
            setCellValue(sheet, "A5", "致 " + customer.getName() + " (" + project.getCode() + ")");
        } else {
            setCellValue(sheet, "A5", "");
        }

        setCellValue(sheet, "K5", satisfactionSurvey.getCode());

        if (satisfactionSurvey.getApplyTime() != null) {
            setCellValue(sheet, "A9", MyDateTimeUtils.format(satisfactionSurvey.getApplyTime(), "yyyy 年 MM 月 dd 日"));
        }

        String[] split = StringUtils.split(satisfactionSurvey.getData(), ":");
        if (split != null) {
            String[] scores = split[1].split(",");
            for (int i = 0; i < scores.length; i++) {
                int val = Integer.parseInt(scores[i]);
                Row row = getRow(sheet, 12 + i, true);
                for (int k = 0; k < 10; k++) {
                    setCellValue(row, k + 2, ((10 - k) == val) ? "√" : "");
                }
            }
        }


        if (applicant != null) {
            if (!ProxyUtils.isInitialized(applicant)) {
                applicant = getEmployeeService().findById(applicant.getId());
                project.setApplicant(applicant);
            }
            setCellValue(sheet, "H31", applicant.getName());
        } else {
            setCellValue(sheet, "H31", "");
        }

        if (satisfactionSurvey.getApplyTime() != null) {
            setCellValue(sheet, "K31", MyDateTimeUtils.format(satisfactionSurvey.getApplyTime().toLocalDate()));
        }
    }
}
