package easydo.technology.service;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import easydo.technology.exception.BizException;
import easydo.technology.model.vo.GLDContract;
import easydo.technology.util.HttpClientUtil;
import easydo.technology.utils.StringUtil;
import lombok.extern.java.Log;

@Log
@Component
public class GLDCostService {
    @Value("${tenantId_gld_cost}")
    String tenantId;
    @Value("${GLD.host}")
    String costHost;
    @Value("${GLD.COST.getPath}")
    String costGetPath;
    @Value("${GLD.COST.authorization}")
    String costAuthorization;
    @Value("${GLD.COST.updatePath}")
    String costUpdatePath;
    @Value("${GLD.COST.getContractPath}")
    String costContractPath;
    @Value("${GLD.COST.contractFile}")
    String costContractFile;

    public JSONObject getHY(List<String> projectCodeList) {
        JSONObject data = new JSONObject();
        if (projectCodeList.isEmpty()) {
            throw new BizException("参数缺失");
        }
        data.put("projectCodes", projectCodeList);
        String url = costHost + costGetPath;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", costAuthorization);
        header.put("X-CORAL-TENANT", tenantId);
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "查询合约规划合约视角req========>" + data.toJSONString() + ",url========>" + url);
        JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(url, data.toJSONString(), header);
        log.info(uuid + "查询合约规划合约视角res========>" + resObj.toJSONString());
        return resObj;
    }

    public JSONObject getKM(List<String> projectCodeList) {
        JSONObject data = new JSONObject();

        if (StringUtil.isEmpty(tenantId) || projectCodeList.isEmpty()) {
            throw new BizException("参数缺失");
        }
        data.put("projectCodes", projectCodeList);
        data.put("contractPlanMode", "Index");
        String url = costHost + costGetPath;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", costAuthorization);
        header.put("X-CORAL-TENANT", tenantId);
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "查询合约规划科目视角req========>" + data.toJSONString() + ",url========>" + url);
        JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(url, data.toJSONString(), header);
        log.info(uuid + "查询合约规划科目视角res========>" + resObj.toJSONString());
        return resObj;
    }

    public void updateState(Long contractPlanId, String useState) {
        JSONObject data = new JSONObject();
        List<Long> contractPlanIds = new ArrayList<>();
        contractPlanIds.add(contractPlanId);
        data.put("contractPlanItemIds", contractPlanIds);
        data.put("useState", useState);
        String url = costHost + costUpdatePath;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", costAuthorization);
        header.put("X-CORAL-TENANT", tenantId);
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "修改合约规划状态req========>" + data.toJSONString() + ",url========>" + url);
        JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(url, data.toJSONString(), header);
        log.info(uuid + "修改合约规划状态res========>" + resObj.toJSONString());
        if (!"success".equals(resObj.getString("code"))) {
            throw new BizException("修改合约规划状态异常");
        }
    }

    public List<GLDContract> getContractList(Long projectId, String purchaseNo) {
        JSONObject data = new JSONObject();
        data.put("projectId", projectId);
        // data.put("projectCode", projectCode);
        data.put("procurementApprovalCode", purchaseNo);
        data.put("queryDetail", true);
        String url = costHost + costContractPath;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", costAuthorization);
        header.put("X-CORAL-TENANT", tenantId);
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "查询合同信息req========>" + data.toJSONString() + ",url========>" + url);
        JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(url, data.toJSONString(), header);
        log.info(uuid + "查询合同信息res========>" + resObj.toJSONString());
        JSONArray array = resObj.getJSONArray("data");
        List<GLDContract> list = new ArrayList<>();
        for (Object obj : array) {
            JSONObject object = (JSONObject) obj;

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (object.containsKey("createTime")) {
                long createTimeSeconds = object.getLongValue("createTime");
                Date date = new Date(createTimeSeconds);
                String createTime = sdf.format(date);
                object.put("createTime", createTime);
            }
            if (object.containsKey("approvedEndTime")) {
                long approvedEndTimeSeconds = object.getLongValue("approvedEndTime");
                Date date = new Date(approvedEndTimeSeconds);
                String approvedEndTime = sdf.format(date);
                object.put("approvedEndTime", approvedEndTime);
            }
            GLDContract contract = JSONObject.parseObject(object.toJSONString(), GLDContract.class);

            JSONArray attachmentInfoList = object.getJSONArray("extAttachmentInfoList");
            for (Object attach : attachmentInfoList) {
                JSONObject attachObj = (JSONObject) attach;
                contract.setObjectId(attachObj.getString("objectId"));
                contract.setFileName(attachObj.getString("name"));
                list.add(contract);
            }
        }
        return list;
    }

    public void getContractFile(String objectId, String fileName, HttpServletRequest request, HttpServletResponse response) {
        String url = costHost + costContractFile + objectId;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", costAuthorization);
        header.put("X-CORAL-TENANT", tenantId);
        if (StringUtil.isEmpty(fileName)) {
            fileName = "contract.pdf";
        }
        HttpClientUtil.sendGETWithHeader_OutputStream(url, header, request, response, fileName);
    }

    // public static void main(String[] args) {
    // JSONObject data = new JSONObject();
    // data.put("projectId", "840608311945216");
    // data.put("procurementApprovalCode", "ZCCP-20240129191729593");
    // data.put("queryDetail", true);
    // String url =
    // "http://jsf-int.glodon.com/cost-management/openapi/contracts/list";
    // Map<String, String> header = new HashMap<>();
    // header.put("Authorization",
    // "Basic
    // a0ZkMkE4UkhSM1l1ZlplQ1lVUGNjVWFMblJWQW5ZZ1c6VTJNakoycVZiaGNVYlI5VlVyUUdYeVFQekp1WkdoNm4=");
    // header.put("X-CORAL-TENANT", "865509948108800");
    // JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(url,
    // data.toJSONString(), header);
    // // log.info("查询合同信息req========>" + data.toJSONString() +
    // "res========>" + resObj.toJSONString());

    // JSONArray array = resObj.getJSONArray("data");
    // List<GLDContract> list = new ArrayList<>();
    // for (Object obj : array) {
    // JSONObject object = (JSONObject) obj;

    // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // if (object.containsKey("createTime")) {
    // long createTimeSeconds = object.getLongValue("createTime");
    // Date date = new Date(createTimeSeconds);
    // String createTime = sdf.format(date);
    // object.put("createTime", createTime);
    // }
    // if (object.containsKey("approvedEndTime")) {
    // long approvedEndTimeSeconds = object.getLongValue("approvedEndTime");
    // Date date = new Date(approvedEndTimeSeconds);
    // String approvedEndTime = sdf.format(date);
    // object.put("approvedEndTime", approvedEndTime);
    // }
    // JSONObject contractObj =
    // (JSONObject)object.getJSONArray("contractDetailedList").get(0);

    // GLDContract contract = JSONObject.parseObject(object.toJSONString(),
    // GLDContract.class);
    // contract.setObjectId(contractObj.getString("objectId"));
    // list.add(contract);
    // }
    // log.info(JSONArray.toJSONString(list));
    // }


    public static void main(String[] args) {
        JSONObject data = new JSONObject();
        data.put("projectId", "11200363");
        // data.put("projectCode", projectCode);
        data.put("procurementApprovalCode", "ZCPU2024092300001");
        data.put("queryDetail", true);
        String url = "http://218.201.101.181:14780" + "/cost-management/openapi/contracts/list";
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "Basic a0ZkMkE4UkhSM1l1ZlplQ1lVUGNjVWFMblJWQW5ZZ1c6VTJNakoycVZiaGNVYlI5VlVyUUdYeVFQekp1WkdoNm4=");
        header.put("X-CORAL-TENANT", "5600003");
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "查询合同信息req========>" + data.toJSONString() + ",url========>" + url);
        JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(url, data.toJSONString(), header);
        log.info(uuid + "查询合同信息res========>" + resObj.toJSONString());
    }
}