package cn.exploring.engine.server.wx.web;

import cn.exploring.engine.server.core.util.ResponseUtil;
import cn.exploring.engine.server.db.domain.WxUser;
import cn.exploring.engine.server.db.domain.WxUserFormid;
import cn.exploring.engine.server.db.service.WxUserFormIdService;
import cn.exploring.engine.server.db.service.WxUserService;
import cn.exploring.engine.server.wx.annotation.LoginUser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/wx/formid")
@Validated
public class WxUserFormId {
    private final Log logger = LogFactory.getLog(WxUserFormId.class);

    @Autowired
    private WxUserService userService;

    @Autowired
    private WxUserFormIdService formIdService;

    @GetMapping("create")
    public Object create(@LoginUser Integer userId, @NotNull String formId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        WxUser user = userService.findById(userId);
        WxUserFormid userFormid = new WxUserFormid();
        userFormid.setOpenid(user.getWeixinOpenid());
        userFormid.setFormid(formId);
        userFormid.setIsprepay(false);
        userFormid.setUseamount(1);
        userFormid.setExpireTime(LocalDateTime.now().plusDays(7));
        formIdService.addUserFormid(userFormid);

        return ResponseUtil.ok();
    }

    //用户基本信息 查询
    @GetMapping("/read")
    public Object read(@LoginUser Integer myUserId, Integer userId) {
        if(myUserId == null || myUserId <= 0){
            return ResponseUtil.unlogin();
        }

        if(userId == null || userId.intValue() == 0){
            return   ResponseUtil. badArgument();
        }

        WxUser user = userService.getUserInfoByIdFromCache(userId);
        if (user != null) {
            return ResponseUtil.ok(user);
        } else {
            return ResponseUtil.noUser();
        }
    }

    //我的基本信息 查询
    @PostMapping("/update")
    public Object update(@LoginUser Integer userId, @RequestBody  WxUser user) {
        if(userId == null || userId <= 0){
            return ResponseUtil.unlogin();
        }

        user.setId(userId);

        return  ResponseUtil.ok(userService.updateById(user));
    }
}
