package nckd.jxccl.sit.hcsi.formplugin.web.tp.basedata;

import com.google.common.collect.Maps;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.MessageTypes;
import kd.bos.form.control.Control;
import kd.bos.form.control.Image;
import kd.bos.form.control.Label;
import kd.bos.form.control.events.UploadEvent;
import kd.bos.form.control.events.UploadListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.url.UrlService;
import nckd.jxccl.sit.hcsi.business.importtaskguide.ImportTaskGuideExportService;
import nckd.jxccl.sit.hcsi.business.importtaskguide.ImportTaskGuideImportService;

import java.util.EventObject;
import java.util.Map;

/**
 * 动态表单插件
 */
public class TaskGuideImportFormPlugin extends AbstractFormPlugin implements UploadListener {

    private static final String KEY_BTN_OK = "btnok";
    private static final String KEY_BTN_DOWNLOAD = "btndownload";
    private static final String KEY_BTN_RESETFILE = "btnresetfile";
    private static final String KEY_BTN_UPLOAD = "btnupload";

    public TaskGuideImportFormPlugin() {}

    @Override
    public void initialize() {
        this.addClickListeners(new String[]{KEY_BTN_OK, KEY_BTN_DOWNLOAD, KEY_BTN_RESETFILE});
        Image label = (Image)this.getControl(KEY_BTN_UPLOAD);
        label.addUploadListener(this);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        this.getView().setVisible(Boolean.FALSE, new String[]{"filepanel"});
        this.getView().setEnable(Boolean.FALSE, new String[]{"keyfields"});
        Label title = (Label)this.getControl("title");
        title.setText(ResManager.loadKDString("导入任务", "TaskGuideImportViewPlugin_0", "swc-hsas-formplugin", new Object[0]));
    }

    @Override
    public void click(EventObject evt) {
        switch (((Control)evt.getSource()).getKey()) {
            case KEY_BTN_OK:
                this.importData();
                break;
            case KEY_BTN_DOWNLOAD:
                ImportTaskGuideExportService exportService = new ImportTaskGuideExportService();
                exportService.exportExcelTemplate(this.getView());
                break;
            case KEY_BTN_RESETFILE:
                this.resetFileInfo();
        }
    }

    public void upload(UploadEvent evt) {
        Object[] urls = evt.getUrls();
        if (urls.length > 0) {
            IFormView view = this.getView();
            String url = (String)urls[0];
            view.setVisible(Boolean.TRUE, new String[]{"filepanel"});
            view.setVisible(Boolean.FALSE, new String[]{"uploadpanel"});
            IDataModel model = this.getModel();
            model.setValue("filename", url.substring(url.lastIndexOf(47) + 1));
            String fullUrl = UrlService.getAttachmentFullUrl(url);
            model.setValue("filepath", url);
            model.setValue("fullpath", fullUrl);
        }
    }

    private void resetFileInfo() {
        this.getModel().setValue("filename", "");
        this.getModel().setValue("filepath", "");
        this.getView().setVisible(Boolean.FALSE, new String[]{"filepanel"});
        this.getView().setVisible(Boolean.TRUE, new String[]{"uploadpanel"});
    }

    private void importData() {
        String url = this.getModel().getDataEntity().getString("filepath");
        if (StringUtils.isBlank(url)) {
            this.getView().showErrorNotification(ResManager.loadKDString("请先上传数据文件后操作。", "HSASCalTableImportStartPlugin_1", "swc-hsas-formplugin", new Object[0]));
        } else {
            FormShowParameter params = this.getView().getFormShowParameter();
            Long importTaskId = (Long)params.getCustomParam("importTaskId");
            Long sinsurTplId = (Long)params.getCustomParam("sinsurTplId");
            Long welfarepayerId = params.getCustomParam("welfarepayerId");
            Long periodId = params.getCustomParam("periodId");
            String periodNumber = params.getCustomParam("periodNumber");
            Long orgId = Long.valueOf(params.getCustomParam("orgId").toString());
            String importTaskName = (String)params.getCustomParam("importTaskName");
            String pageId = this.getView().getParentView().getPageId();
            ImportTaskGuideImportService importService = new ImportTaskGuideImportService(url, importTaskId, sinsurTplId, periodId, periodNumber, welfarepayerId);

            try {
                Map<String, String> result = importService.parseAndCheckExcelData(orgId, pageId, importTaskName);
                String errorMsg = (String)result.get("errorMsg");
                if (!StringUtils.isEmpty(errorMsg)) {
                    this.getView().showErrorNotification(errorMsg);
                    return;
                }

                Map<String, Object> returnData = Maps.newHashMapWithExpectedSize(16);
                returnData.put("isOk", Boolean.TRUE);
                returnData.put("totalCount", result.get("totalCount"));
                returnData.put("cacheKey", result.get("cacheKey"));
                returnData.put("importTaskId", importTaskId);
                returnData.put("sinsurTplId", sinsurTplId);
                this.getView().returnDataToParent(returnData);
                this.getView().close();
            } catch (Exception e) {
                String msg = ResManager.loadKDString("导入模板格式错误，请上传正确格式的数据模板。", "ImportConstants_3", "swc-hsbp-common", new Object[0]);
                this.getView().showMessage(msg, e.getMessage(), MessageTypes.Default);
            }

        }
    }
}