package com.yida.data.user.controller;

import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.user.EduParent;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.WxUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.user.service.EduParentService;
import com.yida.data.user.service.EduStaffService;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Api(tags = "用户")
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/user")
public class EduUserController {
    private final EduParentService eduParentService;
    private final EduStaffService eduStaffService;
    private final WxUtil wxUtil;
    private final CommonService commonService;


    @ApiOperation("获取openId")
    @GetMapping("/bindWxOpenId")
    public ResultBean<String> getOpenId(@ApiParam("code") String code,
                                        @ApiParam("用户类型，0-家长，1-老师") Integer type,
                                        @ApiParam("用户id(家长id或老师id)") Long identityId) {
        log.info("user:[{}]", FebsUtil.getCurrentUser());
        Dept school = commonService.getDept(FebsUtil.getTopDeptId());
        EduParent parent = null;
        EduStaff staff = null;
        if (type == 0) {
            parent = eduParentService.getById(identityId);
        } else if (type == 1) {
            staff = eduStaffService.getById(identityId);
        }
        if (Objects.isNull(parent) && Objects.isNull(staff)) {
            throw new FebsException("人员信息异常");
        }
        String openId = type == 0 ? parent.getWxPublicOpenId() : staff.getWxPublicOpenId();
        if (StrUtil.isBlank(openId)) {
            openId = wxUtil.getOpenId(school.getWxPublicAppId(), school.getWxPublicSecret(), code);
            if (type == 0) {
                parent.setWxPublicOpenId(openId);
                eduParentService.updateById(parent);
            } else if (type == 1) {
                log.info("职工绑定");
                staff.setWxPublicOpenId(openId);
                eduStaffService.updateById(staff);
            }
        }
        return ResultBean.buildSuccess(openId);
    }
}
