package com.ruoyi.web.controller.login;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.im.util.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.basic.mapper.YjStoreMapper;
import com.ruoyi.basic.service.impl.YjAppUserServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.model.AppLoginUser;
import com.ruoyi.common.core.domain.model.AppUserLoginBody;
import com.ruoyi.common.utils.JpushClientUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.AppLoginService;
import com.ruoyi.basic.domain.YjStore;
import com.ruoyi.basic.service.impl.YjStoreServiceImpl;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.basic.dto.AppLoginUserForGetInfor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "01-登录与验证")
@RestController
@RequestMapping("/api")
public class AppLoginController {

    @Autowired
    private AppLoginService appLoginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private YjAppUserServiceImpl appUserService;

    @Autowired
    private YjStoreMapper storeMapper;
    @Autowired
    private SysPermissionService permissionService;

    /**
     * 注册
     * @param loginBody
     * @return
     */
    @PostMapping("/register")
    public RestResponse register(@RequestBody AppUserLoginBody loginBody){
        appLoginService.validateCaptcha(loginBody.getCode(), loginBody.getUuid());
        if (!loginBody.getPassword().equals(loginBody.getPasswordSecond())){
            throw new  RuntimeException("密码不一致！");
        }
        Long haveUser=appUserService.count(new QueryWrapper<AppUser>().eq("phone_number",loginBody.getPhonenumber()));
       if (haveUser>0){
           throw new  RuntimeException("手机号已被注册！");
       }
        AppUser appUser=new AppUser();
        appUser.setPhoneNumber(loginBody.getPhonenumber());
        appUser.setNickName(loginBody.getPhonenumber());
        appUser.setPassword(SecurityUtils.encryptPassword(loginBody.getPassword()));
        appUser.setStatus(1);
        appUserService.save(appUser);

        return new RestResponse().setSuccess(true).setMessage("注册成功！");
    }

    /**
     * 账号密码注册 手机号+验证码+密码
     * @param loginBody
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody AppUserLoginBody loginBody){
        AjaxResult ajax = AjaxResult.success();
        String token=appLoginService.login(loginBody.getPhonenumber(),loginBody.getPassword(),loginBody.getCode(),loginBody.getUuid(),loginBody.getRegisterId(),loginBody.getMiniAppCode());
        ajax.put(Constants.TOKEN, token);

        //  保存设备id绑定别名，便于推送消息
        if (StrUtil.isNotEmpty(loginBody.getRegisterId())){
            appUserService.update(new UpdateWrapper<AppUser>().eq("phone_number",loginBody.getPhonenumber())
                    .set("register_id",loginBody.getRegisterId())
                    .set(StrUtil.isNotEmpty(loginBody.getLoginSysPlatform()),"login_sys_platform",loginBody.getLoginSysPlatform())
            );
            //  极光推送注册设备id绑定别名，便于推送消息
            JpushClientUtil.bindAlias(loginBody.getRegisterId(),loginBody.getPhonenumber());
        }

        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        AppLoginUser user = SecurityUtils.getAppLoginUser();
        AppLoginUserForGetInfor appUser=
                BeanUtils.copyProperties(user.getAppUser(),AppLoginUserForGetInfor.class);
        appUser.setUserId(user.getAppUserId());
        appUser.setPhonenumber(user.getAppUser().getPhoneNumber());
        // 角色集合
        appUser.setRoleId(user.getRoles());
        //管理人员（教练、店长、顾问）默认访问门店.

//        if (ObjectUtil.isNotEmpty(user.getManageAccountId())&&ObjectUtil.isNotEmpty(appUser.getVisitStore())){
//            Long deptId= userService.selectUserById(user.getManageAccountId()).getDeptId();
//            appUser.setVisitStore(deptId);
//        }
        AjaxResult ajax = AjaxResult.success();

        ajax.put("appLoginUser", appUser);
        ajax.put("visitStore",getIndex(appUser.getVisitStore()));
        return ajax;
    }


    @Resource
    private YjStoreServiceImpl storeService;


    public Map<String,String> getIndex(Long visitStore){
        YjStore yjStore;
        Map m=new HashMap();
        if (ObjectUtil.isNotEmpty(visitStore)){
            yjStore=storeService.getById(visitStore);
        }else {
            yjStore= storeService.list().get(0);
        }
        m.put("address",yjStore.getAddress());
        m.put("storeName",yjStore.getStoreName());
        m.put("phone",yjStore.getPhone());
        m.put("banner",yjStore.getBanner());
        m.put("id",yjStore.getId());
        return  m;
    }



    /**
     * 用户当前经纬度 用来查附近门店
     * @param address（未使用，获取全部门店）
     * @return
     */
    @GetMapping("/getStoreList")
    public AjaxResult getStoreList(String address) {

        AjaxResult ajax = AjaxResult.success();
        List<YjStore> dtoList= storeMapper.getStoreList();
        dtoList.forEach(l->{
            l.setStoreName(l.getStoreName()+"（总店）");
            l.setChildList(storeMapper.getChilds(l.getId()));
        });
        ajax.put("storeList",dtoList);
        return ajax;
    }




}
