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

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.common.utils.SpringContextUtils;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.artificer.service.ArtificerService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.consortia.dao.ConsortiaDao;
import com.sqx.modules.consortia.entity.Consortia;
import com.sqx.modules.consortia.service.ConsortiaService;
import com.sqx.modules.coupon.dao.CouponCardDao;
import com.sqx.modules.coupon.entity.Coupon;
import com.sqx.modules.coupon.entity.CouponCard;
import com.sqx.modules.coupon.entity.CouponCardType;
import com.sqx.modules.coupon.entity.CouponUser;
import com.sqx.modules.coupon.service.CouponCardService;
import com.sqx.modules.coupon.service.CouponCardTypeService;
import com.sqx.modules.coupon.service.CouponService;
import com.sqx.modules.coupon.service.CouponUserService;
import com.sqx.modules.utils.excel.ExcelData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
public class ConsortiaServiceImpl extends ServiceImpl<ConsortiaDao, Consortia> implements ConsortiaService {

    @Autowired
    private UserService userService;
    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private CommonInfoService commonRepository;


    @Override
    public Result insertConsortia(Consortia consortia){
        UserEntity userEntity = userService.selectUserById(consortia.getUserId());
        if(userEntity.getConsortiaId()!=null){
            /*Consortia consortia1 = baseMapper.selectById(userEntity.getConsortiaId());
            if(consortia1!=null && consortia1.getUserId().equals(userEntity.getUserId())){
                baseMapper.updateConsortiaUserIdIsNullByConsortId(consortia1.getConsortiaId());
            }*/
            return Result.error("当前用户已经绑定商家，请移除后操作！");
        }
        consortia.setCreateTime(DateUtils.format(new Date()));
        consortia.setTags(consortia.getTags().replaceAll("，",","));
        baseMapper.insert(consortia);
        userEntity.setConsortiaId(consortia.getConsortiaId());
        userEntity.setIsShop(1);
        userService.updateById(userEntity);
        return Result.success();
    }

    @Override
    public Result updateConsortia(Consortia consortia){
        Consortia oldConsortia = baseMapper.selectById(consortia.getConsortiaId());
        if(consortia.getUserId()!=null &&  !consortia.getUserId().equals(oldConsortia.getUserId())){
            UserEntity user = userService.getById(consortia.getUserId());
            if(user.getConsortiaId()!=null){
                /*Consortia consortia1 = baseMapper.selectById(user.getConsortiaId());
                if(consortia1!=null && consortia1.getUserId().equals(user.getUserId())){
                    baseMapper.updateConsortiaUserIdIsNullByConsortId(consortia1.getConsortiaId());
                }*/
                return Result.error("当前用户已经绑定商家，请移除后操作！");
            }
            user.setConsortiaId(consortia.getConsortiaId());
            user.setIsShop(1);
            consortia.setTags(consortia.getTags().replaceAll("，",","));
            userService.updateById(user);
            userService.update(
                    null,
                    Wrappers.<UserEntity>lambdaUpdate()
                            .set(UserEntity::getIsShop, null)
                            .set(UserEntity::getConsortiaId, null)
                            .eq(UserEntity::getUserId, oldConsortia.getUserId())
            );

        }else{
            consortia.setTags(consortia.getTags().replaceAll("，",","));
        }
        baseMapper.updateById(consortia);
        return Result.success();
    }

    @Override
    public Result deleteConsortiaById(Long consortiaId){
        baseMapper.deleteById(consortiaId);
        userService.updateUserClientIdIsNullByClientId(consortiaId);
        return Result.success();
    }

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

    @Override
    public Result selectConsortiaByUserId(Long consortiaId){
        return Result.success().put("data",baseMapper.selectById(consortiaId));
    }

    @Override
    public Result insertConsortiaUser(Long userId,Long consortiaId){
        UserEntity userEntity = userService.selectUserById(userId);
        userEntity.setConsortiaId(consortiaId);
        userService.updateById(userEntity);
        return Result.success();
    }

    @Override
    public Result deleteConsortiaUser(Long userId){
        userService.updateUserConsortiaIdIsNull(userId);
        return Result.success();
    }

    @Override
    public Result selectUserListByConsortiaId(Integer page,Integer limit,String userName,String phone,Long consortiaId,Long shopId,Integer flag,String time){
        return artificerService.selectUserListByConsortiaId(page, limit, userName, phone, consortiaId,shopId,flag,time);
    }

    @Override
    public Result selectConsortiaMoney(Long shopId,Integer flag,String time){
        return Result.success().put("data",baseMapper.selectConsortiaMoney(shopId, flag, time));
    }

    @Override
    public Result selectConsortiaUserId(Long userId) {
        QueryWrapper<Consortia> query = new QueryWrapper<Consortia>();
        query.eq("user_id", userId);
        query.last("limit 1");
        return Result.success().put("data",baseMapper.selectOne(query));
    }

    @Override
    public Result genOrGetQrCodePath(String id) {
        //去附件里找有没有
        String http = commonRepository.findOne(19).getValue();
        String[] split = http.split("://");
        // 上传文件路径
        String baseAudioUploadPath = "/www/wwwroot/"+split[1]+"/file/uploadPath";

        String baseFilePath = baseAudioUploadPath + "/" + "QrCode" + "/";
        //创建文件
        String filePath = baseFilePath + id + ".jpg";

        File QRCodeFile = FileUtil.file(filePath);
        //判断文件存不存在
        if(!FileUtil.exist(filePath)){
            //生成并保存并返回二维码
            FileUtil.touch(filePath);
            //获取前台地址
            QrCodeUtil.generate(commonRepository.findOne(19).getValue() + "/pages/public/login?bindingConsortiaId=" + id, 300, 300, QRCodeFile);
        }
        //返回可访问地址
        String url = StringUtils.replace(filePath,"/www/wwwroot/"+split[1],http);
        return Result.success().put("imagePath",url);
    }


}
