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.Locations;
import xyz.wbsite.module.admin.mgr.LocationsManager;
import xyz.wbsite.module.admin.req.LocationsCreateRequest;
import xyz.wbsite.module.admin.req.LocationsDeleteRequest;
import xyz.wbsite.module.admin.req.LocationsFindRequest;
import xyz.wbsite.module.admin.req.LocationsUpdateRequest;
import xyz.wbsite.module.admin.rsp.LocationsCreateResponse;
import xyz.wbsite.module.admin.rsp.LocationsDeleteResponse;
import xyz.wbsite.module.admin.rsp.LocationsFindResponse;
import xyz.wbsite.module.admin.rsp.LocationsUpdateResponse;

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

public class LocationsAjax{

    @Autowired
    private LocationsManager locationsManager;

    public LocationsCreateResponse create(LocationsCreateRequest request) {
        return locationsManager.create(request, LocalData.getToken());
    }

    public LocationsDeleteResponse delete(LocationsDeleteRequest request) {
        return locationsManager.delete(request, LocalData.getToken());
    }

    public LocationsUpdateResponse update(LocationsUpdateRequest request) {
        return locationsManager.update(request, LocalData.getToken());
    }

    public LocationsFindResponse find(LocationsFindRequest request) {
        return locationsManager.find(request, LocalData.getToken());
    }

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

    public Object exports(LocationsFindRequest request) {
        LocationsFindResponse response = locationsManager.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<>(Locations.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<>(Locations.class).read(file.getBytes(), excelTypeEnum, new WExcel.Processor<Locations>() {
                @Override
                public List<String> exec(Locations o, int index) {
                    LocationsCreateRequest request = MapperUtil.map(o, LocationsCreateRequest.class);
                    List<String> validate = ValidationUtil.validate(request);
                    if (validate == null || validate.size() == 0) {
                        LocationsCreateResponse locationsCreateResponse = locationsManager.create(request, LocalData.getToken());
                        if (locationsCreateResponse.hasError()) {
                            for (Error error : locationsCreateResponse.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;
    }
}
