package com.gic.haoban.manage.service.service.out.impl;

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
import com.gic.haoban.manage.api.dto.OpenStaffDTO;
import com.gic.haoban.manage.api.qdto.OpenStaffInitQDTO;
import com.gic.haoban.manage.api.service.OpenStaffApiService;
import com.gic.haoban.manage.service.dao.mapper.OpenStaffMapper;
import com.gic.haoban.manage.service.entity.TabOpenStaff;
import com.gic.haoban.manage.service.pojo.QwOpenResultInitBO;
import com.gic.haoban.manage.service.service.OpenStaffService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.util.OpenUtils;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 企微托管账号
 */
@Service("openStaffApiService")
public class OpenStaffApiServiceImpl implements OpenStaffApiService {

    private static final Logger log = LogManager.getLogger(OpenStaffApiService.class);

    @Autowired
    private OpenStaffMapper openStaffMapper ;
    @Autowired
    private OpenStaffService openStaffService ;
    @Autowired
    private WxEnterpriseService wxEnterpriseService ;

    @Override
    public ServiceResponse<Void> delete(Long id) {
        this.openStaffMapper.deleteByPrimaryKey(id) ;
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> updateValiFlag(String uuid) {
        this.openStaffMapper.updateValiFlag(uuid) ;
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> updateLoginStatus(String uuid, int loginStatus) {
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> login(String uuid, Long qwCorpId, String corpName, Long qwUserId) {
        TabOpenStaff openStaff = this.openStaffMapper.getByUUID(uuid) ;
        if(null == openStaff) {
            log.info("通过uuid查不到={}",uuid);
            OpenUtils.logout(uuid);
            return ServiceResponse.failure("9999","登录错误") ;
        }
        String wxEnterpriseId = openStaff.getWxEnterpriseId() ;
        String backWxEnterpriseId = this.wxEnterpriseService.getWxEnterpriseIdByName(corpName) ;
        if(StringUtils.isBlank(backWxEnterpriseId) || !backWxEnterpriseId.equals(wxEnterpriseId)) {
            OpenUtils.logout(uuid);
            log.info("登录的企业不对={},{}",uuid,corpName);
            return ServiceResponse.failure("9999","登录错误") ;
        }
        openStaff.setWxCorpId(qwCorpId);
        openStaff.setQwUserId(qwUserId);
        if(null == openStaff.getFirstAuthTime()) {
            openStaff.setFirstAuthTime(new Date());
        }
        openStaff.setAuthTime(new Date());
        openStaff.setStatusFlag(1);
        this.openStaffMapper.update(openStaff);
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> logout(String uuid) {
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<OpenStaffDTO> getById(Long openStaffId) {
        TabOpenStaff openStaff = this.openStaffMapper.getById(openStaffId) ;
        if(null == openStaff) {
            return ServiceResponse.failure("9999","已删除")  ;
        }
        OpenStaffDTO dto = EntityUtil.changeEntityByJSON(OpenStaffDTO.class,openStaff) ;
        return ServiceResponse.success(dto);
    }

    @Override
    public ServiceResponse<Long> init(OpenStaffInitQDTO qdto) {
        String staffId = qdto.getStaffId();
        if(StringUtils.isBlank(staffId)) {
            log.info("staffId is null");
            return ServiceResponse.failure("9999","staffId为空") ;
        }
        String lockKey = "lock:qywx:open:"+staffId ;
        try {
            RedisUtil.lock(lockKey , 3L);
            TabOpenStaff openStaff = this.openStaffMapper.getByStaffId(staffId) ;
            if(null == openStaff) {
                openStaff = new TabOpenStaff() ;
                openStaff.setStaffId(staffId);
                openStaff.setWxEnterpriseId(qdto.getWxEnterpriseId());
                openStaff.setEnterpriseId(qdto.getEnterpriseId());
            }
            Long qwUserId = null ;
            if(null != openStaff) {
                qwUserId = openStaff.getQwUserId() ;
            }
            ServiceResponse<QwOpenResultInitBO> resp = OpenUtils.init(qwUserId) ;
            log.info("resp={}", JSONObject.toJSONString(resp));
            QwOpenResultInitBO init = resp.getResult() ;
            openStaff.setUuid(init.getUuid());
            openStaff.setQrCode1(init.getQrcode());
            openStaff.setKey1(init.getKey());
            openStaff = this.openStaffService.save(openStaff);
            return ServiceResponse.success(openStaff.getOpenStaffId()) ;
        }catch (Exception e) {
            log.info("异常",e);
        }
        return ServiceResponse.failure("9999","登录失败") ;
    }
}
