package com.iformall.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.iformall.common.ErrorCode;
import com.iformall.domain.po.WxAppinfo;
import com.iformall.domain.po.WxCUser;
import com.iformall.domain.po.WxCUserBasicInfo;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxAppinfoService;
import com.iformall.service.WxCUserBasicInfoService;
import com.iformall.service.WxCUserService;
import com.iformall.service.wechat.FmOpenService;
import com.iformall.utils.Constant;
import com.iformall.utils.IPUtil;
import com.iformall.utils.MaUtil;
import org.apache.commons.lang3.StringUtils;
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;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

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

    @Autowired
    private WxCUserService wxCUserService;

    @Autowired
    private WxAppinfoService wxAppinfoService;

    @Autowired
    private FmOpenService openService;

    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @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 String getTenantId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String tenantId = (String) request.getAttribute(Constant.TENANT_ID);
        return tenantId;
    }

    public Long getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Long cUserId = (Long) request.getAttribute(Constant.LOGIN_USER_KEY);
        return cUserId;
    }

    /**
     * 请尽量多用getTenantId, getUserId
     */
    public WxCUser getUser() {
        Long cUserId = getUserId();
        WxCUser user = wxCUserService.getById(cUserId);
        if (user == null)
            throw new MallinkException(ErrorCode.USER_IS_EMPTY);
        return user;
    }

    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);
            if (appinfo == null) {
                return null;
            }
            WxMaService service = MaUtil.getWeappService(appinfo);
            return service;
        }

    }

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


    public void saveToBasicInfo(WxCUser user) {
        String phone = user.getPhone();
        if (phone != null && phone.contains("*")) {
            phone = user.getVerifyCodePhone();
        }
        if (StringUtils.isBlank(phone))
            return;

        List<WxCUserBasicInfo> list = wxCUserBasicInfoService.findByPhone(user.getTenantId(), phone);
        if (list.size() > 0) {
            WxCUserBasicInfo basicInfo = list.get(0);
            // 微信名称，统一成微信昵称
            if (!Objects.equals(basicInfo.getNickName(), user.getNickName())) {
                basicInfo.setNickName(user.getNickName());
            }
            // 性别
            if (basicInfo.getSex() == null) {
                basicInfo.setSex(user.getGender());
            }
            // 成长值
            if (Objects.nonNull(user.getScore())) {
                basicInfo.setPoins(user.getScore());
            }
            // 积分
            if (Objects.nonNull(user.getCredit())) {
                basicInfo.setCredit(user.getCredit());
            }
            wxCUserBasicInfoService.updateObj(basicInfo, user);
        } else {
            Date cur = new Date();
            WxCUserBasicInfo basicInfo = new WxCUserBasicInfo();
            basicInfo.setId(user.getId());
            basicInfo.setTenantId(user.getTenantId());
            basicInfo.setPhone(phone);
            basicInfo.setNickName(user.getNickName());
            basicInfo.setSex(user.getGender());
            basicInfo.setPoins(user.getScore());
            basicInfo.setCreateDate(cur);
            basicInfo.setUpdateDate(cur);
            basicInfo.setCredit(user.getCredit());
            wxCUserBasicInfoService.save(basicInfo);
        }
    }

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