package com.usoftchina.uas.office.qywx.listener;

import com.usoftchina.qywx.sdk.AddrBookSdk;
import com.usoftchina.qywx.sdk.dto.UpdateUserReq;
import com.usoftchina.uas.office.dto.UasEvent;
import com.usoftchina.uas.office.listener.UasEventListener;
import com.usoftchina.uas.office.qywx.entity.Employee;
import com.usoftchina.uas.office.qywx.service.UasEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yingp
 * @date 2020/2/16
 */
@Component
public class UasEmployeeListener {

    @Autowired
    private AddrBookSdk addrBookSdk;

    @Autowired
    private UasEmployeeService employeeService;

    /**
     * uas人员资料审核，修改企业微信通讯录人员
     */
    @UasEventListener(caller = "Employeemanager", operation = "AUDIT")
    public void onEmployeeAudit(UasEvent event) {
        if (!addrBookSdk.enabled()) {
            return;
        }
        Employee employee = employeeService.getById(Integer.parseInt(event.getKey().toString()));
        if (null != employee) {
            if ("离职".equals(employee.getEm_class())) {
                if (null != employee.getEm_qywx() && !addrBookSdk.isReadonly()) {
                    addrBookSdk.deleteUser(employee.getEm_qywx());
                }
            } else {
                employeeService.sync(employee);
            }
        }
    }

    /**
     * uas人员资料反审核，禁用企业微信通讯录人员
     */
    @UasEventListener(caller = "Employeemanager", operation = "RESAUDIT")
    public void onEmployeeUnAudit(UasEvent event) {
        if (!addrBookSdk.enabled()) {
            return;
        }
        Employee employee = employeeService.getById(Integer.parseInt(event.getKey().toString()));
        if (null != employee && null != employee.getEm_qywx() && !addrBookSdk.isReadonly()) {
            addrBookSdk.updateUser(new UpdateUserReq().userId(employee.getEm_qywx()).enable(false));
        }
    }

    /**
     * uas人员资料删除，删除企业微信通讯录人员
     */
    @UasEventListener(caller = "Employeemanager", operation = "DELETE")
    public void onEmployeeDelete(UasEvent event) {
        if (!addrBookSdk.enabled()) {
            return;
        }
        Employee employee = employeeService.getRemovedById(Integer.parseInt(event.getKey().toString()));
        if (null != employee && null != employee.getEm_qywx() && !addrBookSdk.isReadonly()) {
            addrBookSdk.deleteUser(employee.getEm_qywx());
        }
    }
}
