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

import com.usoftchina.qywx.sdk.AddrBookSdk;
import com.usoftchina.qywx.sdk.dto.GetDepartmentListResp;
import com.usoftchina.qywx.sdk.dto.GetUserListResp;
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.entity.HrOrg;
import com.usoftchina.uas.office.qywx.service.UasEmployeeService;
import com.usoftchina.uas.office.qywx.service.UasOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

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

    @Autowired
    private AddrBookSdk addrBookSdk;

    @Autowired
    private UasOrgService orgService;

    @Autowired
    private UasEmployeeService employeeService;

    @UasEventListener(caller = "HrOrg", operation = {"DELETE",  "BANNED"})
    public void onOrgDelete(UasEvent event) {
        if (!addrBookSdk.enabled()) {
            return;
        }
        HrOrg org = null;
        if ("DELETE".equals(event.getOperation())) {
            org = orgService.getRemovedById(Integer.parseInt(event.getKey().toString()));
        } else {
            org = orgService.getById(Integer.parseInt(event.getKey().toString()));
        }
        if (null != org && null != org.getOr_qywx() && !addrBookSdk.isReadonly()) {
            // 检查部门下面是否有人
            checkUser(org);
            // 删除，检查部门下面是否有子部门，一并删除
            deleteWithChildren(org.getOr_qywx());
        }
    }

    @UasEventListener(caller = "HrOrg", operation = {"SAVE", "UPDATE", "RESBANNED"})
    public void onOrgSave(UasEvent event) {
        if (!addrBookSdk.enabled()) {
            return;
        }
        HrOrg org = orgService.getById(Integer.parseInt(event.getKey().toString()));
        if (null != org) {
            orgService.sync(org);
        }
    }

    /**
     * 检查部门下面是否有人
     *
     * @param org
     */
    private void checkUser(HrOrg org) {
        List<GetUserListResp.User> userList = addrBookSdk.getUserList(org.getOr_qywx(), true);
        if (!CollectionUtils.isEmpty(userList)) {
            for (GetUserListResp.User user : userList) {
                Employee employee = employeeService.getByQywx(user.getUserid());
                if (null == employee) {
                    addrBookSdk.deleteUser(user.getUserid());
                } else {
                    if (!employeeService.isMemberOfOrg(org, employee)) {
                        employeeService.sync(employee);
                    } else {
                        throw new RuntimeException("部门下面还有有效人员，请先删除人员后再继续！");
                    }
                }
            }
        }
    }

    /**
     * 删除，检查部门下面是否有子部门，一并删除
     *
     * @param departmentId
     */
    private void deleteWithChildren(Integer departmentId) {
        List<GetDepartmentListResp.Department> departmentList = addrBookSdk.getDepartmentList(departmentId);
        if (!CollectionUtils.isEmpty(departmentList)) {
            if (departmentList.size() > 1) {
                for (GetDepartmentListResp.Department department : departmentList) {
                    if (!department.getId().equals(departmentId)) {
                        deleteWithChildren(department.getId());
                    }
                }
            }
            addrBookSdk.deleteDepartment(departmentId);
        }
    }
}
