package com.iformall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxAppinfo;
import com.iformall.domain.po.WxMerchantBUser;
import com.iformall.domain.po.WxMsgValidationcode;
import com.iformall.enums.EnumMerchantBUserStatus;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxAppinfoMapper;
import com.iformall.mapper.WxMerchantBUserMapper;
import com.iformall.mapper.WxMsgValidationcodeMapper;
import com.iformall.service.WxMerchantBUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gongbiao
 */
@Service
public class WxMerchantBUserServiceImpl implements WxMerchantBUserService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxAppinfoMapper wxAppinfoMapper;

    @Autowired
    WxMerchantBUserMapper wxMerchantBUserMapper;

    @Autowired
    WxMsgValidationcodeMapper wxMsgValidationcodeMapper;

    @Override
    public PageInfo<WxMerchantBUser> listAsPage(WxMerchantBUser record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxMerchantBUserMapper.findList(record));
    }

    @Override
    public WxMerchantBUser getById(Long id) {
        return wxMerchantBUserMapper.selectById(id);
    }

    @Override
    public WxMerchantBUser getBUserByAppId(WxMerchantBUser record) {
        List<WxMerchantBUser> userList = wxMerchantBUserMapper.findList(record);
        if (userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public WxMerchantBUser getByToken(String token) {
        return wxMerchantBUserMapper.findByToken(token);
    }

    @Override
    public Long saveOrUpdate(WxMerchantBUser record) {
        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            long id = idWorker.nextId();
            record.setId(id);
            Date date = new Date();
            record.setCreateDate(date);
            record.setUpdateDate(date);
            wxMerchantBUserMapper.insert(record);
            return id;
        } else {
            Date date = new Date();
            record.setUpdateDate(date);
            wxMerchantBUserMapper.updateById(record);
            return record.getId();
        }
    }

    @Override
    public void deleteById(Long id) {
        wxMerchantBUserMapper.deleteById(id);
    }

    @Override
    public boolean hasphone(String phone, String tenantId) {
        WxMerchantBUser bUser = new WxMerchantBUser();
        bUser.setTenantId(tenantId);
        bUser.setPhone(phone);
        bUser.setStatus(EnumMerchantBUserStatus.VALID.getCode());
        List<WxMerchantBUser> list = wxMerchantBUserMapper.findList(bUser);
        return list.size() >= 1 ? true : false;
    }

    @Override
    public ResultData updatepwd(String appId, String phone, String code, String pwd) {
        WxAppinfo appinfo = wxAppinfoMapper.findByAppId(appId);
        WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode();
        wxMsgValidationcode.setTenantId(appinfo.getTenantId());
        wxMsgValidationcode.setPhone(phone);
        wxMsgValidationcode.setCode(code);
        List<WxMsgValidationcode> wxmsgvalidationcodelist = wxMsgValidationcodeMapper.findList(wxMsgValidationcode);
        Date currentdate = new Date();
        wxmsgvalidationcodelist = wxmsgvalidationcodelist.stream().filter(validationcode ->
                validationcode.getExpiretime().after(currentdate)).collect(Collectors.toList());
        if (wxmsgvalidationcodelist.size() > 0) {
            //更新
            WxMerchantBUser bUser = new WxMerchantBUser();
            bUser.setTenantId(appinfo.getTenantId());
            bUser.setPhone(phone);
            bUser.setAppId(appId);
            bUser.setStatus(EnumMerchantBUserStatus.VALID.getCode());
            List<WxMerchantBUser> list = wxMerchantBUserMapper.findList(bUser);
            if (list.size() > 0) {
                bUser = list.get(0);
                bUser.setUserPwd(pwd);
                try {
                    wxMerchantBUserMapper.updateById(bUser);
                } catch (Exception e) {
                    logger.error("db failed: 商户-" + bUser.getId() + ", e:" + e.getMessage());
                    throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
                }
            } else {
                logger.error("B端用户不是这个app的用户：" + appId);
                throw new MallinkException(ErrorCode.BUSER_NOT_IN_APP);
            }
        }
        return new ResultData();
    }


}
