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

import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.OpenStaffDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatDTO;
import com.gic.haoban.manage.api.qdto.OpenStaffPageQDTO;
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.service.OpenStaffService;
import com.gic.haoban.manage.service.util.OpenUtils;
import com.github.pagehelper.PageHelper;
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;
import java.util.List;

@Service("openStaffService")
public class OpenStaffServiceImpl implements OpenStaffService {

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

    @Autowired
    private OpenStaffMapper openStaffMapper ;

    @Override
    public TabOpenStaff save(TabOpenStaff tab) {
        tab.setUpdateTime(new Date());
        if(null == tab.getOpenStaffId()) {
            tab.setOpenStaffId(UniqueIdUtils.uniqueLong());
            tab.setDeleteFlag(0);
            tab.setCreateTime(new Date());
            this.openStaffMapper.insert(tab) ;
        }else {
            this.openStaffMapper.update(tab) ;
        }
        return tab ;
    }

    @Override
    public TabOpenStaff getByUUID(String uuid) {
        TabOpenStaff openStaff = this.openStaffMapper.getByUUID(uuid) ;
        if(null == openStaff) {
            log.info("通过uuid查不到={}",uuid);
            OpenUtils.logout(uuid);
        }
        return openStaff;
    }

    @Override
    public void logout(String uuid) {
        TabOpenStaff openStaff = this.getByUUID(uuid) ;
        if(null == openStaff) {
            return ;
        }
        OpenUtils.logout(uuid);
        openStaff.setStep(0);
        openStaff.setStatusFlag(2);
        openStaff.setValidFlag(0);
        openStaff.setValidQrcodeFlag(0);
        openStaff.setQrCode1(null);
        openStaff.setQrCode2(null);
        openStaff.setKey1(null);
        openStaff.setKey2(null);
        openStaff.setUuid(null);
        this.openStaffMapper.update(openStaff) ;
    }

    @Override
    public ServiceResponse<Page<OpenStaffDTO>> page(OpenStaffPageQDTO qdto, BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo);
        List<OpenStaffDTO> list = this.openStaffMapper.list(qdto);
        Page<OpenStaffDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, OpenStaffDTO.class);
        return ServiceResponse.success(retPage);
    }
}
