package com.ylx.address.controller;

import com.alibaba.fastjson.JSON;
import com.ylx.common.core.domain.R;
import com.ylx.common.core.domain.model.aliyun.SMSVerificationCode;
import com.ylx.common.core.domain.model.aliyun.SendSmsComponents;
import com.ylx.common.core.domain.model.aliyun.SendSmsEnum;
import com.ylx.common.utils.StringUtils;
import com.ylx.massage.domain.vo.Result;
import com.ylx.address.service.TAddressService;
import com.ylx.address.domain.dto.UserAddressAddDto;
import com.ylx.address.domain.dto.UserAddressDeleteDto;
import com.ylx.address.domain.dto.UserAddressDto;
import com.ylx.address.domain.dto.UserAddressUpdateDto;
import com.ylx.address.domain.vo.UserAddressVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 类描述：
 *
 * @author Administrator
 * @version 1.0
 * @date 2026/6/5 17:54
 */
@RestController
@RequestMapping("/user/address")
@Api(tags = {"用户端地址管理"})
@Slf4j
public class UserAddressController {
    public static final String PHONE_USER_ADDRESS_CODE_KEY = "user:address:phon:";
    @Value("${codeSwitch}")
    private Boolean codeSwitch;
    @Resource
    private TAddressService tAddressService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SendSmsComponents sendSms;
    /**
     * 用户地址列表查询
     *
     * @return
     */
    @ApiOperation(value="用户地址列表查询", notes="用户地址列表查询")
    @PostMapping(value = "/getUserAddress")
    public R<List<UserAddressVo>> getUserAddress(@Validated @RequestBody UserAddressDto dto) {
        return R.ok(tAddressService.getByOpenIdList(dto));
    }

    /**
     * 用户地址新增
     *
     * @return
     */
    @ApiOperation(value="新增用户地址", notes="新增用户地址")
    @PostMapping(value = "/addUserAddress")
    public R<?> addUserAddress(@Validated @RequestBody UserAddressAddDto dto) {
        if (codeSwitch) {
            // 短信验证
            String msg = redisTemplate.opsForValue().get(PHONE_USER_ADDRESS_CODE_KEY + dto.getPhone());
            if (StringUtils.isEmpty(msg)) {
                return R.fail("验证码已失效");
            }

            if (!dto.getPhoneMsg().equals(msg)) {
                return R.fail("短信验证码不正确");
            }
        }
        tAddressService.addUserAddress(dto);
        return R.ok();
    }

    /**
     * 用户地址编辑
     *
     * @return
     */
    @ApiOperation(value="用户地址编辑", notes="用户地址编辑")
    @PostMapping(value = "/updateUserAddress")
    public R<?> updateUserAddress(@Validated @RequestBody UserAddressUpdateDto dto) {
        if (codeSwitch) {
            // 短信验证
            String msg = redisTemplate.opsForValue().get(PHONE_USER_ADDRESS_CODE_KEY + dto.getPhone());
            if (StringUtils.isEmpty(msg)) {
                return R.fail("验证码已失效");
            }

            if (!dto.getPhoneMsg().equals(msg)) {
                return R.fail("短信验证码不正确");
            }
        }
        tAddressService.updateUserAddress(dto);
        return R.ok();
    }

    /**
     * 用户地址删除
     *
     * @return
     */
    @ApiOperation(value="用户地址删除", notes="用户地址删除")
    @PostMapping(value = "/deleteUserAddress")
    public R<?> deleteUserAddress(@Validated @RequestBody UserAddressDeleteDto dto) {
        tAddressService.deleteUserAddress(dto);
        return R.ok();
    }

    /**
     * 用户地址新增或者编辑时获取验证码
     * @param phone
     * @param request
     * @return
     */
    @GetMapping("/sendMsg")
    @ApiOperation(value = "短信发送", notes = "短信发送")
    public Result sendMsg(@RequestParam String phone, HttpServletRequest request) {
        if (StringUtils.isEmpty(phone)) {
            return Result.error("手机号不能为空");
        }
        Random rand = new Random();
        // randNumber 将被赋值为一个 MIN 和 MAX 范围内的随机数
        int randNumber = rand.nextInt(9999 - 1000 + 1) + 1000;
        // 保存验证码到redis
        redisTemplate.opsForValue()
                .set(PHONE_USER_ADDRESS_CODE_KEY + phone, String.valueOf(randNumber), 5L
                        , TimeUnit.MINUTES);
        try {
            SMSVerificationCode smsVerificationCode = new SMSVerificationCode(String.valueOf(randNumber));
            String jsonString = JSON.toJSONString(smsVerificationCode);
            sendSms.sendSms(phone, SendSmsEnum.SMS_220650024, jsonString);
            return Result.ok("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("发送失败");
    }

}