package easydo.technology.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

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

import easydo.technology.model.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import easydo.technology.components.JdbcClient;
import easydo.technology.enums.ChengfaEnum;
import easydo.technology.exception.BizException;
import easydo.technology.system.domain.SysDept;
import easydo.technology.utils.StringUtil;
import lombok.extern.java.Log;

@Log
@Component
@Profile({"prod", "test"})
public class KafkaClient {
    private final static String DONE_STATUS = "'done'";
    private final static String NULL_STATUS = "null";
    private final static String ACTIVE_STATUS = "'active'";
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;
    @Resource
    GLDCostService gldCostService;
    @Value("${PURCHASE.redirectUrl}")
    String redirectUrl;
    @Value("${PURCHASE.purchasePath}")
    String purchasePath;

    @KafkaListener(topics = {"task_prod"}) // 在这里指定要监听的topic，可以监听多个
    public void listenToMessage(String message) throws Exception{
        JSONObject object = JSONObject.parseObject(message);
        String topic = object.getJSONObject("eventData").getString("topic");
        JSONObject taskSimpleInfo = object.getJSONObject("eventData").getJSONObject("taskSimpleInfo");
        String taskId = taskSimpleInfo.getString("id");
        String state = taskSimpleInfo.getString("state");
        String targetType = taskSimpleInfo.getString("targetType");
        log.info("zcxt listener======>" + object);

        if (!(ChengfaEnum.APPROVE_STATE_ENDED.getValue().equals(state)
                && ChengfaEnum.APPROVE_TOPIC_ENDED.getValue().equals(topic))
                && !(ChengfaEnum.APPROVE_STATE_STOP.getValue().equals(state)
                && ChengfaEnum.APPROVE_TOPIC_STOPPED.getValue().equals(topic))
                && !(ChengfaEnum.APPROVE_STATE_UNSTARTED.getValue().equals(state)
                && ChengfaEnum.APPROVE_TOPIC_REJECTED.getValue().equals(topic))) {
            return;
        }
        if (!ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_PLAN.getValue().equals(targetType)
                && !ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE.getValue().equals(targetType)
                && !ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_MATTER.getValue().equals(targetType)
                && !ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_BID_SIGN.getValue().equals(targetType)
                && !ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_ANSWER_SIGN.getValue().equals(targetType)
                && !ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_BID_NOTICE.getValue().equals(targetType)) {
            return;
        }
        Connection connection = null;
        Statement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();

            if (ChengfaEnum.APPROVE_STATE_ENDED.getValue().equals(state)
                    && ChengfaEnum.APPROVE_TOPIC_ENDED.getValue().equals(topic)) {
                executeSql(statement, targetType, taskId, DONE_STATUS, state, connection);
            }
            if (ChengfaEnum.APPROVE_STATE_STOP.getValue().equals(state)
                    && ChengfaEnum.APPROVE_TOPIC_STOPPED.getValue().equals(topic)) {
                executeSql(statement, targetType, taskId, NULL_STATUS, state, connection);
            }
            if (ChengfaEnum.APPROVE_STATE_UNSTARTED.getValue().equals(state)
                    && ChengfaEnum.APPROVE_TOPIC_REJECTED.getValue().equals(topic)) {
                executeSql(statement, targetType, taskId, ACTIVE_STATUS, state, connection);
            }

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

    private void executeSql(Statement statement, String tableName, String taskId, String status, String state,
                            Connection connection) throws Exception {
        String sql = "update " + tableName + " set status = " + status + ",process_state = '" + state
                + "' where process_task_id = " + taskId;
        statement.executeUpdate(sql);
        if (!ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE.getValue().equals(tableName)
                && !ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_PLAN.getValue().equals(tableName)) {
            sql = "select purchase_id from " + tableName + " where process_task_id = " + taskId;
            ResultSet resultSet = statement.executeQuery(sql);
            String purchaseId = "";
            while (resultSet.next()) {
                purchaseId = resultSet.getString(1);
            }
            sql = "update purchase set status = " + status + " where id = '" + purchaseId + "'";
            statement.executeUpdate(sql);
        }
        if (DONE_STATUS.equals(status)) {
            sql = "select id from " + tableName + " where process_task_id = " + taskId;
            ResultSet resultSet = statement.executeQuery(sql);
            String id = "";
            BusApprove approve = new BusApprove();
            while (resultSet.next()) {
                id = resultSet.getString(1);
                approve = new BusApprove();
                approve.setBusId(id);
                approve.setBusType(tableName);
                approve.setTaskId(taskId);
                approve.setApproveStatus(ChengfaEnum.BUS_APPROVE_APPROVE_STATUS_DONE.getValue());
                approve.setApproveResult(ChengfaEnum.BUS_APPROVE_APPROVE_RESULT_Y.getValue());
                jdbcClient.jdbcInsert(approve, connection);
            }
            sql = "update " + tableName + " set end_time = '" + approve.getCreateTime() + "' where id = '" + id
                    + "'";
            statement.executeUpdate(sql);

            if (ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_PLAN.getValue().equals(tableName)) {
                sql = "select contract_plan_id from " + tableName + " where process_task_id = " + taskId;
                resultSet = statement.executeQuery(sql);
                while (resultSet.next()) {
                    Long contractPlanId = resultSet.getLong(1);
                    if (StringUtil.isEmpty(contractPlanId) || contractPlanId == 0) {
                        continue;
                    }
                    gldCostService.updateState(contractPlanId, ChengfaEnum.CONTRACT_PLAN_USE_STATE_IN_USE.getValue());
                }
            }

            if (ChengfaEnum.BUS_APPROVE_TYPE_PURCHASE_BID_NOTICE.getValue().equals(tableName)) {
                saveOAPurchaseInfo(id, connection);
            }

        }

    }

    public void saveOAPurchaseInfo(String id, Connection connection) throws Exception {
        PurchaseBidNotice notice = new PurchaseBidNotice();
        notice.setId(id);
        notice = jdbcClient.getJdbcModelById(notice, connection);
        Purchase purchase = new Purchase();
        purchase.setId(notice.getPurchaseId());
        purchase = jdbcClient.getJdbcModelById(purchase, connection);
        PurchaseAnswerSign answerSign = new PurchaseAnswerSign();
        answerSign.setPurchaseId(purchase.getId());
        answerSign.setStatus(ChengfaEnum.PURCHASE_STATUS_DONE.getValue());
        answerSign = jdbcClient.getJdbcModel(answerSign, connection);
        PurchaseBidSign bidSign = new PurchaseBidSign();
        bidSign.setPurchaseId(purchase.getId());
        bidSign.setStatus(ChengfaEnum.PURCHASE_STATUS_DONE.getValue());
        bidSign = jdbcClient.getJdbcModel(bidSign, connection);
        PurchaseMatter matter = new PurchaseMatter();
        matter.setPurchaseId(purchase.getId());
        matter = jdbcClient.getJdbcModel(matter, connection);
        matter.setStatus(ChengfaEnum.PURCHASE_STATUS_DONE.getValue());
        SysUser createUser = new SysUser();
        createUser.setUserId(purchase.getCreateId());
        createUser = jdbcClient.getJdbcModel(createUser, connection);
        SysUser purchaseUser = new SysUser();
        if (StringUtil.isEmpty(matter.getId())) {
            purchaseUser.setUserId(bidSign.getCreateId());
            purchaseUser = jdbcClient.getJdbcModel(purchaseUser, connection);
        } else {
            purchaseUser.setUserId(matter.getCreateId());
            purchaseUser = jdbcClient.getJdbcModel(purchaseUser, connection);
        }
        SysDept company = new SysDept();
        company.setDeptId((long) purchase.getBelongDeptId());
        company = jdbcClient.getJdbcModel(company, connection);

        ProjectInfo projectInfo = new ProjectInfo();
        if (StringUtil.isNotEmpty(purchase.getProjectId())) {
            projectInfo.setId(purchase.getProjectId());
            projectInfo = jdbcClient.getJdbcModel(projectInfo, connection);
        }
        if (StringUtil.isNotEmpty(notice.getBidCompanyIds())) {
            notice.setBidCompanyName(null);
            String[] companyIdArr = notice.getBidCompanyIds().split(",");
            for (String comId : companyIdArr) {
                Supplier bidCompany = new Supplier();
                bidCompany.setId(comId);
                bidCompany = jdbcClient.getJdbcModelById(bidCompany, connection);
                if (StringUtil.isEmpty(notice.getBidCompanyName())) {
                    notice.setBidCompanyName(getBidCompanyName(bidCompany));
                } else {
                    notice.setBidCompanyName(notice.getBidCompanyName() + "," + getBidCompanyName(bidCompany));
                }
            }
        }

        OaPurchaseInfo purchaseInfo = new OaPurchaseInfo();
        purchaseInfo.setId(purchase.getId());
        purchaseInfo.setCreateUserCode(createUser.getCode());
        purchaseInfo.setBidCreateUserCode(purchaseUser.getCode());
        purchaseInfo.setCompanyName(company.getName());
        purchaseInfo.setCompanyUnitCode(company.getCode());
        purchaseInfo.setPurchaseName(purchase.getName());
        purchaseInfo.setBidSupplierName(notice.getBidCompanyName());
        purchaseInfo.setPurchaseNo(purchase.getPurchaseNo());
        purchaseInfo.setPurchaseCreateTime(purchase.getCreateTime());
        purchaseInfo.setPurchaseEndTime(purchase.getEndTime());
        if (StringUtil.isNotEmpty(purchase.getId())) {
            purchaseInfo.setPurchaseUrl(redirectUrl + "?userId=1&type=purchase&processInstanceId=" + purchase.getProcessInstanceId() + "&path=" + purchasePath);
        }
        purchaseInfo.setMatterCreateTime(matter.getCreateTime());
        purchaseInfo.setMatterEndTime(matter.getEndTime());
        purchaseInfo.setMatterNo(matter.getBusinessNo());
        if (StringUtil.isNotEmpty(matter.getId())) {
            purchaseInfo.setMatterUrl(redirectUrl + "?userId=1&type=purchase_matter&processInstanceId=" + matter.getProcessInstanceId() + "&path=" + purchasePath);
        }
        purchaseInfo.setBidSignCreateTime(bidSign.getCreateTime());
        purchaseInfo.setBidSignEndTime(bidSign.getEndTime());
        purchaseInfo.setBidAnswerNo(bidSign.getBusinessNo());
        if (StringUtil.isNotEmpty(bidSign.getId())) {
            purchaseInfo.setBidSignUrl(redirectUrl + "?userId=1&type=purchase_bid_sign&processInstanceId=" + bidSign.getProcessInstanceId() + "&path=" + purchasePath);
        }
        purchaseInfo.setBidAnswerCreateTime(answerSign.getCreateTime());
        purchaseInfo.setBidAnswerEndTime(answerSign.getEndTime());
        purchaseInfo.setBidAnswerNo(answerSign.getBusinessNo());
        if (StringUtil.isNotEmpty(answerSign.getId())) {
            purchaseInfo.setBidAnswerUrl(redirectUrl + "?userId=1&type=purchase_answer_sign&processInstanceId=" + answerSign.getProcessInstanceId() + "&path=" + purchasePath);
        }
        purchaseInfo.setBidNoticeCreateTime(notice.getCreateTime());
        purchaseInfo.setBidNoticeEndTime(notice.getEndTime());
        purchaseInfo.setBidNoticeNo(notice.getBusinessNo());
        if (StringUtil.isNotEmpty(notice.getId())) {
            purchaseInfo.setBidNoticeUrl(redirectUrl + "?userId=1&type=purchase_bid_notice&processInstanceId=" + notice.getProcessInstanceId() + "&path=" + purchasePath);
        }
        purchaseInfo.setStatus(0);
        purchaseInfo.setDataSource(4);
        purchaseInfo.setProjectCode(purchase.getProjectNo());
        purchaseInfo.setProjectName(projectInfo.getProjectName());
        purchaseInfo.setPurchaseType(purchase.getPurchaseType());
        purchaseInfo.setIsShare(purchase.getIsShare());
        jdbcClient.jdbcInsert(purchaseInfo, connection);
        log.info("新增oa视图数据======>" + purchaseInfo.toString());
    }

    private String getBidCompanyName(Supplier bidCompany) {
        String name = bidCompany.getSupplierName();
        if (StringUtil.isNotEmpty(bidCompany.getContactName()) && StringUtil.isNotEmpty(bidCompany.getContactPhone())) {
            return name + "(" + bidCompany.getContactName() + ":" + bidCompany.getContactPhone() + ")";
        } else if (StringUtil.isNotEmpty(bidCompany.getContactName()) || StringUtil.isNotEmpty(bidCompany.getContactPhone())) {
            return name + "(" + (StringUtil.isNotEmpty(bidCompany.getContactName()) ? bidCompany.getContactName() : bidCompany.getContactPhone()) + ")";
        } else {
            return name;
        }
    }

    public static void main(String[] args) {
        String message = "{\"partitionKey\":0,\"eventType\":\"TaskEvent\",\"eventData\":\"{\\\"topic\\\":\\\"NODE_ENDED\\\",\\\"userAccessToken\\\":\\\"  cn-7e59e3b0-5646-438d-b943-78bfa032cc8f\\\",\\\"taskSimpleInfo\\\":{\\\"id\\\":11200747,\\\"subject\\\":\\\"startPosName\\\",\\\"state\\\":\\\"PROCESSING\\\",\\\"startTime\\\":null,\\\"startPosName\\\":\\\"第三方招采系统\\\",\\\"deadLineState\\\":null,\\\"deadLine\\\":null,\\\"settingId\\\":null,\\\"processingStepInfo\\\":null,\\\"deptId\\\":11200297,\\\"deptName\\\":null,\\\"taskCode\\\":null,\\\"targetId\\\":0,\\\"targetType\\\":\\\"purchase_matter\\\",\\\"extData\\\":null,\\\"remark\\\":\\\"已同意 不知道第几次的测试审核 下午第一次\\\",\\\"templateId\\\":null,\\\"taskType\\\":\\\"APPROVAL\\\",\\\"approvalLastProcessorId\\\":5600090,\\\"approvalLastProcessorName\\\":\\\"王经理\\\",\\\"preProcessorIds\\\":null,\\\"nextProcessorIds\\\":null,\\\"startorId\\\":5600057,\\\"rejectOpinion\\\":null,\\\"xmglInstanceId\\\":\\\"8fc4cdea-5a14-11ef-9a92-02429b7252f5\\\",\\\"operation\\\":\\\"approve\\\",\\\"xmglTaskId\\\":\\\"8fd94073-5a14-11ef-9a92-02429b7252f5\\\",\\\"endTaskInfo\\\":{\\\"assigneeName\\\":\\\"王经理\\\",\\\"createTime\\\":\\\"2024-08-14 16:09:43\\\",\\\"taskName\\\":\\\"负责人审批\\\",\\\"assignee\\\":\\\"5600090\\\",\\\"endTime\\\":\\\"2024-08-16 13:40:22\\\",\\\"previousUserId\\\":\\\"5600057\\\",\\\"opinion\\\":\\\"已同意 不知道第几次的测试审核 下午第一次\\\"}}}\"}";
        JSONObject object = JSONObject.parseObject(message);
        String topic = object.getJSONObject("eventData").getString("topic");
        JSONObject taskSimpleInfo = object.getJSONObject("eventData").getJSONObject("taskSimpleInfo");
        long taskId = taskSimpleInfo.getLong("id");
        String state = taskSimpleInfo.getString("state");

        log.info(topic + taskId + state);
    }
}