package com.template.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;

import com.google.gson.JsonObject;
import com.template.annotation.DESRespondSecret;
import com.template.api.DingtalkControllerAPI;
import com.template.common.utils.DingTalkInterface;
import com.template.common.utils.TimeExchange;
import com.template.model.pojo.AttColumns;
import com.template.model.pojo.SmartUser;
import com.template.model.result.CommonResult;
import com.template.services.SmartUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: binguo
 * @Date: 2023/7/5 星期三 9:28
 * @Description: com.template.controller
 * @Version: 1.0
 */
@RestController
//返回参数加密注解
@DESRespondSecret
@Slf4j
public class DingtalkController implements DingtalkControllerAPI {

    @Autowired
    private DingTalkInterface dingTalkInterface;

    @Autowired
    private SmartUserService smartUserService;
    /**
     * 获取列定义
     * 遍历用户
     * 	根据手机号获取用户id
     * 	根据id获取列值
     * 存入新表
     */
    @Override
    @DESRespondSecret(validated = true)
    public CommonResult queryAttReport(int currentPage, int pageCount, String name, String state) {

        try {
            JSONObject jsonObject=dingTalkInterface.getattcolumns();
            String errcode = String.valueOf(jsonObject.get("errcode"));
            if("0".equals(errcode)){
                JSONObject result=  jsonObject.getJSONObject("result");
                JSONArray columeArray=result.getJSONArray("columns");
//                拼接列id
                StringBuilder stringInsertCols = new StringBuilder();
                List<Map<String, String>> attColumnsList = new ArrayList<>();
                for (int i = 0; i < columeArray.size(); i++) {
//                    入库
                    JSONObject column=columeArray.getJSONObject(i);
//                    AttColumns attColumns=new AttColumns();
                    Map<String,String> attColumnsMap=new HashMap<>();
                    attColumnsMap.put("id",column.getString("id"));
                    attColumnsMap.put("name",column.getString("name"));
                    attColumnsMap.put("alias",column.getString("alias"));
                    attColumnsList.add(attColumnsMap);
                    stringInsertCols.append(column.getString("id")+",");
                }
                String columnId= stringInsertCols.deleteCharAt(stringInsertCols.length() - 1).toString();
                //查询所有用户
                List<SmartUser> users=smartUserService.getListUser();
                for (SmartUser user:users) {
                    //查库没有钉钉id则更新
                    String dingId = user.getDingId();
                    if(dingId==null){
                        JSONObject jsonObject1=dingTalkInterface.getUserIdByPhone(user.getPhone());
                        String flag = String.valueOf(jsonObject.get("errcode"));
                        if(!"0".equals(flag)){
                            log.info("获取"+user.getPhone()+"userId失败;");
                            continue;
                        }
                        dingId=jsonObject.getJSONObject("jsonObject").getString("userid");
                        //存入钉钉id
                        user.setDingId(dingId);
                        smartUserService.saveOrUpdate(user);

                    }
//                    获取列值
                   JSONObject jsonObject1= dingTalkInterface.getcolumnval(dingId,columnId,
                           TimeExchange.TimeDesD(new Date(),-1)+" 00:00:00",TimeExchange.getDate()+" 00:00:00");
                    String flag = String.valueOf(jsonObject1.get("errcode"));
                    if(!"0".equals(flag)){
                        log.info("获取"+user.getPhone()+"考勤数据失败;");
                        continue;
                    }
                    List<Map<String,String>> keyValueList=new ArrayList<>();
                    JSONArray columnValsList=jsonObject1.getJSONObject("result").getJSONArray("column_vals");
                    for (int i = 0; i < columnValsList.size(); i++) {
                        //获取列名
                        String columId=columnValsList.getJSONObject(i).getJSONObject("column_vo").getString("id");
                        List<Map<String, String>> identityData = attColumnsList.stream().filter(e -> e.get("id").equals(columId)).collect(Collectors.toList());
                        if (identityData.isEmpty()){
                            log.info("======"+columId+"===此id列未找到列定义");
                            continue;
                        }
                        String alias=identityData.get(0).get("alias");
                        //获取列值
                        JSONArray valsArray=columnValsList.getJSONObject(i).getJSONArray("column_vals");
                        String vals="";
                        if (valsArray!=null&&valsArray.size()>0){
                            vals=valsArray.getJSONObject(0).getString("value");
                        }else{
                            vals=columnValsList.getJSONObject(i).getString("fixed_value");
                        }
                        Map<String,String> keyValue=new HashMap<>();
                        keyValue.put(alias,vals);
                        keyValueList.add(keyValue);
                    }
                    //根据keyValueList入库

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.fail(e.getMessage());
        }
        return CommonResult.ok("");
    }

}
