package com.lz.modules.job.business;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.google.common.collect.Lists;
import com.lz.common.utils.DateUtils;
import com.lz.common.utils.DingTalkUtil;
import com.lz.modules.app.dao.StaffDao;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.entity.StaffOccupationEntity;
import com.lz.modules.app.service.DepartmentsService;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.app.service.StaffOccupationService;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.job.model.responseBo.DepartmentInfosBo;
import com.lz.modules.job.model.responseBo.DepartmentStaffBo;
import com.mchange.lang.IntegerUtils;
import com.taobao.api.ApiException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author fumeiai
 * @date 2019-05-29 17:06
 * @Description 钉钉同步业务
 * @注意 本内容仅限于杭州霖梓网络科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
@Component(value = "dingtalkBusiness")
public class DingtalkBusiness {
    protected final static org.slf4j.Logger logger = LoggerFactory.getLogger(DingtalkBusiness.class);

    @Autowired
    DingTalkUtil dingTalkUtil;

    @Resource
    DepartmentsService departmentsService;

    @Resource
    DepartmentsStaffRelateService departmentsStaffRelateService;

    @Resource
    StaffService staffService;

    @Resource
    StaffOccupationService staffOccupationService;

    @Resource
    StaffDao staffDao;


    /**
     * 获取组织架构信息并录入到数据库
     */
//    @DataSource(name = DataSourceNames.FOUR)
    public void getDingTalkepartmentsIntoData(String appid) {

        /*List<StaffEntity> staffEntityList = staffDao.selectByRang("535");//飞书数据更新为钉钉数据
        for (StaffEntity staff:staffEntityList
             ) {
            List<StaffEntity> list = staffDao.selectByName(staff.getName());
            if(list.size() > 0){
                StaffEntity staff1 = list.get(0);
                if(staff.getId().intValue() != staff1.getId().intValue()){
                    staff1.setJobNumber(staff.getJobNumber());
                    staff1.setAvatar(staff.getAvatar());
                    staff1.setEmployeeId(staff.getEmployeeId());
                    staff1.setOpenId(staff.getOpenId());
                    staff1.setUnionId(staff.getUnionId());


                    staffDao.deleteById(staff.getId());
                    staffDao.updateStaff(staff1);
                }

            }


        }
        return;*/
        //获取Token
        String token = dingTalkUtil.getAccessToken(appid);
        if(token != null && token.length() > 0){

            //获取所有的部门详情
            List<DepartmentInfosBo> departmentInfosBos = dingTalkUtil.getDepartmentDetails(token, "1");
            if(departmentInfosBos.size() > 0){
                //更新数据库中的部门相关信息
                departmentsService.updateDepartmentInfos(departmentInfosBos);
                //删除原有的对应关系下面在更新
                departmentsStaffRelateService.deleteAllRelates();
                //未在飞书组织架构里的成员，置为离职(全部置为离职，再把在职的恢复)
                staffOccupationService.updateAllOccupation();
                //获取飞书部门对应的用户详情
                for (DepartmentInfosBo departmentInfo : departmentInfosBos) {
                    //获取部门用户详情
                    List<DepartmentStaffBo> staffs = dingTalkUtil.getDepartmentStaffDetails(token, departmentInfo.getId());
                    logger.info("=============================" + departmentInfo.getName() + "================================");
                    if(staffs.size() > 0){
                        //循环录入到员工信息表中
                        List<StaffEntity> staffIds = staffService.updateStaffsInfo(staffs);

                        //加入到部门和员工关系表，同时更新leader关系
                        departmentsStaffRelateService.addRelateInfos(departmentInfo.getId(), staffIds);
                        //录入员工职业信息表
                        enterStaffOccupationInfos(staffs);
                    }
                }
            }else{
                logger.info("部门信息为空");
            }
        }
    }

    public void enterStaffOccupationInfos(List<DepartmentStaffBo> staffs) {
        List<StaffOccupationEntity> StaffOccupations = Lists.newArrayList();
        for (DepartmentStaffBo departmentStaffBo : staffs) {
            StaffEntity staffEntity = staffService.getStaffInfoByOpenId(departmentStaffBo.getOpenId());
            Long staffId = staffEntity.getId();
            StaffOccupationEntity staffOccupationEntity = staffOccupationService.getStaffOccupationByStaffId(staffId);
            if (staffOccupationEntity == null) {
                StaffOccupationEntity staffOccupation = new StaffOccupationEntity();
                staffOccupation.setStaffId(staffId);
                staffOccupation.setPosition(departmentStaffBo.getPosition());//职位信息
                staffOccupation.setEmployeeNo(departmentStaffBo.getEmployeeNo());
                staffOccupation.setStaffNo(departmentStaffBo.getEmployeeNo());//钉钉的员工工号
                staffOccupation.setStaffType(departmentStaffBo.getEmployeeType());
                staffOccupation.setStaffStatus(departmentStaffBo.getStatus());
                staffOccupation.setEntryTime(DateUtils.getCurrentDate());
                StaffOccupations.add(staffOccupation);
            } else {
                staffOccupationService.updateStatusByStaff(staffId, departmentStaffBo);//更新职位信息，工号信息
            }
        }
        if (StaffOccupations.size() > 0) {
            staffOccupationService.saveBatch(StaffOccupations);
        }
    }
}
