package com.malk.hangshi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.malk.hangshi.service.HSService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.*;

@Service
@Slf4j
public class HSImplService implements HSService {


    //进出口
    private final static String OUTINURL="https://eacconsole.ceair.com/api/WBPM1-eaccart/statistical/asis/list";
    //餐车数
    private final static String CARURL="https://eacconsole.ceair.com/api/WBPM1-eaccart/cartAbnormal/abnormal";


    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    private Map DEPT_INFO;

    @Override
    @Synchronized
    public Map getDeptInfo(boolean isClear) {

        if (isClear) {
            DEPT_INFO = null;
        }

        if (ObjectUtil.isNull(DEPT_INFO)) {
            int total = 0;
            Map deptInfo = UtilMap.map("东方航空食品投资有限公司", ddClient_contacts.getUserCount(ddClient.getAccessToken(), true));
            // 一级部门累计
            List<Map> deptInfos = ddClient_contacts.listSubDepartmentDetail(ddClient.getAccessToken(), DDConf.TOP_DEPARTMENT);
            for (Map dept : deptInfos) {
                String deptName = String.valueOf(dept.get("name"));
                if (!deptName.contains("航食")) {
                    continue;
                }
                long deptId = UtilMap.getLong(dept, "dept_id");
                int count = 0;
                for (long sub : ddClient_contacts.getDepartmentId_all(ddClient.getAccessToken(), true, deptId)) {
                    count += ddClient_contacts.listDepartmentUserId(ddClient.getAccessToken(), sub).size();
                }
                total += count;
                deptInfo.put(dept.get("name"), count);
                // 上海航食处理
                if (deptName.equals("上海航食")) {
                    List<Map> subDeptInfos = ddClient_contacts.listSubDepartmentDetail(ddClient.getAccessToken(), deptId);
                    for (Map subDept : subDeptInfos) {
                        if (Arrays.asList("虹桥中心", "浦东中心").contains(subDept.get("name"))) {
                            int num = 0;
                            for (long sub : ddClient_contacts.getDepartmentId_all(ddClient.getAccessToken(), true, UtilMap.getLong(subDept, "dept_id"))) {
                                num += ddClient_contacts.listDepartmentUserId(ddClient.getAccessToken(), sub).size();
                            }
                            deptInfo.put(subDept.get("name"), num);
                        }
                    }
                    deptInfo.put("各职能业务部门及事业部", UtilMap.getInt(deptInfo, "上海航食") - UtilMap.getInt(deptInfo, "虹桥中心") - UtilMap.getInt(deptInfo, "浦东中心"));
                }
            }
//            deptInfo.put("航食", total);
            DEPT_INFO = deptInfo;
        }
        return DEPT_INFO;
    }

    @Override
    public int getCorpCount() {
        return ddClient_contacts.getUserCount(ddClient.getAccessToken(), true);
    }


    @Autowired
    private YDClient ydClient;

    @Override
    public void syncHangShiInfo() {

        YDParam ydParam = YDParam.builder()
                .appType("APP_RNU2SVHDBJX8KIFTWVYZ")
                .systemToken("H7966HA1OP38AMWZAHPAB6GZSTR134F87IWDLH")
                .formUuid("FORM-YU966T91NP38DWF5FKBBK6G90HWP3BRBQIWDL1") //获取所有航食列表
                .build();
        List<Map> dataList = (List<Map>) ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getData();


        //遍历航食数据
        dataList.forEach(dataItem -> {
            Map map = (Map) dataItem.get("formData");

            String hsName =  map.get("textField_ldwirsz3").toString();
            String hsId=  map.get("textField_lvxkvjcw").toString();

            LocalDate currentDate = LocalDate.now();
            LocalDate previousDay = currentDate.minusDays(1);

            String rsp = getOutInInfo(getToken(),hsId,previousDay.toString(),OUTINURL);
            Map result = (Map) JSON.parse(rsp);

            Map hashMap = new HashMap();
            Map maps = (Map) result.get("osisList");
            List<Map> mapList = (List<Map>) maps.get("data");

            DecimalFormat df = new DecimalFormat("#.##");
            mapList.forEach(mapItem -> {
                Map map1 = (Map) mapItem.get("dynamicInventoryStatistical");
                hashMap.put("numberField_ldwi9du2",map1.get("longNumber"));  //昨日库存长
                hashMap.put("numberField_ldwi9du3",map1.get("shortNumber"));  //昨日库存长
                hashMap.put("numberField_ldwi9du4",map1.get("total"));  //昨日总库存
                Map map2 = (Map) mapItem.get("inputCartStatistical");
                hashMap.put("numberField_ldwi9dua",map2.get("total"));  //昨日进港量
                Map map3 = (Map) mapItem.get("outputCartStatistical");
                hashMap.put("numberField_ldwi9du9",map3.get("total")); //昨日出港量
                Double totalIn = Double.valueOf(map2.get("total").toString());
                Double totalOut = Double.valueOf(map3.get("total").toString());
                Double totalSum = Double.valueOf(map1.get("total").toString());
                hashMap.put("numberField_ldwi9dub",totalIn-totalOut); //昨日总盈亏
                double  tatalScale= (totalOut / totalSum) * 100;
                hashMap.put("numberField_ldwk062u",df.format(tatalScale)); //餐车利用率

            });


            String rsp2 = getOutInInfo(getToken(),hsId,previousDay.toString(),CARURL);
            Map result2 = (Map) JSON.parse(rsp2);

            Map maps2 = (Map) result2.get("stationAbnormal");
            List<Map> mapList2 = (List<Map>) maps2.get("data");

            mapList2.forEach(mapItem2 -> {
                hashMap.put("numberField_ldwi9dug",mapItem2.get("openingCart"));  //昨日开口餐车数
            });

            hashMap.put("selectField_ldwi9dtr",hsName);  //航食名称

            hashMap.put("dateField_ldwi9dtt", UtilDateTime.parse(String.valueOf(currentDate),"yyyy-MM-dd"));
            hashMap.put("dateField_le2jibxo", UtilDateTime.parse(String.valueOf(previousDay),"yyyy-MM-dd"));


            try {
                ydClient.operateData(YDParam.builder()
                        .appType("APP_RNU2SVHDBJX8KIFTWVYZ")
                        .systemToken("H7966HA1OP38AMWZAHPAB6GZSTR134F87IWDLH")
                        .formUuid("FORM-FC731953C5684406B3A980B1EA6AC93EA9JD") //获取所有航食列表
                        .formDataJson(JSON.toJSONString(hashMap))
                        .build(), YDConf.FORM_OPERATION.create);
            } catch (Exception e) {
                log.info("异常数据 hashMap:{}",hashMap);
            }


        });
    }


    /**
     *
     */
    public String getToken() {

        Map<String, String> body = new HashMap<>();
        body.put("account","7859121209872651");
        body.put("password","efc736bbE@09054c");
        String str = UtilHttp.doPost("https://eacconsole.ceair.com/api/WBPM1-eacorg/external/access",null,null,body);
        String token = String.valueOf(((Map) JSON.parse(str)).get("accessToken"));
        return token;
    }


    /**
     * 进出港数据   开口餐车数
     * @param token
     * @param id
     * @param dataTime
     * @return
     */
    public String getOutInInfo(String token,String id,String dataTime,String url){

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/json;charset=UTF-8");
        headers.put("X-GL-ACCESS-TOKEN",token);
        headers.put("X-GL-AGENT","EAFORG-SERVICE");
        headers.put("X-GL-CLIENT","OPERATION");

        Map<String, String> params = new HashMap<>();
        params.put("pageStart","0");
        params.put("pageSize","10");
        params.put("id",id);
        params.put("paramType","ORGANIZATION");
        params.put("startTime",dataTime);
        params.put("endTime",dataTime);
        String rsp= UtilHttp.doGet(url,headers,params);

        return rsp;
    }

}
