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

import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.usoftchina.dingtalk.sdk.AddrBookSdk;
import com.usoftchina.uas.office.dingtalk.entity.Employee;
import com.usoftchina.uas.office.dingtalk.entity.HrOrg;
import com.usoftchina.uas.office.dingtalk.service.UasEmployeeService;
import com.usoftchina.uas.office.dingtalk.service.UasOrgService;
import com.usoftchina.uas.office.dto.UasEvent;
import com.usoftchina.uas.office.listener.UasEventListener;
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) {
        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_ding()) {
            // 检查部门下面是否有人
            checkUser(org);
            // 删除，检查部门下面是否有子部门，一并删除
            deleteWithChildren(org.getOr_ding());
        }
    }

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

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

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