package com.sqx.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserCertificationDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserCertification;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserCertificationService;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserCertificationImpl extends ServiceImpl<UserCertificationDao, UserCertification> implements UserCertificationService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private PayDetailsDao payDetailsDao;


    @Override
    public Result insert(Long userId, String name, String idNumber, String front, String back,Integer classify,String phone,String address,Integer sex,String infantImg,String infantImgs,String birthdate,String ordersNo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查询身份证是否被绑定
        UserCertification userCertification = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("id_number", idNumber).eq("status", 1));
        if (userCertification != null) {
            return Result.error("身份证号已经被绑定");
        } else {
            //查询是否实名过
            UserCertification userCertification1 = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId));
            if (userCertification1 == null) {
                //没有实名过
                UserCertification userCertification2 = new UserCertification();
                userCertification2.setUserId(userId);
                userCertification2.setIdNumber(idNumber);
                userCertification2.setName(name);
                userCertification2.setCreateTime(simpleDateFormat.format(new Date()));
                userCertification2.setFront(front);
                userCertification2.setBack(back);
                userCertification2.setStatus((long) 0);
                userCertification2.setUpdateTime(simpleDateFormat.format(new Date()));
                userCertification2.setClassify(classify);
                userCertification2.setPhone(phone);
                userCertification2.setAddress(address);
                userCertification2.setSex(sex);
                userCertification2.setInfantImg(infantImg);
                userCertification2.setInfantImgs(infantImgs);
                userCertification2.setBirthdate(birthdate);
                userCertification2.setOrdersNo(ordersNo);
                baseMapper.insert(userCertification2);
            } else {
                //实名过
                userCertification1.setName(name);
                userCertification1.setIdNumber(idNumber);
                userCertification1.setFront(front);
                userCertification1.setBack(back);
                userCertification1.setStatus((long) 0);
                userCertification1.setUpdateTime(simpleDateFormat.format(new Date()));
                userCertification1.setClassify(classify);
                userCertification1.setPhone(phone);
                userCertification1.setAddress(address);
                userCertification1.setInfantImg(infantImg);
                userCertification1.setInfantImgs(infantImgs);
                userCertification1.setBirthdate(birthdate);
                userCertification1.setOrdersNo(ordersNo);
                baseMapper.updateById(userCertification1);
            }
            UserEntity userEntity = userDao.selectById(userId);
            if(classify==1){
                userEntity.setIsAuthentication(1);
            }else{
                userEntity.setIsAuthentication(4);
            }
            userDao.updateById(userEntity);
            return Result.success();
        }
    }

    @Override
    public Result isInsert(Long userId) {
        UserCertification userCertification = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId).eq("status", 1));
        if (userCertification != null) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    public static Integer getAgeByCertId(String certId) {
        String birthday = "";
        if (certId.length() == 18) {
            birthday = certId.substring(6, 10) + "/"
                    + certId.substring(10, 12) + "/"
                    + certId.substring(12, 14);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date now = new Date();
        Date birth = new Date();
        try {
            birth = sdf.parse(birthday);
        } catch (ParseException e) {
        }
        long intervalMilli = now.getTime() - birth.getTime();
        int age = (int) (intervalMilli/(24 * 60 * 60 * 1000))/365;
        return age;
    }




    @Override
    public Result queryCertification(Long page, Long limit, String status, String name,Integer classify) {

        if (page == null || limit == null) {
            return Result.error("分页参数为空");
        } else {
            IPage<UserCertification> iPage = new Page(page, limit);
            String nname = null;
            if (name != null && !(name.equals(""))) {
                nname = "%" + name + "%";
            }
            IPage iPage1 = baseMapper.queryCertification(iPage, status, nname,classify);
            List<UserCertification> userCertifications = iPage1.getRecords();
            for (UserCertification userCertification : userCertifications) {
                if (userCertification != null) {
                    //关联用户
                    userCertification.setUserEntity(userDao.selectById(userCertification.getUserId()));
                }
            }
            return Result.success().put("data", new PageUtils(iPage1));
        }
    }

    @Override
    public Result queryUserCertification(IPage iPage, String name,String phone) {
        String nname = null;
        if (name != null && !(name.equals(""))) {
            nname = "%" + name + "%";
        }
        String nphone=null;
        if(phone != null && !(phone.equals(""))){
            nphone = "%" + phone + "%";
        }

        return Result.success().put("data", baseMapper.queryUserCertification(iPage, nname,nphone));
    }

    @Override
    public Result auditorUserCertification(Long status, Long id, String remek) {
        UserCertification userCertification = baseMapper.selectById(id);
        if (userCertification != null) {
            if(status==1){
                UserEntity userEntity = userDao.selectById(userCertification.getUserId());
                if(userCertification.getClassify()==1){
                    userEntity.setIsAuthentication(2);
                }else{
                    userEntity.setIsAuthentication(5);
                }
                userDao.updateById(userEntity);
            }else{
                UserEntity userEntity = userDao.selectById(userCertification.getUserId());
                if(userCertification.getClassify()==1){
                    userEntity.setIsAuthentication(3);
                }else{
                    userEntity.setIsAuthentication(6);
                }
                userDao.updateById(userEntity);
                PayDetails payDetails = payDetailsDao.selectByOrderId(userCertification.getOrdersNo());
                userMoneyService.updateMoney(1,userCertification.getUserId(),payDetails.getMoney());
                UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
                userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
                userMoneyDetails.setUserId(userCertification.getUserId());
                //查询用户当前余额
                UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(userCertification.getUserId());
                //插入余额
                userMoneyDetails.setBalance(userNowMoney.getMoney());
                //插入操作类型为已操作用户余额
                userMoneyDetails.setManipulateType(2);
                userMoneyDetails.setContent("实名认证审核失败，资金退还至钱包");
                userMoneyDetails.setTitle("实名认证审核失败");
                userMoneyDetails.setType(1);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }
            userCertification.setStatus(status);
            userCertification.setRemek(remek);
            baseMapper.updateById(userCertification);
            return Result.success();
        } else {
            return Result.error("要审核的信息不存在！");
        }
    }

    @Override
    public Result queryInsert(Long userId,Integer classify) {
        return Result.success().put("data", baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId).eq("classify",classify)));
    }


    @Override
    public Result exitMoney(Long userId){
        UserCertification userCertification = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId));
        if(userCertification==null){
            return Result.error("您还没有提交实名认证信息！");
        }
        if(userCertification.getStatus()!=1){
            return Result.error("您的认证信息未通过！");
        }



        PayDetails payDetails = payDetailsDao.selectByOrderId(userCertification.getOrdersNo());
        userMoneyService.updateMoney(1,userCertification.getUserId(),payDetails.getMoney());

        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
        //查询用户当前余额
        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(userCertification.getUserId());
        //插入余额
        userMoneyDetails.setBalance(userNowMoney.getMoney());
        //插入操作类型为已操作用户余额
        userMoneyDetails.setManipulateType(2);
        userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
        userMoneyDetails.setUserId(userCertification.getUserId());
        userMoneyDetails.setContent("您的实名认证信息已失效，保证金已经退款至您的账户");
        userMoneyDetails.setTitle("退保证金");
        userMoneyDetails.setType(1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);

        baseMapper.deleteById(userCertification.getId());
        UserEntity userEntity = userDao.selectById(userId);
        userEntity.setIsAuthentication(0);
        userDao.updateById(userEntity);

        return Result.success();

    }



}
