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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.artificer.dao.AgencyDao;
import com.sqx.modules.artificer.dao.ArtificerMassageDao;
import com.sqx.modules.artificer.entity.Agency;
import com.sqx.modules.artificer.entity.ArtificerMassage;
import com.sqx.modules.artificer.service.AgencyService;
import com.sqx.modules.artificer.service.ArtificerMassageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantReadWriteLock;


@Service
public class AgencyServiceImpl extends ServiceImpl<AgencyDao, Agency> implements AgencyService {

    @Autowired
    private UserService userService;

    private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true);

    @Override
    public Result insertAgency(Agency agency){
        reentrantReadWriteLock.writeLock().lock();
        try{
            UserEntity userEntity = userService.selectUserById(agency.getUserId());
            if(userEntity.getIsAuthentication()!=null && userEntity.getIsAuthentication()==2){
                return Result.error("您已经是技师了，请不要重复申请");
            }
            Agency agency1 = selectAgencyByUserId(agency.getUserId());
            if(agency1!=null){
                return Result.error("您已经提交过申请了！");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            agency.setStatus(0);
            agency.setCreateTime(sdf.format(new Date()));
            baseMapper.insert(agency);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    public Agency selectAgencyByUserId(Long userId){
        return baseMapper.selectOne(new QueryWrapper<Agency>().eq("user_id",userId));
    }



}