package com.fs.qw.service.impl;

import com.fs.common.core.domain.R;
import com.fs.qw.domain.QwDept;
import com.fs.qw.mapper.QwDeptMapper;
import com.fs.qw.service.IQwDeptService;
import com.fs.qwApi.domain.QwDeptResult;
import com.fs.qwApi.domain.inner.Department;
import com.fs.qwApi.service.QwApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 企业微信部门Service业务层处理
 *
 * @author fs
 * @date 2024-08-27
 */
@Service
public class QwDeptServiceImpl implements IQwDeptService
{
    @Autowired
    private QwDeptMapper qwDeptMapper;

    @Autowired
    private QwApiService qwApiService;

    /**
     * 查询企业微信部门
     *
     * @param id 企业微信部门主键
     * @return 企业微信部门
     */
    @Override
    public QwDept selectQwDeptById(Long id)
    {
        return qwDeptMapper.selectQwDeptById(id);
    }

    /**
     * 查询企业微信部门列表
     *
     * @param qwDept 企业微信部门
     * @return 企业微信部门
     */
    @Override
    public List<QwDept> selectQwDeptList(QwDept qwDept)
    {
        return qwDeptMapper.selectQwDeptList(qwDept);
    }

    /**
     * 新增企业微信部门
     *
     * @param qwDept 企业微信部门
     * @return 结果
     */
    @Override
    public int insertQwDept(QwDept qwDept)
    {
        return qwDeptMapper.insertQwDept(qwDept);
    }


    /**
     * 新增或插入 企业微信部门
     */
    @Override
    public R insertOrUpdateQwDept(String corpId) {

        QwDeptResult departmentList = qwApiService.getDepartmentList(corpId);

        if (departmentList.getErrcode() == 0) {
            List<Department> department = departmentList.getDepartment();
            for (Department dept : department) {
                QwDept qwDept = new QwDept();
                qwDept.setDeptId(Long.valueOf(dept.getId()));
                qwDept.setDeptName(dept.getName());
                qwDept.setCorpId(corpId);
                qwDept.setParentid(Long.valueOf(dept.getParentid()));
                int i = qwDeptMapper.insertOrUpdateQwDept(qwDept);
            }
        }else {
            return R.error("同步失败："+departmentList.getErrmsg());
        }

        return null;
    }

    /**
     * 修改企业微信部门
     *
     * @param qwDept 企业微信部门
     * @return 结果
     */
    @Override
    public int updateQwDept(QwDept qwDept)
    {
        return qwDeptMapper.updateQwDept(qwDept);
    }

    /**
     * 批量删除企业微信部门
     *
     * @param ids 需要删除的企业微信部门主键
     * @return 结果
     */
    @Override
    public int deleteQwDeptByIds(Long[] ids)
    {
        return qwDeptMapper.deleteQwDeptByIds(ids);
    }

    @Override
    public int deleteQwDeptByDeptId(QwDept qwDept) {
        return qwDeptMapper.deleteQwDeptByDeptId(qwDept);
    }

    /**
     * 删除企业微信部门信息
     *
     * @param id 企业微信部门主键
     * @return 结果
     */
    @Override
    public int deleteQwDeptById(Long id)
    {
        return qwDeptMapper.deleteQwDeptById(id);
    }
}
