package xyz.wbsite.action.ajax.admin;

import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import xyz.wbsite.frame.base.Error;
import xyz.wbsite.frame.excel.WExcel;
import xyz.wbsite.frame.utils.LogUtil;
import xyz.wbsite.frame.base.LocalData;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.base.BaseResponse;
import xyz.wbsite.frame.utils.ResponseUtil;
import xyz.wbsite.frame.utils.ValidationUtil;
import xyz.wbsite.frame.excel.exception.TemplateNotMatchException;
import xyz.wbsite.module.admin.ent.ConfigData;
import xyz.wbsite.module.admin.mgr.ConfigDataManager;
import xyz.wbsite.module.admin.req.ConfigDataCreateRequest;
import xyz.wbsite.module.admin.req.ConfigDataDeleteRequest;
import xyz.wbsite.module.admin.req.ConfigDataFindRequest;
import xyz.wbsite.module.admin.req.ConfigDataUpdateRequest;
import xyz.wbsite.module.admin.rsp.ConfigDataCreateResponse;
import xyz.wbsite.module.admin.rsp.ConfigDataDeleteResponse;
import xyz.wbsite.module.admin.rsp.ConfigDataFindResponse;
import xyz.wbsite.module.admin.rsp.ConfigDataUpdateResponse;

import java.io.IOException;
import java.util.List;

public class ConfigDataAjax{

    @Autowired
    private ConfigDataManager configDataManager;

    public ConfigDataCreateResponse create(ConfigDataCreateRequest request) {
        return configDataManager.create(request, LocalData.getToken());
    }

    public ConfigDataDeleteResponse delete(ConfigDataDeleteRequest request) {
        return configDataManager.delete(request, LocalData.getToken());
    }

    public ConfigDataUpdateResponse update(ConfigDataUpdateRequest request) {
        return configDataManager.update(request, LocalData.getToken());
    }

    public ConfigDataFindResponse find(ConfigDataFindRequest request) {
        return configDataManager.find(request, LocalData.getToken());
    }

    public Object template(){
        return ResponseUtil.apply(new WExcel<>(ConfigData.class));
    }

    public Object exports(ConfigDataFindRequest request) {
        ConfigDataFindResponse response = configDataManager.find(request, LocalData.getToken());
        if (response.hasError()) {
            return response;
        } else if (response.getTotalCount() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "导出数据为空");
            return response;
        }
        return ResponseUtil.apply(new WExcel<>(ConfigData.class).addDatas(response.getResult()));
    }

    public Object imports(MultipartFile file) {
        BaseResponse baseResponse = new BaseResponse();
        try {
            // 检查文件格式
            String originalFilename = file.getOriginalFilename() != null ? file.getOriginalFilename() : "";
            if (!originalFilename.matches(".+(.xlsx?|.XLSX?)$")) {
                baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件格式错误！");
                return baseResponse;
            }
            // 兼容2003以前老版本.xls
            ExcelTypeEnum excelTypeEnum = originalFilename.matches(".+(.xlsx|.XLSX)$") ? ExcelTypeEnum.XLSX : ExcelTypeEnum.XLS;
            WExcel sheet = new WExcel<>(ConfigData.class).read(file.getBytes(), excelTypeEnum, new WExcel.Processor<ConfigData>() {
                @Override
                public List<String> exec(ConfigData o, int index) {
                    ConfigDataCreateRequest request = MapperUtil.map(o, ConfigDataCreateRequest.class);
                    List<String> validate = ValidationUtil.validate(request);
                    if (validate == null || validate.size() == 0) {
                        ConfigDataCreateResponse configDataCreateResponse = configDataManager.create(request, LocalData.getToken());
                        if (configDataCreateResponse.hasError()) {
                            for (Error error : configDataCreateResponse.getErrors()) {
                                validate.add(error.getMessage());
                            }
                        }
                    }
                    return validate;
                }
            });
            // 当导入出现错误时可以将存在标注错误的Excel返回给用户改正
            if (sheet.hasError()) {
                return ResponseUtil.apply(sheet.getBytes(), sheet.getName() + "-检查.xlsx");
            } else {
                return baseResponse;
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.dumpException(e);
            baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件出错");
        } catch (TemplateNotMatchException e) {
            baseResponse.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
        }
        return baseResponse;
    }
}
