package com.sqx.modules.artificer.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.UserMoneyDao;
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.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.artificer.dao.OrdersDao;
import com.sqx.modules.artificer.dao.RealNameDao;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.entity.Certification;
import com.sqx.modules.artificer.service.ArtificerService;
import com.sqx.modules.artificer.service.RealNameService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.sys.entity.SysDictEntity;
import com.sqx.modules.sys.service.SysDictService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
public class RealNameServiceImpl extends ServiceImpl<RealNameDao, Certification> implements RealNameService {

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private UserService userService;
    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private SysDictService sysDictService;

    private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true);

    @Override
    public Result selectRealName(Long userId) {
        Certification certification = baseMapper.selectOne(new QueryWrapper<Certification>().eq("user_id", userId).orderByDesc("update_time").last("limit 1"));
        return Result.success().put("data", certification);
    }

    @Override
    public Result updateRealName(Certification certification) {

        UserEntity user = userService.getById(certification.getUserId());
        /*CommonInfo one = commonInfoService.findOne(240);
        if("是".equals(one.getValue())) {
            //判断身份证是否合法
            String result = VerifyIdCardUtils.verifyIdCard(certification.getIdNumber(), certification.getName());
            if("ok".equals(result)){
                certification.setStatus(1);
                certification.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                user.setIsAuthentication(2);
                Artificer artificer = artificerService.selectArtificerByUserId(user.getUserId());
                artificer.setStatus(2);
                artificer.setArtificerName(certification.getName());
                artificer.setArtificerImg(certification.getAvatar());
                artificer.setLifePhoto(certification.getImagePhoto());
                artificer.setCertificate(certification.getCertification());
                artificer.setContent(certification.getIndividualResume());
                artificerService.updateById(artificer);
            }else{
                return Result.error("您填写的信息有误，请检查后重试！");
            }
        }else {
            user.setIsAuthentication(1);
            certification.setStatus(0);
            certification.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }*/
        user.setIsAuthentication(1);
        certification.setStatus(0);
        certification.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        userService.updateById(user);
        if(certification.getId()!=null){
            baseMapper.updateById(certification);
        }else{
            certification.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            baseMapper.delete(new QueryWrapper<Certification>().eq("user_id",certification.getUserId()));
            baseMapper.insert(certification);
        }
        return Result.success();
    }

    @Override
    public Result selectRealNameList(Integer page, Integer limit, Integer status, String userName, String phone,Long classifyId) {
        Page<Certification> pages = new Page<>(page, limit);
        IPage<Certification> certificationIPage = baseMapper.selectPage(pages, new QueryWrapper<Certification>()
                .eq(status != null, "status", status)
                .eq(StringUtils.isNotEmpty(userName), "name", userName)
                .eq(classifyId != null, "classify_id", classifyId)
                .eq(StringUtils.isNotEmpty(phone), "phone", phone).orderByDesc("create_time"));
        List<Certification> records = certificationIPage.getRecords();
        for (Certification certification:records){
            if(certification.getClassifyId()!=null){
                SysDictEntity sysDictEntity = sysDictService.getById(certification.getClassifyId());
                if(sysDictEntity!=null){
                    certification.setClassifyName(sysDictEntity.getValue());
                }
            }
        }
        PageUtils pageUtils = new PageUtils(certificationIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result auditRealName(Certification certification) {
        baseMapper.updateById(certification);
        Certification certification1 = baseMapper.selectById(certification.getId());
        if(certification.getStatus()==1){
            Artificer artificer = artificerService.selectArtificerByUserId(certification1.getUserId());
            if(artificer==null){
                artificer=new Artificer();
            }else {
                return  Result.error("该技师已存在");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            artificer.setUserId(certification1.getUserId());
            artificer.setCreateTime(sdf.format(new Date()));
            artificer.setArtificerSales(0);
            artificer.setStatus(2);
            artificer.setArtificerName(certification1.getName());
            artificer.setArtificerImg(certification1.getAvatar());
            artificer.setLifePhoto(certification1.getImagePhoto());
            artificer.setCertificate(certification1.getCertification());
            artificer.setContent(certification1.getIndividualResume());
            artificer.setClassifyId(certification1.getClassifyId());
            artificer.setCreditScore(BigDecimal.valueOf(100));
            artificer.setTripWay(1);
            if(artificer.getArtificerId()!=null){
                artificerService.updateById(artificer);
            }else{
                artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
                artificerService.save(artificer);
            }

            UserEntity userEntity = userService.selectUserById(artificer.getUserId());
            userEntity.setIsAuthentication(2);
            userService.updateById(userEntity);
        }else{
            UserEntity userEntity = userService.selectUserById(certification1.getUserId());
            userEntity.setIsAuthentication(3);
            userService.updateById(userEntity);
        }
        return Result.success();
    }

    @Override
    public Result selectRealNameById(Long userId) {
        Certification certification = baseMapper.selectOne(new QueryWrapper<Certification>().eq("user_id", userId).orderByDesc("update_time").last("limit 1"));
        return Result.success().put("data", certification);
    }

    @Override
    public Result retreatCashDeposit(Long userId) {
        UserEntity userEntity = userService.selectUserById(userId);
        if(userEntity.getIsCashDeposit()==null || userEntity.getIsCashDeposit()==1){
            return Result.error("保证金未缴纳！");
        }else if(userEntity.getIsCashDeposit()==2){
            //判断有没有进行中的订单
            Artificer artificer = artificerService.selectArtificerByUserId(userId);
            int i = ordersDao.selectOrdersCountByUnderway(artificer.getArtificerId());
            if(i>0){
                return Result.error("当前还有未完成的订单，请完成后再进行退款！");
            }

            UserMoney userMoney = userMoneyDao.selectOne(new QueryWrapper<UserMoney>().eq("user_id", userId));
            userMoneyDao.updateCashDeposit(2, userId, userMoney.getCashDeposit().doubleValue());
            userMoneyDao.updateMayMoney(1, userId, userMoney.getCashDeposit().doubleValue());
            UserMoneyDetails userMoneyDetails =new UserMoneyDetails();
            userMoneyDetails.setMoney(userMoney.getCashDeposit());
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("保证金退款成功,资金已到您的钱包！");
            userMoneyDetails.setTitle("保证金退款");
            userMoneyDetails.setType(1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(new Date());
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsService.save(userMoneyDetails);

            userMoneyDetails=new UserMoneyDetails();
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setTitle("保证金退款");
            userMoneyDetails.setContent("保证金退款成功,资金已到您的钱包！");
            userMoneyDetails.setType(2);
            userMoneyDetails.setMoney(userMoney.getCashDeposit());
            userMoneyDetails.setState(2);
            userMoneyDetails.setClassify(1);
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsService.save(userMoneyDetails);
            userEntity.setIsCashDeposit(1);
            artificer.setStatus(2);
            artificerService.updateById(artificer);
            userService.updateById(userEntity);
            return Result.success();
        }
        return Result.error("保证金申请退款中！");
    }

    @Override
    public Result auditRefund(Long userId, Integer type) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            UserEntity userEntity = userService.selectUserById(userId);
            if(userEntity.getIsCashDeposit()!=3){
                return Result.error("保证金已退款或未申请，请刷新后重试！");
            }
            if(type==1){
                UserMoney userMoney = userMoneyDao.selectOne(new QueryWrapper<UserMoney>().eq("user_id", userId));
                userMoneyDao.updateCashDeposit(2, userId, userMoney.getCashDeposit().doubleValue());
                userMoneyDao.updateMayMoney(1, userId, userMoney.getCashDeposit().doubleValue());
                userEntity.setIsCashDeposit(1);
                Artificer artificer = artificerService.selectArtificerByUserId(userId);
                artificer.setStatus(2);
                artificerService.updateById(artificer);
            }else{
                userEntity.setIsCashDeposit(2);
            }
            userService.updateById(userEntity);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            log.error("保证金退还异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请刷新后重试！");
    }

    @Override
    public Result selectRefundCashDepositList(Integer page,Integer limit,String userName,String phone){
        Page<Map<String,Object>> pages=new Page<>(page,limit);
        return Result.success().put("data",new PageUtils(baseMapper.selectRefundCashDepositList(pages,userName,phone)));
    }


}
