package cn.com.ctop.kuaishou.modules.batch.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouOperationRecord;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouOperationRecordMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService2;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class KuaishouInterfaceServiceImpl2 implements IKuaishouInterfaceService2 {

    @Resource
    private KuaishouOperationRecordMapper kuaishouOperationRecordMapper;


    @Override
    public void getOperationRecord(Long advertiserId, String accessToken, Integer operationTarget, String startDate, String endDate){

//        Long days = DateUtils.getDiscrepantDays(startDate, endDate);
//        String start = null;
//        String end = null;
        //for (int i = 0; i <= days; i++) {
        //    start = DateUtils.addDay(startDate, i);
        //    end = start;
        getOperationRecordByPage2(advertiserId, accessToken,1, 500, operationTarget, startDate, endDate);
        //}
    }

    private void getOperationRecordByPage(Long advertiserId, String accessToken, Integer page, Integer pageSize, Integer operationTarget, String startDate, String endDate) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.OPERATION_RECORD;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject json = new JSONObject();
        json.put("advertiser_id", advertiserId);
        json.put("operation_target", operationTarget);
        json.put("page", page);
        json.put("page_size", pageSize);
        json.put("start_date", startDate);
        json.put("end_date", endDate);

        String result = HttpUtils.kuaiShouhttpPostRequest(url, json.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);

        if(!Check.isNull(resultJson)){
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                JSONObject data = resultJson.getJSONObject("data");
                if (!Check.isNull(data)) {
                    List<KuaishouOperationRecord> recordList =  new ArrayList();

                    Integer totalCount = data.getInteger("total_count");
                    JSONArray dataArr = data.getJSONArray("details");
                    for (int i = 0; i < dataArr.size(); i++) {
                        JSONObject dataJson = JSONObject.parseObject(dataArr.get(i).toString());
                        if (!Check.isNull(dataJson)) {

                            Date operationTime = dataJson.getDate("operation_time");
                            //Date operationDate = DateUtils.parseDate()
                            Integer operationType = dataJson.getInteger("operation_type");
                            operationTarget = dataJson.getInteger("operation_target");
                            Integer roleType = dataJson.getInteger("role_type");
                            String objectId = dataJson.getString("object_id");
                            String objectName = dataJson.getString("object_name");

                            //if (page == 1 && i==0) { //如果页数为1，删除原来的数据
                            //    KuaishouOperationRecord recordDelete = new KuaishouOperationRecord();
                            //    recordDelete.setStatDate(startDate);//按天删除记录
                            //    recordDelete.setAccountId(advertiserId);
                            //    //recordDelete.setOperationTime(operationTime);
                            //    //recordDelete.setOperationType(operationType);
                            //    //recordDelete.setRoleType(roleType);
                            //    //recordDelete.setObjectName(objectName);
                            //    //recordDelete.setOperationTarget(operationTarget);
                            //    //recordDelete.setObjectId(objectId);
                            //    operationRecordDelete(recordDelete,operationTarget);
                            //}

                            String contentLogArrayString =  dataJson.getString("content_log");

                            //int jsize =  contentLogArray.size();
                            //for(int j=0; j<jsize;j++){
                            //    JSONObject log = contentLogArray.getJSONObject(j);

                                KuaishouOperationRecord record = new KuaishouOperationRecord();
                                record.setAccountId(advertiserId);
                                record.setStatDate(DateUtils.formatDate(operationTime));
                                record.setOperationTime(operationTime);
                                record.setOperationType(operationType);
                                record.setRoleType(roleType);
                                record.setObjectName(objectName);
                                record.setOperationTarget(operationTarget);
                                record.setObjectId(objectId);
                                record.setLog(contentLogArrayString);
                                //record.setFieldName(log.getString("field_name"));
                                //record.setOriginalData(log.getString("original_data"));
                                //record.setUpdateData(log.getString("update_data"));

                            recordList.add(record);
                            //}
                        }
                    }
                    if(recordList !=null && recordList.size()!=0){
                        operationRecordInsert(recordList,operationTarget);
                    }

                    Integer totalPage = (totalCount - 1) / pageSize + 1;
                    if (page < totalPage) {
                        getOperationRecordByPage(advertiserId, accessToken, page + 1, pageSize, operationTarget, startDate, endDate);
                    }
                }else{
                    log.error("快手操作记录接口data结果不正确，{} ~ {}, resultJson:{}", startDate, endDate, result);
                }
            }else{
                if(code == 500000){
                    System.out.println("5秒后重试，accountId:"+advertiserId+",日期:"+startDate);
                    try{Thread.sleep(5000);} catch (InterruptedException e){};
                    getOperationRecordByPage(advertiserId, accessToken,page, pageSize, operationTarget, startDate, endDate);
                }else {
                    log.error("快手操作记录接口code返回结果不正确，{} ~ {} resultJson:{}", startDate, endDate, result);
                }
            }
        } else {
            log.error("快手操作记录接口获取地域列表返回结果为空，{} ~ {}, resultJson:{}", startDate, endDate, result);
        }

    }

    private void getOperationRecordByPage2(Long advertiserId, String accessToken, Integer page, Integer pageSize, Integer operationTarget, String startDate, String endDate) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.OPERATION_RECORD;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject json = new JSONObject();
        json.put("advertiser_id", advertiserId);
        json.put("operation_target", operationTarget);
        json.put("page", page);
        json.put("page_size", pageSize);
        json.put("start_date", startDate);
        json.put("end_date", endDate);

        String result = HttpUtils.kuaiShouhttpPostRequest(url, json.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);

        if(!Check.isNull(resultJson)){
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                JSONObject data = resultJson.getJSONObject("data");
                if (!Check.isNull(data)) {
                    List<KuaishouOperationRecord> recordList =  new ArrayList();

                    Integer totalCount = data.getInteger("total_count");
                    JSONArray dataArr = data.getJSONArray("details");
                    for (int i = 0; i < dataArr.size(); i++) {
                        JSONObject dataJson = JSONObject.parseObject(dataArr.get(i).toString());
                        if (!Check.isNull(dataJson)) {

                            Date operationTime = dataJson.getDate("operation_time");
                            //Date operationDate = DateUtils.parseDate()
                            Integer operationType = dataJson.getInteger("operation_type");
                            operationTarget = dataJson.getInteger("operation_target");
                            Integer roleType = dataJson.getInteger("role_type");
                            String objectId = dataJson.getString("object_id");
                            String objectName = dataJson.getString("object_name");



                            String contentLogArrayString =  dataJson.getString("content_log");
                            JSONArray jsonArray = JSONArray.parseArray(contentLogArrayString);
                            for(int j=0;j<jsonArray.size();j++){
                                JSONObject object = jsonArray.getJSONObject(j);
                                String originalData = object.getString("original_data");
                                String updateData = object.getString("update_data");
                                String fieldName = object.getString("field_name");
                                KuaishouOperationRecord record = new KuaishouOperationRecord();
                                record.setAccountId(advertiserId);
                                record.setStatDate(DateUtils.formatDate(operationTime));
                                record.setOriginalData(originalData);
                                record.setUpdateData(updateData);
                                record.setFieldName(fieldName);

                                record.setOperationTime(operationTime);
                                record.setOperationType(operationType);
                                record.setOperationTarget(operationTarget);
                                record.setRoleType(roleType);
                                record.setObjectId(objectId);
                                record.setObjectName(objectName);

                                if("".equals(record.getOriginalData()) && "".equals(record.getUpdateData())){
                                    continue;
                                }
                                recordList.add(record);
                            }

                        }
                    }
                    saveOperationRecordListToDb(recordList);

                    Integer totalPage = (totalCount - 1) / pageSize + 1;
                    if (page < totalPage) {
                        getOperationRecordByPage2(advertiserId, accessToken, page + 1, pageSize, operationTarget, startDate, endDate);
                    }
                }else{
                    log.error("快手操作记录接口data结果不正确，{} ~ {}, resultJson:{}", startDate, endDate, result);
                }
            }else{
                if(code == 500000){
                    System.out.print("》》5秒后重试，accountId:"+advertiserId+",日期:"+startDate+"《《 ");
                    try{Thread.sleep(5000);} catch (InterruptedException e){};
                    getOperationRecordByPage2(advertiserId, accessToken,page, pageSize, operationTarget, startDate, endDate);
                }else {
                    log.error("快手操作记录接口code返回结果不正确，{} ~ {} resultJson:{}", startDate, endDate, result);
                }
            }
        } else {
            log.error("快手操作记录接口获取地域列表返回结果为空，{} ~ {}, resultJson:{}", startDate, endDate, result);
        }

    }

    private void operationRecordDelete(KuaishouOperationRecord recordDelete, Integer operationTarget){
        if(operationTarget == 1){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoAccount(recordDelete);
        }else if(operationTarget == 2){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoCampaign(recordDelete);
        }else if(operationTarget == 3){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoUnit(recordDelete);
        }else if(operationTarget == 4){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoCreative(recordDelete);
        }else if(operationTarget == 5){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoVideo(recordDelete);
        }else if(operationTarget == 6){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoApp(recordDelete);
        }else if(operationTarget == 7){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoPackage(recordDelete);
        }
    }

    private void operationRecordInsert(List<KuaishouOperationRecord> recordList, Integer operationTarget){
        if(operationTarget == 1){
            kuaishouOperationRecordMapper.insertOperationRecordInfoAccount(recordList);
        }else if(operationTarget == 2){
            kuaishouOperationRecordMapper.insertOperationRecordInfoCampaign(recordList);
        }else if(operationTarget == 3){
            kuaishouOperationRecordMapper.insertOperationRecordInfoUnit(recordList);
        }else if(operationTarget == 4){
            kuaishouOperationRecordMapper.insertOperationRecordInfoCreative(recordList);
        }else if(operationTarget == 5){
            kuaishouOperationRecordMapper.insertOperationRecordInfoVideo(recordList);
        }else if(operationTarget == 6){
            kuaishouOperationRecordMapper.insertOperationRecordInfoApp(recordList);
        }else if(operationTarget == 7){
            kuaishouOperationRecordMapper.insertOperationRecordInfoPackage(recordList);
        }
    }

    private void saveOperationRecordListToDb(List<KuaishouOperationRecord> records) {
        if (Check.isNull(records)) {
            return;
        }

        List<KuaishouOperationRecord> batchList = new ArrayList<>();
        records.removeAll(Collections.singleton(null));
        Integer operationTarget = records.get(0).getOperationTarget();



        for (KuaishouOperationRecord sumPosition : records) {
            batchList.add(sumPosition);

            if (batchList.size() >= 1000) {
                if (operationTarget == 1) {
                    kuaishouOperationRecordMapper.insertOperationRecordInfoAccountNew(batchList);
                } else if (operationTarget == 2) {
                    kuaishouOperationRecordMapper.insertOperationRecordInfoCampaignNew(batchList);
                } else if (operationTarget == 3) {
                    kuaishouOperationRecordMapper.insertOperationRecordInfoUnitNew(batchList);
                } else if (operationTarget == 4) {
                    kuaishouOperationRecordMapper.insertOperationRecordInfoCreativeNew(batchList);
                } else if (operationTarget == 5) {
                    kuaishouOperationRecordMapper.insertOperationRecordInfoVideoNew(batchList);
                } else if (operationTarget == 6) {
                    kuaishouOperationRecordMapper.insertOperationRecordInfoAppNew(batchList);
                } else if (operationTarget == 7) {
                    kuaishouOperationRecordMapper.insertOperationRecordInfoPackageNew(batchList);
                } else {
                    System.out.println("未知的目标类型！");
                }
                batchList.clear();
            }
        }
        if (!batchList.isEmpty()) {

            if (operationTarget == 1) {
                kuaishouOperationRecordMapper.insertOperationRecordInfoAccountNew(batchList);
            } else if (operationTarget == 2) {
                kuaishouOperationRecordMapper.insertOperationRecordInfoCampaignNew(batchList);
            } else if (operationTarget == 3) {
                kuaishouOperationRecordMapper.insertOperationRecordInfoUnitNew(batchList);
            } else if (operationTarget == 4) {
                kuaishouOperationRecordMapper.insertOperationRecordInfoCreativeNew(batchList);
            } else if (operationTarget == 5) {
                kuaishouOperationRecordMapper.insertOperationRecordInfoVideoNew(batchList);
            } else if (operationTarget == 6) {
                kuaishouOperationRecordMapper.insertOperationRecordInfoAppNew(batchList);
            } else if (operationTarget == 7) {
                kuaishouOperationRecordMapper.insertOperationRecordInfoPackageNew(batchList);
            } else {
                System.out.println("未知的目标类型！");
            }
            batchList.clear();
        }

    }





}
