package com.seeyon.apps.qrCodeForm.manager;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.qrCodeForm.constant.Constants;
import com.seeyon.apps.qrCodeForm.constant.QrCodeFormConstants;
import com.seeyon.apps.qrCodeForm.constant.SupportTypeEnum;
import com.seeyon.apps.weixin.manager.WechatUserManager;
import com.seeyon.apps.weixin.po.WechatUser;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.modules.business.BusinessSourceTypeManager;
import com.seeyon.cap4.form.modules.business.FormAppBO;
import com.seeyon.cap4.form.util.BizUtil;
import com.seeyon.cap4.form.util.Enums;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.HttpClientUtil;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.AjaxAccess;
import com.seeyon.ctp.util.annotation.Inject;
import org.apache.commons.logging.Log;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class QrCodeFormManagerImpl implements QrCodeFormManager {

    private static Log log = CtpLogFactory.getLog(QrCodeFormManagerImpl.class);

    @Inject
    private FormApi4Cap4 formApi4Cap4;
    @Inject
    private OrgManager orgManager;
    @Inject
    private ICstConfigApi cstConfigApi;
    @Inject
    public WechatUserManager wechatUserManager;


    /**
     * 获取应用包数据
     *
     * @param params
     * @return
     */
    @Override
    @AjaxAccess
    public List<Map<String, Object>> listBusiness(Map<String, Object> params) {
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        try {
            FlipInfo fi = new FlipInfo(1, -1);
            Map<String, Object> resultMap = formApi4Cap4.listBusiness(fi, params);
            if (Strings.isNotEmpty(fi.getData())) {
                listMap = fi.getData();
            }
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        return listMap;
    }

    /**
     * 获取所有的应用下的模板
     *
     * @param params
     * @return
     */
    @AjaxAccess
    @Override
    public List<FormAppBO> listFormApp(Map<String, Object> params) {
        List<FormAppBO> returnList = new ArrayList<>();
        String type = ParamUtil.getString(params, "type");
        String bizConfigId = ParamUtil.getString(params, "bizConfigId");
        BusinessSourceTypeManager sourceType = BizUtil.getSourceTypeById(type);
        Long bizConfigL = 0L;
        if (Strings.isNotBlank(bizConfigId)) {
            bizConfigL = Long.parseLong(bizConfigId);
        }
        try {
            List<FormAppBO> allList = sourceType.getFormAppBOList(AppContext.getCurrentUser(), "", "", false, bizConfigL);
            if (Strings.isNotEmpty(allList)) {
                returnList = allList.stream().filter(a -> !"PARENT".equals(a.getSourctTypeName())).collect(Collectors.toList());
            }
        } catch (BusinessException e) {
            log.error("获取所有模板异常", e);
        }
        return returnList;
    }

    @Override
    @AjaxAccess
    public Map<String, Object> qrCodeFormUrl(Map<String, Object> params) throws UnsupportedEncodingException {
        Map<String, Object> result = new HashMap<>();
        Integer sourceType = ParamUtil.getInt(params, "sourceType");
        //String fillUrl = Constants._URLTPL.replaceAll("\\{corpId}", Constants._CORPID);
        String fillUrl;
        String _redirecturi = Constants._REDIRECTURI;
        if (sourceType == Enums.SourceType.SOURCE_TYPE_FLOWTEMPLATE.getKey()) {
            String templateId = ParamUtil.getString(params, "templateId");
            String tourl = Constants.FLOW_URL + templateId;
            try {
//                fillUrl = fillUrl + URLEncoder.encode(
                String address = cstConfigApi.getConfig(QrCodeFormConstants.getPluginId(), QrCodeFormConstants.oaAddress.name());;
                fillUrl = address + SystemEnvironment.getContextPath() + _redirecturi;
                fillUrl +=  URLEncoder.encode(tourl, "UTF-8");
//                        "http://172.16.30.123:8081"+ SystemEnvironment.getContextPath() + _redirecturi + tourl, "UTF-8"
//                ) + Constants._FIXURL;
                result.put("fillUrl", fillUrl);
                return result;
            } catch (UnsupportedEncodingException e) {
                log.error("地址处理异常", e);
            }
        } else if (sourceType == Enums.SourceType.SOURCE_TYPE_INFOMANAGE.getKey()) {
            String formType = ParamUtil.getString(params, "formType");
            String type = ParamUtil.getString(params, "type");
            String title = ParamUtil.getString(params, "title");
            String moduleId = ParamUtil.getString(params, "moduleId");
            String formTemplateId = ParamUtil.getString(params, "formTemplateId");
            String moduleType = ParamUtil.getString(params, "moduleType");
            String operateType = ParamUtil.getString(params, "operateType");
            String rightId = ParamUtil.getString(params, "rightId");
            //http://127.0.0.1/seeyon/qrCodeForm.do?method=newMain&html=/seeyon/m3/apps/v5/cap4/htmls/native/form/index.html?cusType=true&formTemplateId=-4624141853295951831&moduleId=-4624141853295951831&moduleType=42&formType=main&type=new&operateType=0&rightId=-1
            String tourl = Constants.UNFLOW_URL + "cusType=true"
                    + "&formTemplateId=" + formTemplateId
                    + "&moduleId=" + moduleId
                    + "&moduleType=" + moduleType
                    + "&formType=" + formType
                    + "&type=" + type
                    + "&rightId=" + rightId
                    + "&operateType=" + operateType;
            try {
//                fillUrl = fillUrl + URLEncoder.encode(
                String address = cstConfigApi.getConfig(QrCodeFormConstants.getPluginId(), QrCodeFormConstants.oaAddress.name());
                fillUrl = address + SystemEnvironment.getContextPath() + _redirecturi;

                fillUrl += URLEncoder.encode(tourl, "UTF-8");
//                        "http://172.16.30.123:80"+ SystemEnvironment.getContextPath() + _redirecturi + tourl, "UTF-8"
//                ) + Constants._FIXURL;
                log.info("生成地址为：" + fillUrl);
                result.put("fillUrl", fillUrl);
                return result;
            } catch (UnsupportedEncodingException e) {
                log.error("地址处理异常", e);
            }
        }
        return result;
    }

}
