package easydo.technology.controller;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.alibaba.fastjson.JSONObject;
import easydo.technology.exception.BizException;
import easydo.technology.model.*;
import easydo.technology.model.vo.GLDContract;
import easydo.technology.service.GLDCostService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import easydo.technology.annotation.WebLog;
import easydo.technology.components.JdbcClient;
import easydo.technology.service.GLDMasterService;
import easydo.technology.util.HttpClientUtil;
import easydo.technology.utils.RedisUtils;
import easydo.technology.utils.StringUtil;
import lombok.extern.java.Log;

@Log
@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    DataSource dataSource;
    @Resource
    JdbcClient jdbcClient;
    @Resource
    GLDMasterService gldMasterService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    RedisUtils redisUtils;
    @Resource
    GLDCostService gldCostService;

    /*
     * public static void main(String[] args) {
     * String url = "http://218.201.101.181:14780/tenant/v2/tenants?size=20000";
     * String auth =
     * "Basic YlFvc0tIeWJkSlZUZGtMcXA0U1VIMlE0ejNZQjc5eVA6b1ZmaU5zR1c1NVZzSW5ITTlDOVI3c2g0SHlpVGMxY2w="
     * ;
     * String token = "cn-b3c73fac-2629-4337-94fb-e79c289d1979";
     * String tenantId = "5600001";
     * 
     * JSONObject object = HttpClientUtil.sendGLDGET_getTenantId(url, token);
     * log.info(object.toJSONString());
     * //{"access_token":"cn-b3c73fac-2629-4337-94fb-e79c289d1979","scope":
     * "paas-clouddoc,paas-gdoc_tenant,paas-new-storage-service_admin,paas-organization_admin,paas-gws_tenant,paas-organization_tenant,paas-comment-service_tenant,paas-databag_tenant,paas-new-storage-service_tenant,paas-databag_admin,paas_databag_tenant,paas-raw-storage-service_tenant"
     * ,"token_type":"bearer","exp":1723342092,"expires_in":74670}
     * }
     */

    // public static void main(String[] args) {
    // String url =
    // "http://218.201.101.181:14780/flow-app-local/v4/flow-definitions/query-for-start?formId=flow/STD_Dcm_PROCUREMENT_SYSTEM&mgtGroupId=11200297";
    // Map<String, String> header = new HashMap<>();
    // header.put("Authorization",
    // "Basic
    // YlFvc0tIeWJkSlZUZGtMcXA0U1VIMlE0ejNZQjc5eVA6b1ZmaU5zR1c1NVZzSW5ITTlDOVI3c2g0SHlpVGMxY2w=");
    // header.put("x-tenant-id", "5600003");

    // JSONArray resObject = HttpClientUtil.sendGETWithHeader_Arr(url, header);
    // log.info(resObject.toJSONString());
    // }

    /*
     * public static void main(String[] args) {
     * // String url =
     * "http://218.201.101.181:8180/seeyon/thirdpartyController.do?ticket=-5127817351537210703";
     * // String username = HttpClientUtil.sendOaGET_USERNAME(url);
     * // log.info(username);
     * 
     * String url = "http://218.201.101.181:8180/seeyon/rest/token";
     * JSONObject object = new JSONObject();
     * object.put("userName", "zcxt");
     * object.put("password", "2679fc6b-df18-4563-9b8e-773b59bdcb62");
     * JSONObject resObject = HttpClientUtil.sendPOST(url, object.toJSONString());
     * String accessToken = resObject.getString("id");
     * log.info(accessToken);
     * 
     * String getUserInfoUrl =
     * "http://218.201.101.181:8180/seeyon/rest/orgMember?loginName=guanglianda";
     * Map<String, String> header = new HashMap<>();
     * header.put("token", accessToken);
     * // header.put("Authorization", "Bearer " + accessToken);
     * JSONObject resObj = HttpClientUtil.sendGETWithHeader_Obj(getUserInfoUrl,
     * header);
     * log.info(resObj);
     * }
     */

    @WebLog
    @RequestMapping(value = "/getPage")
    public Object getPage() throws Exception {
        Connection connection = null;
        Map<String, Object> map = new HashMap<>();
        try {
            connection = dataSource.getConnection();
//            connection.setAutoCommit(false);
            map.put("isHaveContract", 0);
            map.put("projectIdBegin", 1);
            List<Purchase> list = jdbcClient.getJdbcList(map, Purchase.class, connection);
            for (Purchase model : list) {
                List<GLDContract> contractList = gldCostService.getContractList(model.getProjectId(),
                        model.getPurchaseNo());
                if (!contractList.isEmpty()) {
                    PurchaseBidNotice bidNotice = new PurchaseBidNotice();
                    bidNotice.setPurchaseId(model.getId());
                    bidNotice = jdbcClient.getJdbcModel(bidNotice, connection);
                    Supplier supplier = new Supplier();
                    supplier.setId(bidNotice.getBidCompanyIds());
                    supplier = jdbcClient.getJdbcModel(supplier, connection);

                    for (GLDContract contract : contractList) {
                        PurchaseContract purchaseContract = new PurchaseContract();
                        purchaseContract.setPurchaseId(model.getId());
                        purchaseContract.setProjectId(model.getProjectId());
                        purchaseContract.setContractName(contract.getName());
                        purchaseContract.setContractNo(contract.getCode());
                        purchaseContract.setSignAmount(contract.getTaxAmount());
                        purchaseContract.setCreateTime(contract.getCreateTime());
                        purchaseContract.setEndTime(contract.getApprovedEndTime());
                        purchaseContract.setObjectId(contract.getObjectId());
                        purchaseContract.setFileName(contract.getFileName());
                        purchaseContract.setSupplierId(supplier.getId());
                        purchaseContract.setSupplierName(supplier.getSupplierName());
                        purchaseContract.setSupplierNo(supplier.getSupplierNo());
                        jdbcClient.jdbcInsert(purchaseContract, connection);
                    }
                    model.setIsHaveContract(true);
                    jdbcClient.jdbcUpdateById(model, connection);
                }
            }

//            connection.commit();
        } catch (Exception e) {
//            connection.commit();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
        return "success";
    }

    @WebLog
    @RequestMapping(value = "/getPassword")
    public Object getPage(@RequestBody SysUser user) throws Exception {
//        redisUtils.set("test", "123456", 600);
//        log.info(redisUtils.get("test").toString());
//        if(true){
//            throw new BizException("122345678");
//        }
        JSONObject object = new JSONObject();
        object.put("password", passwordEncoder.encode(user.getUsername()));
        return object;
    }

    @WebLog
    @GetMapping(value = "/test")
    public void test(HttpServletResponse response, HttpServletRequest request, @RequestParam String objectId,
            @RequestParam(required = false) String fileName) throws Exception {
        String url = "http://jsf-int.glodon.com/cost-management/openapi/attachments/" + objectId;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization",
                "Basic a0ZkMkE4UkhSM1l1ZlplQ1lVUGNjVWFMblJWQW5ZZ1c6VTJNakoycVZiaGNVYlI5VlVyUUdYeVFQekp1WkdoNm4=");
        header.put("X-CORAL-TENANT", "865509948108800");
        if (StringUtil.isEmpty(fileName)) {
            fileName = "contract.pdf";
        }
        HttpClientUtil.sendGETWithHeader_OutputStream(url, header, request, response, fileName);

    }

    // public static void main(String[] args) {
    // String creationDate = LocalDateUtil.localDateTimeFormat(LocalDateTime.now(),
    // "yyyy-MM-dd HH:mm");
    // String creationDate2 = LocalDateUtil.localDateTimeFormat(LocalDateTime.now(),
    // "yyyy-MM-dd HH:mm:ss");

    // String url = "http://218.201.101.181:8180" + "/seeyon/rest/token";
    // JSONObject object = new JSONObject();
    // object.put("userName", "zcxt");
    // object.put("password", "2679fc6b-df18-4563-9b8e-773b59bdcb62");
    // JSONObject resObject = HttpClientUtil.sendPOST(url, object.toJSONString());
    // log.info("查询OAtoken的res======>" + resObject.toJSONString());
    // String token = resObject.getString("id");

    // Map<String, String> header = new HashMap<>();
    // header.put("token", token);

    // String sendTodoUrl = "http://218.201.101.181:8180" +
    // "/seeyon/rest/thirdpartyPending/receive?token=" + token;
    // object = new JSONObject();
    // object.put("registerCode", "3007");
    // object.put("taskId", "4e12f28b-8e15-4f82-afbf-59dd0b083394");
    // object.put("title", "供应商评价");
    // object.put("senderName", "guanglianda");
    // object.put("classify", "招采系统");
    // object.put("contentType", "招采系统");
    // object.put("state", 0);
    // object.put("thirdSenderId", "");
    // object.put("thirdReceiverId", "");
    // object.put("creationDate", creationDate);
    // object.put("content", "");
    // object.put("h5url", "");
    // object.put("url", "http://172.16.1.150:8810/purchase/getDetail?"
    // +
    // "type=supplier_evaluate&path=supplier-evaluation-detail&businessId=d0ff0a8b-54bf-4351-ad8d-e7cd26fc181e");
    // object.put("noneBindingSender", "guanglianda");
    // object.put("noneBindingReceiver", "guanglianda");

    // JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(sendTodoUrl,
    // object.toJSONString(), header);
    // log.info("生成OA待办req======>" + object.toJSONString() + ",res======>"
    // + resObj.toJSONString());

    // String updateTodoUrl = "http://218.201.101.181:8180" +
    // "/seeyon/rest/thirdpartyPending/updatePendingState?token=" + token;
    // object = new JSONObject();
    // object.put("registerCode", "3007");
    // object.put("taskId","4e12f28b-8e15-4f82-afbf-59dd0b083394" );
    // object.put("state",1 );
    // object.put("subState",2 );
    // JSONObject resObj =
    // HttpClientUtil.sendPOSTWithHeader(updateTodoUrl,object.toJSONString(),
    // header);
    // log.info("更新OA待办req======>" + object.toJSONString() + ",res======>"
    // + resObj.toJSONString());

    // String sendMessageUrl = "http://218.201.101.181:8180" +
    // "/seeyon/rest/thirdpartyMessage/receive/singleMessage?token=" + token;
    // object = new JSONObject();
    // object.put("thirdpartyRegisterCode", "3007");
    // object.put("thirdpartyMessageId", "1");
    // object.put("messageContent", "您有一条待测试的消息。");
    // object.put("thirdpartyReceiverId", 0);
    // object.put("creation_date", creationDate2);

    // object.put("noneBindingSender", "guanglianda");
    // object.put("noneBindingReceiver", "guanglianda");

    // JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(sendMessageUrl,
    // object.toJSONString(), header);
    // log.info("推送OA消息req======>" + object.toJSONString() + ",res======>"
    // + resObj.toJSONString());
    // }

}