package com.kingdee.eas.custom.erp.util;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.qing.util.StringUtils;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;

public class SynAdminOrgToERPUtils {


    private static Logger log = LoggerFactory.getLogger(SynSalaryFromErpUtils.class);


    //https://sites.gtiit.edu.cn/kderpdev/ierp/kapi/v2/gt15/base/bos_adminorg/gt15_adminorg_add
    private static String ierp = "https://sites.gtiit.edu.cn/kderpdev/ierp";


    /**
     * 新增：获取gt15_adminorg_add的请求地址
     *
     * @param request
     * @param code
     * @return
     */
    public static String getGt15AdminOrgAddUrl() {
        Properties config = SynPublicUtils.getConfig();
        ierp = (String) config.get("ierp");
        return new StringBuffer().append(ierp).append("/kapi/v2/gt15/base/bos_adminorg/gt15_adminorg_add").toString();

    }


    /**
     * 封存：获取gt15_adminorg_beta的请求地址: https://sites.gtiit.edu.cn/kderpdev/ierp/kapi/v2/gt15/base/bos_adminorg/gt15_adminorg_beta
     *
     * @param request
     * @param code
     * @return
     */
    public static String getGt15AdminOrgBetaUrl() {
        Properties config = SynPublicUtils.getConfig();
        ierp = (String) config.get("ierp");
        return new StringBuffer().append(ierp).append("/kapi/v2/gt15/base/bos_adminorg/gt15_adminorg_beta").toString();

    }


    /**
     * 新增：请求参数
     * 获取所有行政组织的
     *
     * @param ctx
     * @return
     * @throws BOSException
     * @throws SQLException
     */
    private static String getAdminOrgDetailEntry(Context ctx, String startDateStr, String endDateStr) throws BOSException, SQLException {


        //获取前一天的0点时间字符串
        String lastDateZeroTimeStr = "";

        //获取当前时间的字符串
        String noeTimeStr = "";

        if (StringUtils.isEmpty(startDateStr) || StringUtils.isEmpty(endDateStr)) {
            //获取上次同步结束的时间
            lastDateZeroTimeStr = SynPublicUtils.getLastUpdateSynTableTimeStrByEvenName(ctx, "synAdminOrgToErp");

            if (StringUtils.isEmpty(lastDateZeroTimeStr)) {
                //为空
                //获取前一天的0点时间字符串
                lastDateZeroTimeStr = SynPublicUtils.getLastDateZeroTime();
            }

            //更新最新 的时间为event_timeStamp,只有在自动触发的才会修改时间
            SynPublicUtils.updateSynTimeTable(ctx, "synAdminOrgToErp");

            //获取当前时间的字符串
            noeTimeStr = SynPublicUtils.getNowTimeStr();
        } else {
            lastDateZeroTimeStr = startDateStr;
            noeTimeStr = endDateStr;
        }

        String sql = "select admin.fnumber as number,admin.fname_l1 as name_l1,admin.fname_l2 as name_l2,admin.fname_l3 as name_l3,admin.fsimplename as gt15_shortname,admin.fname_l2 as gt15_chinesename ,layerType.fnumber as orgpattern_number,layerType.fname_l1 as orgpattern_name ,admin.fdescription_l1 as fcomment,admin2.fnumber as viewparent_number from t_org_admin admin "
                + " left join T_Org_LayerType   layerType on layerType.fid = admin.flayertypeid "
                + " left join t_org_admin admin2 on admin2.fid = admin.fparentid where admin.fisousealup = 0 "
                + "  and ( (admin.flastupdatetime >  {ts '" + lastDateZeroTimeStr + "'} and  admin.flastupdatetime <=  {ts '" + noeTimeStr + "'} ) "
                + "  or (layerType.flastupdatetime >  {ts '" + lastDateZeroTimeStr + "'} and  layerType.flastupdatetime <=  {ts '" + noeTimeStr + "'} ) "
                + "  or (admin2.flastupdatetime >  {ts '" + lastDateZeroTimeStr + "'} and  admin2.flastupdatetime <=  {ts '" + noeTimeStr + "'} )) ";
        //+ " left join t_org_admin admin2 on admin2.fid = admin.fparentid where admin.fisousealup = 0 and  admin.fnumber  not in ('D0003','D0002','D0039','D0040') ";
        log.info("getAdminOrgDetailEntry.sql:" + sql);

        IRowSet executeQuery = DbUtil.executeQuery(ctx, sql);

        JSONArray datas = new JSONArray();
        String paramJOStr = "";
        if (executeQuery.size() > 0) {
            while (executeQuery.next()) {
                String number = executeQuery.getString("number");
                String name_l1 = executeQuery.getString("name_l1");
                String name_l2 = executeQuery.getString("name_l2");
                String name_l3 = executeQuery.getString("name_l3");
                String gt15_shortname = executeQuery.getString("gt15_shortname");
                String gt15_chinesename = executeQuery.getString("gt15_chinesename");
                String orgpattern_number = executeQuery.getString("orgpattern_number");
                String orgpattern_name = executeQuery.getString("orgpattern_name");
                String fcomment = executeQuery.getString("fcomment");
                String viewparent_number = executeQuery.getString("viewparent_number");


                JSONArray structures = new JSONArray();

                JSONObject structure = new JSONObject();
                structure.put("view_number", "01");

                if (StringUtils.isEmpty(viewparent_number)) {
                    //根部组织不传
                    continue;
                }
                structure.put("viewparent_number", viewparent_number);
                structures.add(structure);


                JSONObject data = new JSONObject();
                data.put("number", number);

                JSONObject name = new JSONObject();
                name.put("en_US", name_l1);
                name.put("zh_CN", name_l2);
                name.put("zh_TW", name_l3);

                data.put("name", name);
                data.put("gt15_shortname", gt15_shortname);
                data.put("gt15_chinesename", gt15_chinesename);

                data.put("orgpattern_name", orgpattern_name);

                if ("集团".equals(orgpattern_number)) {
                    orgpattern_number = "Group";
                } else if ("公司".equals(orgpattern_number)) {
                    orgpattern_number = "Company";
                } else if ("部门".equals(orgpattern_number)) {
                    orgpattern_number = "Dept";
                }
                data.put("orgpattern_number", orgpattern_number);

                data.put("fcomment", fcomment);

                data.put("structure", structures);

                datas.add(data);
            }
            JSONObject paramJO = new JSONObject();
            paramJO.put("data", datas);
            paramJOStr = paramJO.toString();
        }
        return paramJOStr;
    }


    /**
     * 新增：新增行政组织接口，推送到星瀚
     *
     * @param ctx
     * @param accessToken
     * @throws Exception
     */
    public static String gt15_adminorg_add(Context ctx, String accessToken, String startDate, String endDate) throws Exception {
        //获取请求地址
        String gt15AdminOrgAddUrl = getGt15AdminOrgAddUrl();

        log.info("SynAdminOrgToERPUtils.gt15_adminorg_add.gt15AdminOrgAddUrl:" + gt15AdminOrgAddUrl);
        //构建行政组织参数
        String paramJOStr = getAdminOrgDetailEntry(ctx, startDate, endDate);
        log.info("SynAdminOrgToERPUtils.gt15_adminorg_add.paramJOStr:" + paramJOStr);
        //数据保存接口
        String responseMsg = HttpsReqUtil.postByHttps(gt15AdminOrgAddUrl, paramJOStr, accessToken);


        return responseMsg;
    }


    /**
     * 新增：推送数据到ERP功能:主体
     *
     * @return
     * @throws Exception
     */
    public static String synAdminorgToErp(Context ctx, String startDate, String endDate) throws Exception {

        //获取appToken
        String appToken = SynSalaryFromErpUtils.getAppToken(ctx);
        log.info("获取synAdminorgToErp.appToken：" + appToken);
        //获取accessToken
        String accessToken = SynSalaryFromErpUtils.getAccessToken(appToken);
        log.info("获取synAdminorgToErp.accessToken状态为：" + accessToken);
        //薪酬明细保存接口
        String responseMsg = gt15_adminorg_add(ctx, accessToken, startDate, endDate);
        log.info("synAdminorgToErp.responseMsg：" + accessToken);
        return null;
    }


    /**
     * 封存：获取封存行政组织的请求参数
     *
     * @param ctx
     * @param startDateStr
     * @param endDateStr
     * @return
     * @throws BOSException
     * @throws SQLException
     */
    public static List<String> getAdminOrgBetaDetailEntry(Context ctx, String startDateStr, String endDateStr) throws BOSException, SQLException {
        //String sql = " select fnumber as number from  t_org_admin where fisousealup = 1 and fnumber not in ('D0003','D0002','D0039','D0040')";

        //获取前一天的0点时间字符串
        String lastDateZeroTimeStr = "";

        //获取当前时间的字符串
        String noeTimeStr = "";

        if (StringUtils.isEmpty(startDateStr) || StringUtils.isEmpty(endDateStr)) {
            //获取上次同步结束的时间
            lastDateZeroTimeStr = SynPublicUtils.getLastUpdateSynTableTimeStrByEvenName(ctx, "synAdminOrgBetaToErp");

            if (StringUtils.isEmpty(lastDateZeroTimeStr)) {
                //为空
                //获取前一天的0点时间字符串
                lastDateZeroTimeStr = SynPublicUtils.getLastDateZeroTime();
            }

            //更新最新 的时间为event_timeStamp,只有在自动触发的才会修改时间
            SynPublicUtils.updateSynTimeTable(ctx, "synAdminOrgBetaToErp");

            //获取当前时间的字符串
            noeTimeStr = SynPublicUtils.getNowTimeStr();
        } else {
            lastDateZeroTimeStr = startDateStr;
            noeTimeStr = endDateStr;
        }


        String sql = " select fnumber as number from  t_org_admin where fisousealup = 1 " +
                " and (flastupdatetime > {ts '" + lastDateZeroTimeStr + "'} and  flastupdatetime <=  {ts '" + noeTimeStr + "'})";
        log.info("getAdminOrgBetaDetailEntry.sql" + sql);
        IRowSet executeQuery = DbUtil.executeQuery(ctx, sql);
        List<String> numbers = new ArrayList<String>();
        if (executeQuery.size() > 0) {
            while (executeQuery.next()) {
                String number = executeQuery.getString("number");
                numbers.add(number);
            }
        }
        return numbers;
    }

    /**
     * 封存：通过编码获取
     *
     * @param number
     * @return
     */
    public static String getParamJOStrByNumber(String number) {
        JSONObject data = new JSONObject();
        data.put("number", number);
        JSONObject paramJO = new JSONObject();
        paramJO.put("data", data);
        String paramJOStr = paramJO.toString();
        return paramJOStr;
    }


    /**
     * 封存：根据编码封存行政组织
     *
     * @param ctx
     * @param accessToken
     * @return
     * @throws Exception
     */
    public static void synGt15_adminorg_beta(Context ctx, String accessToken, String startDate, String endDate) throws Exception {
        //获取请求地址
        String gt15AdminOrgBetaUrl = getGt15AdminOrgBetaUrl();

        log.info("SynAdminOrgToERPUtils.synGt15_adminorg_beta.gt15AdminOrgBetaUrl:" + gt15AdminOrgBetaUrl);
        //构建行政组织参数
        List<String> numbers = getAdminOrgBetaDetailEntry(ctx, startDate, endDate);
        log.info("SynAdminOrgToERPUtils.gt15_adminorg_add.numbers:" + numbers.size());

        for (String number : numbers) {
            String paramJOStr = getParamJOStrByNumber(number);
            //数据保存接口
            String responseMsg = HttpsReqUtil.postByHttps(gt15AdminOrgBetaUrl, paramJOStr, accessToken);
        }

    }


    /**
     * 封存：封存根据编码封存行政组织:主体
     *
     * @param ctx
     * @return
     * @throws Exception
     */
    public static String syndminorgBetaToErp(Context ctx, String startDate, String endDate) throws Exception {
        //获取appToken
        String appToken = SynSalaryFromErpUtils.getAppToken(ctx);
        log.info("获取syndminorgBetaToErp.appToken：" + appToken);
        //获取accessToken
        String accessToken = SynSalaryFromErpUtils.getAccessToken(appToken);
        log.info("获取syndminorgBetaToErp.accessToken为：" + accessToken);
        //薪酬明细保存接口
        synGt15_adminorg_beta(ctx, accessToken, startDate, endDate);
        log.info("syndminorgBetaToErp.responseMsg：" + accessToken);

        return "";
    }


}
