package com.santos.iost.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.santos.iost.Exception.SoSsRequestException;
import com.santos.iost.dao.SoSsDao;
import com.santos.iost.dto.Result;
import com.santos.iost.dto.SoSsResponseDate;
import com.santos.iost.service.*;
import com.santos.iost.utils.HttpUtil;
import com.santos.iost.utils.StringUtil;
import com.santos.iost.vo.SoSsCreateVo;
import com.santos.iost.vo.SoSsRequestVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 第三方通用接口
 * @Author: jeecg-boot
 * @Date: 2021-12-02
 * @Version: V1.0
 */
@RestController
//@RequestMapping("/api")
@Slf4j
public class WebApi {
    @Autowired
    SoSsMaterialService materialService;
    @Autowired
    SpSsSalesOrderService salesOrderService;
    @Autowired
    SoSsSalesDeliveryService salesDeliveryService;
    @Autowired
    SoSsSalesInvoiceService salesInvoiceService;
    @Autowired
    SoSsReceiptService receiptService;
    @Autowired
    SoSsCustomerService customerService;

    @ApiOperation(value = "查询通用接口", notes = "查询通用接口")
    @PostMapping(value = "/create")
    public Result<?> SetData(SoSsCreateVo soSsCreateVo) throws Exception {
        Result result = new Result();
        try {
            if (null == soSsCreateVo.getObjAPIName()) {
                return Result.fail("操作失败", "objAPIName不可为空", "500");
            } else if (soSsCreateVo.getObjAPIName().equals(customerService.apiName)) {
                result = customerService.setData(soSsCreateVo);//产品
            } else {
                return Result.fail("操作失败", soSsCreateVo.getObjAPIName() + "不存在", "406");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation(value = "查询通用接口", notes = "查询通用接口")
    @GetMapping(value = "/queryMasterBatch")
    public Result<?> GetData(SoSsRequestVo soSsRequestVo) throws Exception {
        checkRequest(soSsRequestVo);
        Result result = new Result();
        try {
            if (null == soSsRequestVo.getObjAPIName()) {
                return Result.fail("操作失败", "objAPIName不可为空", "500");
            } else if (soSsRequestVo.getObjAPIName().equals(materialService.apiName)) {
                result = materialService.getData(soSsRequestVo);//产品
            } else if (soSsRequestVo.getObjAPIName().equals(salesOrderService.apiName)) {
                result = salesOrderService.getData(soSsRequestVo);//订单
            } else if (soSsRequestVo.getObjAPIName().equals(salesDeliveryService.apiName)) {
                result = salesDeliveryService.getData(soSsRequestVo);//发货单
            } else if (soSsRequestVo.getObjAPIName().equals(salesInvoiceService.apiName)) {
                result = salesInvoiceService.getData(soSsRequestVo);//开票
            } else if (soSsRequestVo.getObjAPIName().equals(receiptService.apiName)) {
                result = receiptService.getData(soSsRequestVo);//回款
            } else {
                return Result.fail("操作失败", soSsRequestVo.getObjAPIName() + "不存在", "406");
            }

        } finally {
        }
        return result;
    }

    //检查ERM日期是否可用作过滤条件
    void checkRequest(SoSsRequestVo soSsRequestVo) {
//        时间字段检查
        if (null == soSsRequestVo.getStartTime() && null == soSsRequestVo.getEndTime()) {
        } else if (null == soSsRequestVo.getStartTime() || null == soSsRequestVo.getEndTime()) {
            throw new SoSsRequestException("操作失败!", "起止时间为空", "500");
        } else if (StringUtil.isNumber(soSsRequestVo.getStartTime()) && StringUtil.isNumber(soSsRequestVo.getEndTime())) {
            if (Integer.parseInt(soSsRequestVo.getStartTime()) > Integer.parseInt(soSsRequestVo.getEndTime()))
                throw new SoSsRequestException("操作失败!", "开始时间大于结束时间", "500");
        } else {
            throw new SoSsRequestException("操作失败!", "startTime以及endTime字段请使用 unix 时间戳填写,单位毫秒", "500");
        }

//分页用字段检查
        if (null == soSsRequestVo.getLimit()) {
            throw new SoSsRequestException("操作失败!", "limit不允许为空", "201");
        }
        if (soSsRequestVo.getLimit() <= 0) {
            throw new SoSsRequestException("操作失败!", "limit不可小于或等于0", "201");
        }
    }

    public static String TimeStamp2Date(String timestampString, String formats) {
        if (TextUtils.isEmpty(formats))
            formats = "yyyy-MM-dd HH:mm:ss";
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
        return date;
    }

    /*List<Map<String,Object>>转换Map<String,Object>*/
    public Map<String, Object> change(List<Map<String, Object>> data) {
        Map<String, Object> maps = new HashMap<>();
        for (Map<String, Object> datum : data) {
            for (String s : datum.keySet()) {
                maps.put(s, datum.get(s));
            }
        }
        return maps;
    }


    ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator
                    (response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase
                        ("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 60 * 1000;//如果没有约定，则默认定义时长为60s
        }
    };
}
