package easydo.technology.service;

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

import javax.annotation.Resource;
import javax.sql.DataSource;

import easydo.technology.model.ApproveInfo;
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.components.JdbcClient;
import easydo.technology.model.GldMember;
import easydo.technology.model.SysUser;
import easydo.technology.model.vo.GLDApproveVo;
import easydo.technology.util.HttpClientUtil;
import easydo.technology.utils.SecurityUtils;
import lombok.extern.java.Log;

@Log
@Component
public class GLDApproveService {
    @Value("${tenantId_gld_master}")
    String tenantId;
    @Value("${GLD.APPROVE.mgtGroupId}")
    String mgtGroupId;
    @Value("${GLD.APPROVE.authorization}")
    String authorization;
    @Value("${GLD.host}")
    String host;
    @Value("${GLD.APPROVE.startApprove}")
    String startApprove;
    @Value("${GLD.APPROVE.getApproveInfo}")
    String getApproveInfo;
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;

    public String startApprove(GLDApproveVo vo) throws Exception {

        Long userId = SecurityUtils.getCurrentUserId();
        GldMember member = new GldMember();
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            SysUser user = new SysUser();
            user.setUserId(userId);
            user = jdbcClient.getJdbcModel(user, connection);

            member.setPhone(user.getPhone());
            member = jdbcClient.getJdbcModel(member, connection);

            ApproveInfo approveInfo = new ApproveInfo();
            approveInfo.setBusType(vo.getTargetType());
            approveInfo = jdbcClient.getJdbcModel(approveInfo, connection);
            vo.setStartPos(approveInfo.getFormCode());
            vo.setStartPosName(approveInfo.getFormName());

        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }

        String url = (host + startApprove).replace("{deptId}", mgtGroupId);
        Map<String, String> header = new HashMap<>();
        header.put("X-CORAL-TENANT", tenantId);
        header.put("Authorization", authorization);
        JSONObject object = new JSONObject();
        object.put("subject", "startPosName");
        object.put("startPos", vo.getStartPos());
        object.put("startPosName", vo.getStartPosName());
        object.put("templateId", vo.getTemplateId());
        object.put("targetType", vo.getTargetType());
//        object.put("targetId", vo.getTargetId());
        object.put("taskType", "APPROVAL");
        object.put("hiddenResubmit", true);
        object.put("startorId", member.getUserId());
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "发起审批流req========>" + object.toJSONString() + ",url========>" + url);
        JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(url, object.toJSONString(), header);
        log.info(uuid + "发起审批流res========>" + resObj.toJSONString());
        return resObj.getString("id");
    }

    public String restartApprove(GLDApproveVo vo) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        GldMember member = new GldMember();
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            SysUser user = new SysUser();
            user.setUserId(userId);
            user = jdbcClient.getJdbcModel(user, connection);
            member.setPhone(user.getPhone());
            member = jdbcClient.getJdbcModel(member, connection);

            ApproveInfo approveInfo = new ApproveInfo();
            approveInfo.setBusType(vo.getTargetType());
            approveInfo = jdbcClient.getJdbcModel(approveInfo, connection);
            vo.setStartPos(approveInfo.getFormCode());
            vo.setStartPosName(approveInfo.getFormName());

        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }

        String url = (host + startApprove).replace("{deptId}", mgtGroupId);
        Map<String, String> header = new HashMap<>();
        header.put("X-CORAL-TENANT", tenantId);
        header.put("Authorization", authorization);
        JSONObject object = new JSONObject();
        object.put("subject", "startPosName");
        object.put("startPos", vo.getStartPos());
        object.put("startPosName", vo.getStartPosName());
        object.put("templateId", vo.getTemplateId());
        object.put("targetType", vo.getTargetType());
//        object.put("targetId", vo.getTargetId());
        object.put("taskType", "APPROVAL");
        object.put("hiddenResubmit", true);
        object.put("startorId", member.getUserId());
        object.put("resubmitTaskId", vo.getTaskId());
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "重新发起审批流req========>" + object.toJSONString() + ",url========>" + url);
        JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(url, object.toJSONString(), header);
        log.info(uuid + "重新发起审批流res========>" + resObj.toJSONString());
        return resObj.getString("id");
    }

    public GLDApproveVo getApproveInfo(GLDApproveVo vo) {
        String url = host + getApproveInfo.replace("{deptId}", mgtGroupId)
                .replace("{ids}", vo.getTaskId());
        Map<String, String> header = new HashMap<>();
        header.put("X-CORAL-TENANT", tenantId);
        header.put("Authorization", authorization);
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "查询审批流url========>" + url);
        JSONArray resArray = HttpClientUtil.sendGETWithHeader_Arr(url, header);
        log.info(uuid + "查询审批流res========>" + resArray.toJSONString());
        if (resArray.size() > 0) {
            String instanceId = ((JSONObject) resArray.get(0)).getString("xmglInstanceId");
            String state = ((JSONObject) resArray.get(0)).getString("state");
            vo.setInstanceId(instanceId);
            vo.setState(state);
        }
        return vo;
    }

    public static void main(String[] args) {
//        String url = "http://218.201.101.181:14780/task/tasks?targetId=89bfac89-7fd5-4c1f-a386-f2f36efafb1d&targetType=purchase_plan";
        String url = "http://218.201.101.181:14780/task/11200297/tasks?ids=22175528771584&taskType=APPROVAL";
        Map<String, String> header = new HashMap<>();
        header.put("X-CORAL-TENANT", "5600003");
        header.put("Authorization", "Basic YlFvc0tIeWJkSlZUZGtMcXA0U1VIMlE0ejNZQjc5eVA6b1ZmaU5zR1c1NVZzSW5ITTlDOVI3c2g0SHlpVGMxY2w=");
        JSONArray resArray = HttpClientUtil.sendGETWithHeader_Arr(url, header);
        log.info("查询审批流res========>" + resArray.toJSONString());
    }
}
