package com.iformall.controller;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.iformall.domain.po.WxAppinfo;
import com.iformall.service.WxAppinfoService;
import com.iformall.service.wechat.FmOpenService;
import com.iformall.utils.IPUtil;
import com.iformall.utils.MaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@RestController
public class BaseController {
    @Autowired
    private boolean isFmOpen;

    @Autowired
    private WxAppinfoService wxAppinfoService;

    @Autowired
    private FmOpenService openService;

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            public void setAsText(String value) {
                try {
                    setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value));
                } catch (ParseException e) {
                    try {
                        setValue(new SimpleDateFormat("yyyy-MM-dd ").parse(value));
                    } catch (ParseException e1) {
                        setValue(null);
                    }
                }
            }

            public String getAsText() {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) getValue());
            }

        });
    }

    public WxAppinfo getAppInfo(String appId) {
        return wxAppinfoService.getByAppId(appId);
    }

    public WxMaService getWeappService(String appId) {
        if(isFmOpen) {
            return openService.getWxOpenComponentService().getWxMaServiceByAppid(appId);
        } else {
            WxAppinfo appinfo = wxAppinfoService.getByAppId(appId);
            WxMaService service = MaUtil.getWeappService(appinfo);
            return service;
        }
    }

    public WxMaService getWeappServiceByAppInfo(WxAppinfo appinfo) {
        if(!isFmOpen) {
            WxMaService service = MaUtil.getWeappService(appinfo);
            return service;
        }
        return null;
    }

    public String getIpAddr() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipaddress = IPUtil.getIpAddr(request);
        return ipaddress;
    }
}
