package com.gyt.shr.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gyt.shr.config.settingConfig.AppValidationConfig;
import com.gyt.shr.entity.CodeRecord;
import com.gyt.shr.entity.Person;
import com.gyt.shr.mapper.CodeRecordMapper;
import com.gyt.shr.mapper.PersonMapper;
import com.gyt.shr.service.PersonService;
import com.gyt.shr.util.CreateIdUtil;
import com.gyt.shr.result.Result;
import com.gyt.shr.util.CharUtil;
import com.gyt.shr.util.SendMsgUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.gyt.shr.constant.GlobalConstant.NORMAL_USER_LOGIN_STATUS;

/**
* @author coyle
*/
@Service
@Slf4j
public class  PersonServiceImpl   extends ServiceImpl<PersonMapper, Person>  implements PersonService {
    
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private CodeRecordMapper codeRecordMapper;
    @Autowired
    private CharUtil charUtil;
    @Autowired
    private AppValidationConfig appValidationConfig;
    @Autowired
    private SendMsgUtils sendMsgUtils;


    /**
     * 根据手机号码查询是否存在用户
     * @param phone
     * @return
     */
    @Override
    public Result<Person> checkPersonByPhone(String phone) {
        Result<String> result = charUtil.phoneCheck(phone);
        if (result.getCode() == -1) {
            return Result.error(result.getCode(), result.getMsg());
        }
        // 检查 phone 参数的值
        log.debug("请求的手机号码为: {}", phone);
        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fncell", phone);
        final Person normalUser = personMapper.selectOne(queryWrapper);

        if (normalUser == null) {
            log.debug("账号不存在:{}", phone);
            return Result.error(-1, "账户不存在！");
        }
        //查询是否有未过期的验证码
        QueryWrapper<CodeRecord> codeRecordQueryWrapper = new QueryWrapper<>();
        codeRecordQueryWrapper.eq("fnumber", phone);
//        codeRecordQueryWrapper.eq("cfisvalid", true);
        codeRecordQueryWrapper.gt("cfexpiresTime", new Date());
        List<CodeRecord> codeRecords = codeRecordMapper.selectList(codeRecordQueryWrapper);
        if (codeRecords.size() > 0) {
            return Result.error(-1, "验证码仍在有效期内！");
        }

        //验证码过期，重新生成验证码
//        try {
            //生成验证码
            String verifyCode = CharUtil.randomVerify();
            //发送验证码
            boolean isSend = true;
//            boolean isSend = sendMsgUtils.sendCodeToPhone(phone, verifyCode);
            //保存验证码到数据库
            CodeRecord codeRecord = new CodeRecord();
            String fid = CreateIdUtil.createID("252515B0");
            codeRecord.setFid(fid);
            codeRecord.setCode(verifyCode);
            codeRecord.setSend(isSend);
//        codeRecord.setIsvalid(true);
            codeRecord.setIdCardNo(normalUser.getIdCardNo());
            codeRecord.setPid(normalUser.getFid());
            codeRecord.setFname(normalUser.getPname());
            codeRecord.setFnumber(normalUser.getNcell());
            codeRecord.setCreateTime(new Date());
            Date expiresTime = new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(appValidationConfig.getExpireTime().getLength()));
            codeRecord.setExpiresTime(expiresTime);
            //保存验证码到数据库
            codeRecordMapper.insert(codeRecord);

//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        return Result.success(normalUser);
    }




    public Result<Integer> personLogin(String username, String password, HttpServletRequest request) {
        Result<String> result=charUtil.loginInfoCheck(username, password);
        if(result.getCode()==-1){
            return Result.error(result.getCode(), result.getMsg());
        }
        return null;
    }


    public Result<Integer> userLogout(HttpServletRequest request) {
        // 1. 移除会话中的管理员登录状态信息
        request.getSession().removeAttribute(NORMAL_USER_LOGIN_STATUS);
        // 2. 登出成功，返回成功信息
        return  Result.success(200);
    }


}




