package nckd.jimin.jyyy.fi.plugin.form;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.fileservice.path.DecodeFileFactory;
import kd.bos.form.container.Tab;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Search;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.session.SessionDAO;
import kd.bos.session.SessionDAOFactory;
import kd.bos.url.UrlService;
import kd.imc.bds.common.utils.UrlServiceUtils;
import kd.imc.bds.common.utils.ViewUtil;
import kd.sdk.plugin.Plugin;

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

/**
 * 动态表单插件
 */
public class ViewImageByDownloadFilePlugin extends AbstractFormPlugin implements Plugin {

    private static Log logger = LogFactory.getLog(ViewImageByDownloadFilePlugin.class);

    public void registerListener(EventObject event) {
        this.addItemClickListeners(new String[]{"toolbarap"});
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        logger.info("ViewImages itemKey: " + itemKey);
        if (StringUtils.equals(itemKey, "down_test")) {
            this.downOneFile1();
        }
    }


    private void downOneFile1() {
        JSONObject selectImage = this.getSelectImage();
        if (selectImage != null) {
            String viewFileIndexList = selectImage.getString("viewFileIndexList");
            JSONArray imageArr = selectImage.getJSONArray("imageArr");

            for(int i = 0; i < imageArr.size(); ++i) {
                JSONObject imageJson = imageArr.getJSONObject(i);
                if (StringUtils.contains(viewFileIndexList, imageJson.getString("view_file_index"))) {
                    String fileUrl = imageJson.getString("downloadUrl");

                    if (StringUtils.isEmpty(fileUrl)) {
                        fileUrl = imageJson.getString("localUrl");
                    }
                    logger.info("ViewImages fileUrl: " + fileUrl);
                    String uuu = UrlServiceUtils.getDownloadUrl(fileUrl);
                    logger.info("ViewImages downFileURL: " + uuu);
                    this.getView().openUrl(uuu);
                    return;
                }
            }
        }

        this.getView().showTipNotification("下载失败，未查询到当前影像文件");
    }

    private JSONObject getSelectImage() {
        String selectImage = this.getPageCache().get("VIEW_IMAGE_LIST_SELECT");
        logger.info("ViewImages selectImage: " + selectImage);
        if (StringUtils.isEmpty(selectImage)) {
            return null;
        } else {
            String[] selectIndex = selectImage.split(",");
            String perfix = selectIndex[0];
            String index = selectIndex[1];
            String viewFileIndex = selectIndex[2];
            String viewFileIndexList = selectImage.substring(perfix.length() + index.length() + 1);
            String imageStr = this.getView().getPageCache().get("VIEW_IMAGE_LIST_KEY_" + index);
            logger.info("ViewImages imageStr: " + imageStr);
            JSONObject billJson = JSONObject.parseObject(imageStr);
            if (billJson == null) {
                return null;
            } else {
                billJson.put("viewFileIndex", viewFileIndex);
                billJson.put("viewFileIndexList", viewFileIndexList);
                logger.info("ViewImages getSelectImage: " + billJson);
                return billJson;
            }
        }
    }

    public static String getDownloadUrl(String path) {
        if (StringUtils.isNotEmpty(path)) {
            if (path.startsWith("http")) {
                return getCsPath(path);
            } else {
                String arfterDecodePath = DecodeFileFactory.getDecodeService().getDecodeFilePath(path);
                logger.info("ViewImages arfterDecodePath: " + arfterDecodePath);
                if (arfterDecodePath.startsWith("http")) {
                    return getCsPath(arfterDecodePath);
                } else {
                    String previewUrl = UrlService.getAttachmentFullUrl(arfterDecodePath);
                    logger.info("ViewImages previewUrl: " + previewUrl);
                    return getCsPath(previewUrl);
                }
            }
        } else {
            return path;
        }
    }

    public static String getCsPath(String path) {
        if (StringUtils.isNotEmpty(path) && !path.contains("kd_cs_ticket")) {
            String csTicketSuffix = getCsTicketSuffix();
            if (path.contains("?")) {
                path = path + "&" + csTicketSuffix;
            } else {
                path = path + "?" + csTicketSuffix;
            }
            logger.info("ViewImages path1: " + path);
            return path;
        } else {
            logger.info("ViewImages path2: " + path);
            return path;
        }
    }
    public static String getCsTicketSuffix() {
        String kdCsTicket = getCsrfToken(RequestContext.get().getGlobalSessionId());
        String kdCsTicketSuffix = "kd_cs_ticket=" + kdCsTicket;
        return kdCsTicketSuffix;
    }
    public static String getCsrfToken(String sessionId) {
        String returnValue = "";
        if (StringUtils.isNotEmpty(sessionId)) {
            SessionDAO sessionDAO = SessionDAOFactory.getSessionDAO(sessionId);
            Map<String, String> sessionInfo = sessionDAO.getAttributesAsMap(new String[]{"kdCsrfToken"});
            if (sessionInfo != null && sessionInfo.size() > 0) {
                returnValue = (String)sessionInfo.get("kdCsrfToken");
            }
        }

        return returnValue;
    }

}