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

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.dao.mapper.hm.HmQrcodeTempMapper;
import com.gic.haoban.manage.service.entity.hm.TabHmQrcodeTemp;
import com.gic.haoban.manage.service.pojo.qo.HmQrcodeTempQO;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.hm.HmQrcodeTempService;
import com.gic.haoban.manage.service.util.QwUtils;
import com.gic.wechat.api.dto.qywx.response.QywxResponseDTO;
import com.gic.wechat.api.service.qywx.QywxUserApiService;

@Service
public class HmQrcodeTempServiceImpl implements HmQrcodeTempService {

    private static org.apache.logging.log4j.Logger log = LogManager.getLogger(HmQrcodeTempService.class);

    @Autowired
    private HmQrcodeTempMapper hmQrcodeTempMapper;
    @Autowired
    private QywxUserApiService qywxUserApiService;
    @Autowired
    private Config config;
    @Autowired
    private WxEnterpriseService wxEnterpriseService ;

    @Override
    public void save(HmQrcodeTempQO qo) {
        TabHmQrcodeTemp entity = EntityUtil.changeEntityByJSON(TabHmQrcodeTemp.class, qo);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setStatusFlag(1);
        entity.setId(UniqueIdUtils.uniqueLong());
        this.hmQrcodeTempMapper.insert(entity);
    }

    @Override
    public void deleteForTimer() {
        log.info("删除临时活码定时开始");
        List<TabHmQrcodeTemp> list = this.hmQrcodeTempMapper.listAll();
        if (CollectionUtils.isNotEmpty(list)) {
            for (TabHmQrcodeTemp item : list) {
                this.del(item);
            }
        }
    }

    private void del(TabHmQrcodeTemp item) {
        try {
            String corpid = item.getCorpid();
            String configId = item.getWxConfigId();
            WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(item.getWxEnterpriseId());
            QywxResponseDTO resp = qywxUserApiService.delContactWay(qwDTO.getThirdCorpid(), QwUtils.getSecret(qwDTO, config.getWxSuiteid()), configId,qwDTO.isSelf(),qwDTO.getUrlHost());
            log.info("删除临时活码={}{},返回={}", configId, corpid, JSON.toJSONString(resp));
            this.hmQrcodeTempMapper.deleteByPrimaryKey(item.getId());
        } catch (Exception e) {
            log.info("删除临时活码异常={}", e);
        }
    }
}
