package com.muzhi.dingtalk.test.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiSmartworkHrmEmployeeListRequest;
import com.dingtalk.api.request.OapiSmartworkHrmEmployeeQuerydimissionRequest;
import com.dingtalk.api.request.OapiSmartworkHrmEmployeeQueryonjobRequest;
import com.dingtalk.api.response.OapiSmartworkHrmEmployeeListResponse;
import com.dingtalk.api.response.OapiSmartworkHrmEmployeeQuerydimissionResponse;
import com.dingtalk.api.response.OapiSmartworkHrmEmployeeQueryonjobResponse;
import com.muzhi.dingtalk.test.entity.Employee;
import com.muzhi.dingtalk.test.entity.vo.EmployeeDataVo;
import com.muzhi.dingtalk.test.entity.vo.EmployeeQuery;
import com.muzhi.dingtalk.test.mapper.EmployeeMapper;
import com.muzhi.dingtalk.test.service.DingAccessTokenService;
import com.muzhi.dingtalk.test.service.EmployeeService;
import com.muzhi.dingtalk.test.service.FangDeDingAccessTokenService;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;


@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private DingAccessTokenService dingAccessTokenService;

    @Autowired
    private FangDeDingAccessTokenService fangDeDingAccessTokenService;

    @Autowired
    private EmployeeMapper employeeMapper;

    public static String employee = null;
    public static String huamingce = null;

    //获取公司在职员工id列表
    @Override
    public String getEmployeeId() {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
        OapiSmartworkHrmEmployeeQueryonjobRequest request = new OapiSmartworkHrmEmployeeQueryonjobRequest();

        //企业在职员工userid列表
        int offset = 0;//分页游标，从0开始
        int size = 20;//分页大小，最大50

        List<String> list = new ArrayList<>();

        JSONObject result;

        do {

            System.out.println("测试分页值：" + offset);

            try {
                request.setStatusList("2,3,5,-1");
                request.setOffset((long) offset);
                request.setSize((long) size);
                OapiSmartworkHrmEmployeeQueryonjobResponse response = client.execute(request, dingAccessTokenService.getAccessToken());
                employee = response.getBody();
                System.out.println(response.getBody());
            } catch (ApiException e) {
                e.printStackTrace();
            }

            //通过fastjson工具转换成json对象,逐层解析
            JSONObject jsonObject = JSON.parseObject(employee);
            result = jsonObject.getJSONObject("result");

            String dataList = result.getString("data_list");

            //将String数组进行处理，去掉所有的双引号（""）和中括号（[]）
            String dataRes = dataList.replace("\"", "").
                    replaceAll("\\[", "").
                    replaceAll("\\]", "");

            list.add(dataRes);

            if (result.getString("next_cursor") != null || result.getString("data_list") != "") {

                offset = offset + size;

            }

        } while (result.getString("next_cursor") != null);

        String userid = list.toString().replace("\"", "").
                replaceAll("\\[", "").
                replaceAll("\\]", "");

        return userid;
    }

    //获取公司离职员工id列表
    @Override
    public String getLiZhiEmployeeId() {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
        OapiSmartworkHrmEmployeeQuerydimissionRequest request = new OapiSmartworkHrmEmployeeQuerydimissionRequest();

        //企业在职员工userid列表
        int offset = 0;//分页游标，从0开始
        int size = 20;//分页大小，最大50

        List<String> list = new ArrayList<>();

        JSONObject result;

        do {

            System.out.println("测试分页值：" + offset);

            try {
                request.setOffset((long) offset);
                request.setSize((long) size);
                OapiSmartworkHrmEmployeeQuerydimissionResponse response = client.execute(request, fangDeDingAccessTokenService.getFangDeAccessToken());
                employee = response.getBody();
                System.out.println(response.getBody());
            } catch (ApiException e) {
                e.printStackTrace();
            }

            //通过fastjson工具转换成json对象,逐层解析
            JSONObject jsonObject = JSON.parseObject(employee);
            result = jsonObject.getJSONObject("result");

            String dataList = result.getString("data_list");

            //将String数组进行处理，去掉所有的双引号（""）和中括号（[]）
            String dataRes = dataList.replace("\"", "").
                    replaceAll("\\[", "").
                    replaceAll("\\]", "");

            list.add(dataRes);

            if (result.getString("next_cursor") != null || result.getString("data_list") != "") {

                offset = offset + size;

            }

        } while (result.getString("next_cursor") != null);

        String userid = list.toString().replace("\"", "").
                replaceAll("\\[", "").
                replaceAll("\\]", "");

        return userid;
    }




    //获取公司在职员工id列表（未去除",[]）
    @Override
    public List<String> getEmployeeIdAll() {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
        OapiSmartworkHrmEmployeeQueryonjobRequest request = new OapiSmartworkHrmEmployeeQueryonjobRequest();
        try {
            request.setStatusList("2,3,5,-1");
            request.setOffset(0L);
            request.setSize(50L);
            OapiSmartworkHrmEmployeeQueryonjobResponse response = client.execute(request, dingAccessTokenService.getAccessToken());
            employee = response.getBody();
            System.out.println(response.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }

        //通过fastjson工具转换成json对象,逐层解析
        JSONObject jsonObject = JSON.parseObject(employee);
        JSONObject result = jsonObject.getJSONObject("result");
        List dataList = result.getJSONArray("data_list");

        return dataList;
    }

    //查询钉钉接口中的花名册信息
    @Override
    public String getDingHuamingce(){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list");
        OapiSmartworkHrmEmployeeListRequest request = new OapiSmartworkHrmEmployeeListRequest();

        try {
            request.setUseridList(getEmployeeId());

            //需要获取的花名册字段信息
            //request.setFieldFilterList("sys00-name,sys02-sexType,sys01-employeeStatus,sys00-email,sys03-graduateSchool,sys03-highestEdu,sys00-dept,e3d6dbbd-9265-4f1e-8c58-ac3602e83960,sys03-graduationTime,sys00-mobile,sys02-address,sys02-marriage,sys00-confirmJoinTime,sys00-workPlace,sys00-position,sys01-positionLevel,sys02-politicalStatus,sys03-major,sys02-certNo,sys02-birthTime,sys02-certAddress,sys02-certEndTime,sys02-residenceType,sys01-employeeType,sys04-bankAccountNo,sys04-accountBank,sys09-personalHf,sys05-contractType,sys05-contractCompanyName,ff63191a-45cf-4106-ade0-54f1def7cc55");

            OapiSmartworkHrmEmployeeListResponse response = client.execute(request, dingAccessTokenService.getAccessToken());
            huamingce = response.getBody();
            System.out.println(response.getBody());
        }catch (ApiException e){
            e.printStackTrace();
        }

        //通过fastjson工具转换成json对象,逐层解析
        //将String类型的花名册json数据转换为Object数据对象
        JSONObject jsonObject = JSON.parseObject(huamingce);
        String result = jsonObject.getString("result");

        return result;
    }

    //获取数据库中员工花名册employee实体类表数据并放入vo对象进行前端接口调用展示数据
    @Override
    public EmployeeDataVo<Employee> getHuamingce(Integer page, Integer limit, EmployeeQuery employeeQuery){
        //写法1：调用写好的接口（查询数据库中employee表的所有数据）
//        EmployeeDataVo employeeDataVo = new EmployeeDataVo();
//        employeeDataVo.setCode(0);
//        employeeDataVo.setMsg("");
//        employeeDataVo.setCount(tongbuService.getEmployee().size());
//
//        employeeDataVo.setData(tongbuService.getEmployee());
//        return employeeDataVo;

        //写法2：直接在该实现类查询数据库实体类的数据
        EmployeeDataVo employeeDataVo = new EmployeeDataVo();
        employeeDataVo.setCode(0);
        employeeDataVo.setMsg("");
        //查询总数方法1
//        employeeDataVo.setCount(employeeMapper.selectCount(null));

        //分页查询,创建page对象
        Page<Employee> employeePage = new Page<>(page,limit);

        //构建查询条件
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        //多条件组合查询（类似mybatis中动态sql）
        String name = employeeQuery.getName();
        Integer sex = employeeQuery.getSex();
        String date = employeeQuery.getDate();
        //判断条件值是否为空，如果不为空则拼接条件
        if (!StringUtils.isEmpty(name)) {
            //构建条件
            wrapper.like("sys00_name", name);
        }
        if (!StringUtils.isEmpty(sex)) {
            wrapper.eq("sys02_sex_type", sex);
        }
        if (!StringUtils.isEmpty(date)) {
            wrapper.eq("sys00_confirm_join_time", date);
        }
        //排序：按照入职日期进行排序
        wrapper.orderByDesc("sys00_confirm_join_time");
//
//        List<Employee> employeeList = employeePage.getRecords();

        IPage<Employee> result = employeeMapper.selectPage(employeePage, wrapper);

        //查询实体类表中所有的数据（全部）
//        List<Employee> employeeList = employeeMapper.selectList(null);
        //查询分页信息记录（根据分页要求来查）
        List<Employee> employeeList = result.getRecords();
        //查询总数方法2
        employeeDataVo.setCount(result.getTotal());

//        List<EmployeeVo> employeeVoList = new ArrayList<>();
//        for (Employee employee : employeeList) {
//            EmployeeVo employeeVo = new EmployeeVo();
//            //将前面实体类表中的数据，一一对应赋值给后面的vo对象
//            BeanUtils.copyProperties(employee,employeeVo);
//
//            employeeVoList.add(employeeVo);
//        }

        employeeDataVo.setData(employeeList);
        return employeeDataVo;
    }
}
