package com.seeyon.apps.qrCodeForm.controller;

import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.qrCodeForm.constant.QrCodeFormConstants;
import com.seeyon.apps.qrCodeForm.manager.QrCodeFormManager;
import com.seeyon.apps.qrCodeForm.util.LoginUtil;
import com.seeyon.apps.weixin.util.SecurityCertUtil;
import com.seeyon.apps.weixin.util.WeixinUtil;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.constants.ProductEditionEnum;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.common.flag.SysFlag;
import com.seeyon.ctp.common.formula.FormulaUtil;
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.Strings;
import com.seeyon.ctp.util.annotation.Inject;
import org.apache.commons.logging.Log;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QrCodeFormController extends BaseController {
    private static Log log = CtpLogFactory.getLog(QrCodeFormController.class);
    @Inject
    private QrCodeFormManager qrCodeFormManager;
    @Inject
    private OrgManager orgManager;
    @Inject
    private ICstConfigApi cstConfigApi;

    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        log.info("访问二维码生成页面！");
        ModelAndView mav = new ModelAndView("plugin/qrCodeForm/qrCodeFormIndex");
        Map map = new HashMap<String, Object>();
        map.put("bizType", "1");
        map.put("type", "owner-authed-biz");
        map.put("businessType", 0);
        map.put("activeTab", "mineapp");
        List<Map<String, Object>> bizList = qrCodeFormManager.listBusiness(map);
        mav.addObject("bizList", bizList);
        return mav;
    }

//    https://oa.dhx.com.cn/seeyon/qrCodeForm.do?method=newMain&type=1
    public ModelAndView newMain(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView("/wechat/collaborationContent");
        String html = "";
        String type = request.getParameter("type");
        if(Strings.isNotBlank(type)) {
            //获取集成平台中url1的连接地址；/seeyon/m3/apps/v5/collaboration/html/newCollaboration.html?qc=ext&templateId=-2617827166221087111
            //可以通过配置完成地址的获取
            html = cstConfigApi.getConfig(QrCodeFormConstants.getPluginId(), "url" + type);
        }
        if(Strings.isBlank(html)) {
            html = URLDecoder.decode(request.getParameter("html"), "UTF-8");
        }
//        String loginName = qrCodeFormManager.getLoginMember(code);
        /**
         * 客开改动，固定登录名
         */
        //String loginName = (String) FormulaUtil.getVar("qrcode_loginname");
        String loginName = cstConfigApi.getConfig(QrCodeFormConstants.getPluginId(), QrCodeFormConstants.qrcode_loginname.name());
        log.info("登录认证获取loginName为：" + loginName);
        if(Strings.isEmpty(loginName)){
//            mav.addObject("msg", "未获取到人员信息！")b;
//            return mav;
            loginName = "seeyon";
        }

        V3xOrgMember member = orgManager.getMemberByLoginName(loginName);
        if(member == null){
            mav.addObject("msg", "人员不存在！");
            return mav;
        }
        SecurityCertUtil.login(request, loginName);

        Map map = LoginUtil.getToken(String.valueOf(member.getId()), member.getLoginName(), request, response);
        String success = String.valueOf(map.get("success"));
        if (success != null && "false".equals(success)) {
//            String message = map.get("message").toString();
//            if (message.contains("User not found")) {
//                mav.addObject("msg", ResourceUtil.getString("wxt.user.binding.miss")
//                        + "，" + ResourceUtil.getString("wxt.user.name") + wechatUser.getXtUserName() +
//                        "，" + ResourceUtil.getString("wxt.dingding.user.id") + wechatUser.getXtUserId());
//            } else {
//            }
            mav.addObject("msg", (String) map.get("message"));
            return mav;
        }

        String token = (String) map.get("id");
        String suffix = (String) SysFlag.mobileEditionSuffix.getFlag();
        String edition = ProductEditionEnum.getCurrentProductEditionEnum().getValue();
        String v5timestamp = WeixinUtil.getV5Timestamp();
        String address = cstConfigApi.getConfig(QrCodeFormConstants.getPluginId(), QrCodeFormConstants.oaAddress.name());
        if (Strings.isNotBlank(html)) {
            String url = address  + "" + SystemEnvironment.getContextPath() + "/H5/collaboration/index.html?token=" + token + "&edition=" + edition + "&suffix=" + suffix + "&v5timestamp=" + v5timestamp + "&loginName=" + member.getLoginName() + "&html=" + URLEncoder.encode(html, "UTF-8") + "&isAccount=&accountid=" + member.getOrgAccountId() + "&appid=";
            return new ModelAndView("redirect:" + url);
        } else {
            return new ModelAndView("redirect:" + address  + "" + SystemEnvironment.getContextPath() + "/H5/collaboration/index.html?token=" + token + "&edition=" + edition + "&suffix=" + suffix + "&v5timestamp=" + v5timestamp + "&loginName=" + member.getLoginName() + "&html=&isAccount=&accountid=" + member.getOrgAccountId());
        }
    }

}
