package com.liquidnet.service.platform.service.impl.partner;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.dao.ChildDetailsDao;
import com.liquidnet.service.kylin.dao.ChildListDao;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinCheckUserVo;
import com.liquidnet.service.kylin.entity.KylinCheckUser;
import com.liquidnet.service.kylin.mapper.KylinCheckUserMapper;
import com.liquidnet.service.kylin.service.partner.IKylinCheckUserPartnerService;
import com.liquidnet.service.platform.utils.DataUtils;
import com.liquidnet.service.platform.utils.ObjectUtil;
import com.mongodb.BasicDBObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 验票用户表 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-21
 */
@Service
public class KylinCheckUserPartnerServiceImpl extends ServiceImpl<KylinCheckUserMapper, KylinCheckUser> implements IKylinCheckUserPartnerService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoConverter mongoConverter;
    @Autowired
    private DataUtils dataUtils;
    @Autowired
    private KylinCheckUserMapper checkUserMapper;

    @Override
    public PageInfo<ChildListDao> getCheckUserList(String merchantId, String mobile, int page, int size) {
        PageInfo<ChildListDao> pageInfo = null;
        try {
            PageHelper.startPage(page, size);
            List<ChildListDao> data = checkUserMapper.childSimpleList(merchantId, mobile);
            pageInfo = new PageInfo(data);
            return pageInfo;
        } catch (Exception e) {
            return pageInfo;
        }
    }

    @Override
    public ResponseDto<String> del(String merchantId, String checkUserId) {
        try {
            KylinCheckUser checkUser = KylinCheckUser.getNew();
            checkUser.setUpdatedAt(LocalDateTime.now());
            checkUser.setStatus(0);
            checkUserMapper.update(checkUser, Wrappers.lambdaUpdate(KylinCheckUser.class).eq(KylinCheckUser::getCheckUserId, checkUserId));
            dataUtils.delCheckUserRedis(checkUserId);

            HashMap<String, Object> map = ObjectUtil.cloneHashMapStringAndObject();
            map.put("status", 0);
            mongoTemplate.remove(Query.query(Criteria.where("checkUserId").is(checkUserId)), KylinCheckUserVo.class, KylinCheckUserVo.class.getSimpleName());
            return ResponseDto.success("删除成功");
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20102));
        }
    }

    @Override
    public ResponseDto<String> create(String merchantId, String name, String pwd, String mobile) {
        try {

            int count = checkUserMapper.selectCount(Wrappers.lambdaQuery(KylinCheckUser.class).eq(KylinCheckUser::getMobile,mobile).eq(KylinCheckUser::getStatus,1));
            if(count>0){
                return ResponseDto.failure("手机号已存在");
            }

            KylinCheckUser checkUser = KylinCheckUser.getNew();
            checkUser.setName(name);
            checkUser.setPwd(DigestUtils.md5DigestAsHex(pwd.getBytes()));
            checkUser.setMobile(mobile);
            checkUser.setCheckUserId(IDGenerator.nextSnowId());
            checkUser.setCreatedAt(LocalDateTime.now());
            checkUser.setMerchantId(merchantId);
            checkUser.setStatus(1);
            checkUserMapper.insert(checkUser);

            KylinCheckUserVo kylinCheckUserVo = KylinCheckUserVo.getNew();
            BeanUtils.copyProperties(checkUser, kylinCheckUserVo);
            mongoTemplate.insert(kylinCheckUserVo, KylinCheckUserVo.class.getSimpleName());

            return ResponseDto.success("添加成功");
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20101));
        }
    }

    @Override
    public ResponseDto<String> change(String merchantId, String checkUserId, String name, String pwd, String mobile) {
        try {
            KylinCheckUser kylinCheckUser = checkUserMapper.selectOne(Wrappers.lambdaQuery(KylinCheckUser.class).eq(KylinCheckUser::getMobile,mobile).eq(KylinCheckUser::getStatus,1));
            if(kylinCheckUser!=null && !kylinCheckUser.getCheckUserId().equals(checkUserId)){
                return ResponseDto.failure("手机号已存在");
            }

            KylinCheckUser checkUser = KylinCheckUser.getNew();
            checkUser.setName(name);
            if (null != pwd) {
                checkUser.setPwd(DigestUtils.md5DigestAsHex(pwd.getBytes()));
            }
            checkUser.setMobile(mobile);
            checkUser.setUpdatedAt(LocalDateTime.now());
            checkUserMapper.update(checkUser, Wrappers.lambdaUpdate(KylinCheckUser.class).eq(KylinCheckUser::getCheckUserId, checkUserId).eq(KylinCheckUser::getMerchantId, merchantId));
            BasicDBObject obj = ObjectUtil.cloneBasicDBObject().append("$set", mongoConverter.convertToMongoType(checkUser));
            mongoTemplate.getCollection(KylinCheckUserVo.class.getSimpleName()).updateOne(
                    Query.query(Criteria.where("checkUserId").is(checkUserId)).getQueryObject(),
                    obj
            );
            dataUtils.delCheckUserRedis(checkUserId);
            return ResponseDto.success("修改成功");
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20103));
        }
    }

    @Override
    public ResponseDto<ChildDetailsDao> details(String merchantId, String checkUserId) {
        try {
            ChildDetailsDao data = checkUserMapper.childDetails(merchantId, checkUserId);
            return ResponseDto.success(data);
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20104));
        }
    }
}
