package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeFans;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.dto.LifeFansFollowOutcome;
import shop.alien.entity.store.vo.LifeUserCancelAccountResultVo;
import shop.alien.entity.store.vo.LifeUserVo;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.store.service.LifeUserService;
import shop.alien.store.util.ali.AliSms;
import shop.alien.util.common.FileUpload;
import shop.alien.util.common.RandomCreateUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户
 */
@Api(tags = {"一期-用户"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class LifeUserController {

    private final LifeUserService lifeUserService;

    private final LifeUserService service;

    private final FileUpload fileUpload;

    private final LifeUserMapper lifeUserMapper;

    private final AliSms aliSms;

    @ApiOperation("查询用户信息")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键id", dataType = "String", paramType = "query", required = true)})
    @GetMapping("/selectUserById")
    public R<LifeUser> selectUserById(@RequestParam("id") String id) {
        log.info("LifeUserController.selectUserById?id={}", id);
        LifeUser lifeUserVo = new LifeUser();
        LifeUser user = lifeUserMapper.selectById(id);
        if (null == user) {
            return R.fail("查询失败");
        }
//        BeanUtils.copyProperties(user, lifeUserVo);
//        // 添加 是否拉黑标识,是否是达人标识
//        //达人标识 0 不是达人 1 是达人
//        LambdaUpdateWrapper<LifeUserExpert> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.eq(LifeUserExpert::getUserId, user.getId());
//        LifeUserExpert lifeUserExpert = lifeUserExpertMapper.selectOne(wrapper);
//        if (null != lifeUserExpert) {
//            lifeUserVo.setIsExpert("1");
//        } else {
//            lifeUserVo.setIsExpert("0");
//        }
        // 被拉黑标识 0 未拉黑 1 已拉黑(待定)

        return R.data(user);
    }

    @ApiOperation("修改用户信息")
    @ApiOperationSupport(order = 3)
    @PostMapping("/modifyUser")
    public R<Boolean> modifyUser(@RequestBody LifeUser user) {
        log.info("LifeUserController.modifyUser?user={}", user.toString());

        int size = lifeUserService.count(new LambdaQueryWrapper<LifeUser>()
                .eq(LifeUser::getIdCard, user.getIdCard())
                .eq(LifeUser::getDeleteFlag, 0));
        if (size > 0) {
            return  R.fail("该证件已被实名");
        }
        boolean isChangeRealInfo = lifeUserService.checkRealInfo(user);
        int num = service.modifyUser(user);
        if (num == 0) {
            return R.fail("修改失败");
        }
        //如果修改实名信息，则发通知
        if (isChangeRealInfo) {
            lifeUserService.sendNotice(user);
        }
        return R.success("修改成功");
    }

    @ApiOperation("关注")
    @ApiOperationSupport(order = 4)
    @PostMapping("/addFans")
    public R<Boolean> addFans(@RequestBody LifeFans fans) {
        log.info("LifeUserController.addFans fans={}", fans == null ? "null" : fans.toString());
        LifeFansFollowOutcome outcome = service.addFans(fans);
        if (!outcome.isOk()) {
            return R.fail(outcome.getMessage());
        }
        return R.success(outcome.getMessage());
    }

    @ApiOperation("取消关注")
    @ApiOperationSupport(order = 5)
    @PostMapping("/cancelFollewed")
    public R<Boolean> cancelFollewed(@RequestBody LifeFans fans) {
        log.info("LifeUserController.cancelFollewed fans={}", fans == null ? "null" : fans.toString());
        LifeFansFollowOutcome outcome = service.cancelFans(fans);
        if (!outcome.isOk()) {
            return R.fail(outcome.getMessage());
        }
        return R.success(outcome.getMessage());
    }

    @ApiOperation("搜索商家或用户")
    @ApiOperationSupport(order = 6)
    @PostMapping("/getStoreAndUserByName")
    public R<IPage<LifeUserVo>> getStoreAndUserByName(@RequestBody LifeUserVo vo) {
        log.info("LifeUserController.getStoreAndUserByName?vo={}", vo.toString());
        return R.data(service.getStoreAndUserByName(vo));
    }

    @GetMapping("/getUserById")
    public LifeUser getUserById(@RequestParam("id") String id) {
        log.info("LifeUserController.getUserById?id={}", id);
        return service.getUserById(id);
    }

    @PostMapping("/addUser")
    public int addOrUpdateUser(LifeUser user, @RequestParam(value = "image", required = false) MultipartFile image) throws Exception {
        log.info("LifeUserController.addOrUpdateUser?user={}&image={}", user.toString(), image.getOriginalFilename());
        String path = "";
        if (!StringUtils.isEmpty(image.getOriginalFilename())) {
            path = fileUpload.saveImage(image);
        }
        // 设置图片路径
        user.setUserImage(path);
        //邀请码

        user.setInvitedNum(RandomCreateUtil.getRandomNStr(20));
        return service.addOrUpdateUser(user);
    }

    @GetMapping("/getUserPage")
    public Map<String, Object> getStoresPage(@RequestParam(defaultValue = "1") int page,
                                             @RequestParam(defaultValue = "10") int size,
                                             @RequestParam(required = false) String realName,
                                             @RequestParam(required = false) String userPhone) {
        log.info("LifeUserController.getStoresPage?page={},size={},realName={},userPhone={}", page, size, realName, userPhone);
        IPage<LifeUser> stores = service.getStoresPage(page, size, realName, userPhone);
        Map<String, Object> response = new HashMap<>();
        response.put("data", stores.getRecords());
        response.put("total", stores.getRecords().size());
        response.put("current", stores.getCurrent());
        response.put("size", stores.getSize());
        return response;
    }

    /**
     * 用户端注销用户
     */
    @ApiOperation("用户端注销用户")
    @PostMapping("/liftCancelAccount")
    public R<LifeUserCancelAccountResultVo> liftCancelAccount(@RequestBody LifeUserVo user) {
        log.info("LifeUserController.liftCancelAccount?LifeUserVo={}", user);
        if (user.getId() == null) {
            return cancelAccountFail(LifeUserCancelAccountResultVo.STATUS_BUSINESS, "用户id不能为空");
        }
        LifeUser lifeUser = lifeUserMapper.selectById(user.getId());
        if (lifeUser == null) {
            return cancelAccountFail(LifeUserCancelAccountResultVo.STATUS_BUSINESS, "用户不存在");
        }
        if (lifeUser.getLogoutFlag() != null
                && (lifeUser.getLogoutFlag() == LifeUser.LOGOUT_FLAG_DONE
                || lifeUser.getLogoutFlag() == LifeUser.LOGOUT_FLAG_COOLING)) {
            return cancelAccountFail(LifeUserCancelAccountResultVo.STATUS_BUSINESS, "账号已在注销中");
        }
        if (!StringUtils.hasText(lifeUser.getUserPhone())) {
            return cancelAccountFail(LifeUserCancelAccountResultVo.STATUS_BUSINESS, "用户手机号不存在");
        }
        if (!StringUtils.hasText(user.getVerificationCode())) {
            return cancelAccountFail(LifeUserCancelAccountResultVo.STATUS_SMS_ERROR, "验证码不能为空");
        }
        int code;
        try {
            code = Integer.parseInt(user.getVerificationCode().trim());
        } catch (NumberFormatException e) {
            return cancelAccountFail(LifeUserCancelAccountResultVo.STATUS_SMS_ERROR, "验证码格式错误");
        }
        if (!aliSms.checkSmsCode(lifeUser.getUserPhone(), 0, 5, code)) {
            return cancelAccountFail(LifeUserCancelAccountResultVo.STATUS_SMS_ERROR, "验证码错误或已过期");
        }
        try {
            service.liftCancelAccount(user);
        } catch (IllegalArgumentException e) {
            return cancelAccountFail(LifeUserCancelAccountResultVo.STATUS_BUSINESS, e.getMessage());
        }
        return cancelAccountSuccess("注销成功");
    }

    private R<LifeUserCancelAccountResultVo> cancelAccountSuccess(String message) {
        LifeUserCancelAccountResultVo body = LifeUserCancelAccountResultVo.of(
                LifeUserCancelAccountResultVo.STATUS_SUCCESS, message);
        return R.data(body, message);
    }

    private R<LifeUserCancelAccountResultVo> cancelAccountFail(int status, String message) {
        LifeUserCancelAccountResultVo body = LifeUserCancelAccountResultVo.of(status, message);
        R<LifeUserCancelAccountResultVo> result = R.data(body, message);
        result.setSuccess(false);
        return result;
    }

    /**
     * 用户端撤回注销用户
     */
    @ApiOperation("用户端撤回注销用户")
    @PostMapping("/liftCancelAccountUn")
    public R<Boolean> liftCancelAccountUn(@RequestBody LifeUser user) {
        log.info("LifeUserController.liftCancelAccountUn?LifeUser={}", user);
        if (user == null || user.getId() == null) {
            return R.fail("用户id不能为空");
        }
        try {
            service.liftCancelAccountUn(user.getId());
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        }
        return R.success("撤回注销成功");
    }

    @GetMapping("/getUserByPhone")
    public R<LifeUser> getUserByPhone(@RequestParam("phone") String phone) {
        log.info("LifeUserController.getUserByPhone?phone={}", phone);
        return R.data(service.getUserByPhone(phone));
    }

    //查询用户弹窗状态
    @GetMapping("/getUserByIsPopup")
    public R<Boolean> getUserByIsPopup(@RequestParam("id") String id) {
        log.info("LifeUserController.getUserByIsPopup?userId={}", id);
        LifeUser user = lifeUserMapper.selectById(id);
        if (user == null){
            return R.fail("用户不存在");
        }
        if (user.getIsPopup() == 1){
            return R.data(false);
        }
        return R.data(true);
    }

    //保存用户弹窗状态
    @GetMapping("/saveUserByIsPopup")
    public R<Boolean> saveUserByIsPopup(@RequestParam("id") String id, @RequestParam("isPopup") int isPopup) {
        log.info("LifeUserController.getUserByIsPopup?userId={}", id);
        LifeUser user = lifeUserMapper.selectById(id);
        if (user == null){
            return R.fail("用户不存在");
        }
        user.setIsPopup(isPopup);
        // 更新用户弹窗状态
        int a =lifeUserMapper.updateById(user);
        if (a <= 0){
            return R.fail("更新用户弹窗状态失败");
        }
        return R.data(true);
    }

    @ApiOperation("统计用户设备数")
    @ApiOperationSupport(order = 7)
    @GetMapping("/countUserDeviceNum")
    public R<Long> countUserDeviceNum() {
        log.info("LifeUserController.countUserDeviceNum");
        return R.data(lifeUserService.countUserDeviceNum());
    }


}
