package com.mortals.xhx.busiz.applets.web;


import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.IUser;
import com.mortals.xhx.base.login.web.LoginForm;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.busiz.applets.req.LoginReq;
import com.mortals.xhx.busiz.applets.req.StaffReq;
import com.mortals.xhx.busiz.applets.req.UserInfoReq;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.module.company.model.CompanyQuery;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.model.StaffRecordEntity;
import com.mortals.xhx.module.staff.service.StaffRecordService;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED_CONTENT;


/**
 * @author ZYW
 * @date 2023-10-30 9:39
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/login")
public class LoginApiController extends AbstractBaseController<LoginReq>{

    @Autowired
    private UserService userService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private IAuthTokenService authTokenService;


    @RequestMapping("login")
    public Rest<Object> login(@RequestBody LoginReq loginReq) throws Exception {
        String busiDesc = "小程序登录";
        Rest<Object> rest = Rest.ok();
        try {
            JSONObject data = new JSONObject();

            UserQuery userQuery = new UserQuery();
            userQuery.setOpenId(loginReq.getOpenId());
            UserEntity userEntity = userService.selectOne(userQuery);
            String token = "";
            //如果没查到用户，则第一次登录，根据openid创建用户
            if(ObjectUtils.isEmpty(userEntity)){
                UserEntity entity = new UserEntity();
                entity.setUserType(1);  //普通用户
                entity.setLastLoginTime(new Date());
                entity.setOpenId(loginReq.getOpenId());
                entity.setStatus(1);
                entity.setRealName("游客");
                entity.setLoginName(loginReq.getOpenId());
                entity.setLoginPwd("123");  //默认密码123
                entity.setCreateUserName("小程序");

                userService.save(entity);

                token = authTokenService.createToken(entity);

                log.info( busiDesc, "第一次登陆，保存用户信息成功");
                rest.setMsg("未查询到用户信息");
            }else {
                StaffQuery staffQuery = new StaffQuery();

                if(ObjectUtils.isEmpty(userEntity.getStaffId())){
                    rest.setMsg("后台未绑定员工信息");
                }else {
                    staffQuery.setId(userEntity.getStaffId());

                    StaffEntity staffEntity = staffService.selectOne(staffQuery);
                    data.put("userInfo",staffEntity);
                    if(ObjectUtils.isEmpty(userEntity)){
                        rest.setMsg("未查询到员工信息");
                    }
                }

                token = authTokenService.createToken(userEntity);
            }

            data.put("token", token);
            rest.setData(data);

            
        }catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }

        return rest;
    }


    @RequestMapping("updateUserInfo")
    public Rest<Object> updateUserInfo(@RequestBody UserInfoReq userInfoReq) throws Exception {
        String busiDesc = "小程序修改人员信息";
        Rest<Object> rest = Rest.ok();
        try {
            IUser iUser = authTokenService.getLoginUser(request);

            UserEntity user = userService.selectOne(new UserQuery().id(iUser.getId()));

            if(ObjectUtils.isEmpty(user)){
                rest = Rest.fail("获取个人信息失败");
            }else {
                if(!ObjectUtils.isEmpty(userInfoReq.getPhone())){
                    user.setPhone(userInfoReq.getPhone());
                }
                if(!ObjectUtils.isEmpty(userInfoReq.getEmail())){
                    user.setEmail(userInfoReq.getEmail());
                }
                if(!ObjectUtils.isEmpty(userInfoReq.getName())){
                    user.setLoginName(userInfoReq.getName());
                }
                if(!ObjectUtils.isEmpty(userInfoReq.getDeptName())){
                    user.setDeptName(userInfoReq.getDeptName());
                }
                if(!ObjectUtils.isEmpty(userInfoReq.getRealName())){
                    user.setRealName(userInfoReq.getRealName());
                }

                if(!ObjectUtils.isEmpty(userInfoReq.getPhotoPath())){
                    if(!ObjectUtils.isEmpty(user.getPhone())){
                        StaffEntity staffEntity = staffService.selectOne(new StaffQuery().phoneNumber(user.getPhone()));
                        if(!ObjectUtils.isEmpty(staffEntity)){
                            staffEntity.setPhotoPath(userInfoReq.getPhotoPath());

                            staffService.update(staffEntity);
                        }else {
                            rest = Rest.fail("请先在后台创建工作人员");
                        }

                    }else {
                        rest = Rest.fail("请先绑定电话");
                    }
                }
                userService.update(user);

            }

        }catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }

        return rest;
    }


}
