package com.ai.da.common.config;

import com.ai.da.mapper.primary.entity.CustomerData;
import com.ai.da.mapper.primary.entity.TransactionData;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CRMReportInterface {

    // JDBC 驱动器名称以及数据库 URL
    static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    static final String DB_URL = "jdbc:sqlserver://118.142.0.178:1550;databaseName=Hayman_prod";

    // 数据库凭据
    static final String USER = "user01";
    static final String PASS = "haySIS-2302";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动器
            Class.forName(JDBC_DRIVER);

            // 打开一个连接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询步骤1: 生成 RW0095 报告以获取客户完整数据
            System.out.println("执行步骤1：生成 RW0095 报告...");
            // 执行相应的查询并获取数据
//            List<CustomerData> customerData = retrieveCustomerData();
            // 执行查询步骤2: 使用 MZG013 报告检查客户的销售历史
            System.out.println("执行步骤2：使用 MZG013 报告检查客户的销售历史...");
            // 执行相应的查询并获取数据
            List<TransactionData> transactionData = retrieveTransactionData();
            List<String> collect = transactionData.stream().map(TransactionData::getUserMember).collect(Collectors.toList());
            List<CustomerData> customerData = retrieveCustomerData(collect);
            for (TransactionData transactionDatum : transactionData) {
                for (CustomerData customerDatum : customerData) {
                    if (customerDatum.getMbrCode().equals(transactionDatum.getUserMember())) {
                        customerDatum.setLastMonth(transactionDatum.getSumAmt());
                        break;
                    }
                }
            }
            // 执行步骤3: 合并（vlookup）RW0095中的客户购买金额
            System.out.println("执行步骤3：合并客户购买金额...");
            // 执行相应的操作，如vlookup

            // 执行步骤4: 按“发行店”筛选以分离不同文件并逐个发送给店铺
            System.out.println("执行步骤4：按发行店筛选并发送文件给店铺...");
            // 执行相应的操作，如过滤和导出
            String filePath = "C:\\Users\\10233\\Desktop\\CRM.csv";
            exportToCSV(customerData, filePath);
            // 关闭连接
            conn.close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            } // 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("接口执行完成！");
    }

    private static void exportToCSV(List<CustomerData> customerDataList, String filePath) throws IOException {
        FileWriter writer = new FileWriter(filePath);

//        // 写入 CSV 文件的第一行，即字段名
//        writer.append("User Member,Mbr Name,Sh Code,Sum Amt\n");
//
//        // 遍历数据列表，并将每一行数据写入 CSV 文件
//        for (TransactionData transaction : transactionDataList) {
//            writer.append(transaction.getUserMember()).append(",");
//            writer.append(transaction.getMbrName()).append(",");
//            writer.append(transaction.getShCode()).append(",");
//            writer.append(String.valueOf(transaction.getSumAmt())).append("\n");
//        }
        writer.append("mbrCode,mbrName,mbrMobile,mbrGroup,mbrStatus,joinDate,mbrIssue,birthMonth,mbrSex,offBonus,effBonus,sumBonus,lastMonth\n");

        // 遍历 customerDataList，并将数据写入 CSV 文件
        for (CustomerData customer : customerDataList) {
            writer.append(customer.getMbrCode()).append(",");
            writer.append(customer.getMbrName()).append(",");
            writer.append(customer.getMbrMobile()).append(",");
            writer.append(customer.getMbrGroup()).append(",");
            writer.append(customer.getMbrStatus()).append(",");
            writer.append(customer.getJoinDate().toString()).append(","); // 日期需要根据实际情况格式化
            writer.append(customer.getMbrIssue()).append(",");
            writer.append(Integer.toString(customer.getBirthMonth())).append(",");
            writer.append(customer.getMbrSex()).append(",");
            writer.append(Double.toString(customer.getOffBonus())).append(",");
            writer.append(Double.toString(customer.getEffBonus())).append(",");
            writer.append(Double.toString(customer.getSumBonus())).append(",");
            writer.append(Double.toString(customer.getLastMonth())).append("\n");
        }

        writer.close();
    }

    public static List<CustomerData> retrieveCustomerData(List<String> collect) {
        List<CustomerData> customerDataList = new ArrayList<>();
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动器
            Class.forName(JDBC_DRIVER);

            // 打开一个连接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            System.out.println("创建声明...");
            stmt = conn.createStatement();
            String sql;
            // 构建 IN 子句的字符串，用于添加到 SQL 查询中
            StringBuilder inClause = new StringBuilder("(");
            for (String code : collect) {
                inClause.append("'").append(code).append("',");
            }
            inClause.deleteCharAt(inClause.length() - 1); // 删除最后一个逗号
            inClause.append(")");

            // 构建完整的 SQL 查询语句
            sql = "SELECT * FROM V_RW0095B WHERE mbr_code IN " + inClause.toString();
            ResultSet rs = stmt.executeQuery(sql);


            // 处理结果集
            while (rs.next()) {
                // 将每行数据转换为 CustomerData 对象并添加到列表中
                CustomerData customer = new CustomerData();
                customer.setMbrCode(rs.getString("mbr_code"));
                customer.setMbrName(rs.getString("mbr_name"));
                customer.setMbrMobile(rs.getString("mbr_mobile"));
                customer.setMbrGroup(rs.getString("mbr_group"));
                customer.setMbrStatus(rs.getString("mbr_status"));
                customer.setJoinDate(rs.getDate("join_date"));
                customer.setMbrIssue(rs.getString("mbr_issue"));
                customer.setBirthMonth(rs.getInt("birth_m"));
                customer.setMbrSex(rs.getString("mbr_sex"));
                customer.setOffBonus(rs.getDouble("off_bonus"));
                customer.setEffBonus(rs.getDouble("eff_bonus"));
                customer.setSumBonus(rs.getDouble("sum_bonus"));
                customerDataList.add(customer);

            }

            // 清理环境
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            } // 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("查询执行完成！");
        return customerDataList;
    }

    public static List<TransactionData> retrieveTransactionData() {
        List<TransactionData> transactionDataList = new ArrayList<>();
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动器
            Class.forName(JDBC_DRIVER);

            // 打开一个连接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            System.out.println("创建声明...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT user_member,mbr_name,sum(trx_bas_amt) sumAmtByMebBySh FROM V_MZG013\n" +
                    "WHERE trx_date >= DATEADD(day, -7, GETDATE())\n" +
                    "and user_member is not NULL\n" +
                    "GROUP BY user_member,mbr_name";
            ResultSet rs = stmt.executeQuery(sql);

            // 处理结果集
            while (rs.next()) {
                // 将每行数据转换为 TransactionData 对象并添加到列表中
                TransactionData transaction = new TransactionData();
                transaction.setUserMember(rs.getString("user_member"));
                transaction.setMbrName(rs.getString("mbr_name"));
//                transaction.setShCode(rs.getString("sh_code"));
                transaction.setSumAmt(rs.getDouble("sumAmtByMebBySh"));
//                transaction.setTrxNo(rs.getString("trx_no"));
//                transaction.setTrxDate(rs.getTimestamp("trx_date"));
//                transaction.setTrxType(rs.getString("trx_type"));
//                transaction.setTrxStatus(rs.getString("trx_status"));
//                transaction.setTrxTotQty(rs.getDouble("trx_tot_qty"));
//                transaction.setCurrCode(rs.getString("curr_code"));
//                transaction.setExchRate(rs.getDouble("exch_rate"));
//                transaction.setDiscountPerc(rs.getDouble("discount_perc"));
//                transaction.setTrxAccAmt(rs.getDouble("trx_acc_amt"));
//                transaction.setTrxBasAmt(rs.getDouble("trx_bas_amt"));
//                transaction.setOutstandAmt(rs.getDouble("outstand_amt"));
//                transaction.setReceiveAmt(rs.getDouble("receive_amt"));
//                transaction.setChangeAmt(rs.getDouble("change_amt"));
//                transaction.setTrxTotBonus(rs.getDouble("trx_tot_bonus"));
//                transaction.setDepositNo(rs.getString("deposit_no"));
//                transaction.setDepositAmt(rs.getDouble("deposit_amt"));
//                transaction.setDepositStatus(rs.getString("deposit_status"));
//                transaction.setTrxAmtDesc(rs.getString("trx_amt_desc"));
//                transaction.setRemark(rs.getString("remark"));
//                transaction.setShCode(rs.getString("sh_code"));
//                transaction.setWhCodeFrom(rs.getString("wh_code_from"));
//                transaction.setWhCodeTo(rs.getString("wh_code_to"));
//                transaction.setIssuedBy(rs.getString("issued_by"));
//                transaction.setClientCode(rs.getString("client_code"));
//                transaction.setClientName(rs.getString("client_name"));
//                transaction.setSalesmanCode(rs.getString("salesman_code"));
//                transaction.setCtypeCode(rs.getString("ctype_code"));
//                transaction.setUpdatedOn(rs.getTimestamp("updated_on"));
//                transaction.setDocType(rs.getString("doc_type"));
//                transaction.setRefNo(rs.getString("ref_no"));
//                transaction.setAdjType(rs.getString("adj_type"));
//                transaction.setRefType(rs.getString("ref_type"));
//                transaction.setOrderNo(rs.getString("order_no"));
//                transaction.setRecoverF(rs.getString("recover_f"));
//                transaction.setRecoverT(rs.getString("recover_t"));
//                transaction.setRequestBy(rs.getString("request_by"));
//                transaction.setError(rs.getString("error"));
//                transaction.setAuthorizedDate(rs.getTimestamp("authorized_date"));
//                transaction.setAuthorizedBy(rs.getString("authorized_by"));
//                transaction.setChangeCurrCode(rs.getString("change_curr_code"));
//                transaction.setChgRate(rs.getDouble("chg_rate"));
//                transaction.setCashier(rs.getString("cashier"));
//                transaction.setCashiNo(rs.getString("cashi_no"));
//                transaction.setSalesmanCode2(rs.getString("salesman_code2"));
//                transaction.setClassId(rs.getString("class_id"));
//                transaction.setDisAmt(rs.getDouble("dis_amt"));
//                transaction.setAcStatus(rs.getString("ac_status"));
//                transaction.setReprint(rs.getString("reprint"));
//                transaction.setAlt1(rs.getString("alt_1"));
//                transaction.setAlt2(rs.getString("alt_2"));
//                transaction.setAlt3(rs.getString("alt_3"));
//                transaction.setAlt4(rs.getString("alt_4"));
//                transaction.setAlt5(rs.getString("alt_5"));
//                transaction.setAltD1(rs.getDate("alt_d1"));
//                transaction.setAltD2(rs.getDate("alt_d2"));
//                transaction.setAltD3(rs.getDate("alt_d3"));
//                transaction.setAltD4(rs.getDate("alt_d4"));
//                transaction.setAltD5(rs.getDate("alt_d5"));
//                transaction.setSalesmanCode3(rs.getString("salesman_code3"));
//                transaction.setContractNo(rs.getString("contract_no"));
//                transaction.setExpireDate(rs.getTimestamp("expire_date"));
//                transaction.setDepositNetAmt(rs.getDouble("deposit_netamt"));
//                transaction.setClientRestriction(rs.getString("client_restriction"));
//                transaction.setRefStatus(rs.getString("ref_status"));
//                transaction.setMbrDis(rs.getDouble("mbr_dis"));
//                transaction.setPmtDiscount(rs.getDouble("pmt_discount"));
//                transaction.setPmtAmount(rs.getDouble("pmt_amount"));
//                transaction.setPmtNo(rs.getString("pmt_no"));
//                transaction.setRefCode(rs.getString("ref_code"));
//                transaction.setDocApproved(rs.getString("doc_approved"));
//                transaction.setRefractionNo(rs.getString("refraction_no"));
//                transaction.setCcpTot(rs.getDouble("ccp_tot"));
//                transaction.setCcpRed(rs.getDouble("ccp_red"));
//                transaction.setCcpExpired(rs.getDouble("ccp_expired"));
//                transaction.setPrintedTimes(rs.getInt("printed_times"));
//                transaction.setPickupShop(rs.getString("pickup_shop"));
//                transaction.setDeliveryDate(rs.getDate("delivery_date"));
//                transaction.setDeliveryTime(rs.getString("delivery_time"));
//                transaction.setWsCode(rs.getString("ws_code"));
//                transaction.setClCode(rs.getString("cl_code"));
//                transaction.setClDesc(rs.getString("cl_desc"));
//                transaction.setRatio(rs.getString("ratio"));
//                transaction.setUserMember(rs.getString("user_member"));
//                transaction.setHflag(rs.getString("hflag"));
//                transaction.setIssueShop(rs.getString("issue_shop"));
//                transaction.setHoUpdBy(rs.getString("ho_upd_by"));
//                transaction.setHoUpdOn(rs.getTimestamp("ho_upd_on"));
//                transaction.setBonusExpired(rs.getDouble("bonus_expired"));
//                transaction.setBonusRed(rs.getDouble("bonus_red"));
//                transaction.setConfirmedOn(rs.getTimestamp("confirmed_on"));
//                transaction.setConfirmedBy(rs.getString("confirmed_by"));
//                transaction.setDocConfirmed(rs.getString("doc_confirmed"));
//                transaction.setBrNo(rs.getString("br_no"));
//                transaction.setChangeAmt2(rs.getDouble("change_amt2"));
//                transaction.setSalesDate(rs.getDate("sales_date"));
//                transaction.setMbrName(rs.getString("mbr_name"));
//                transaction.setCanEntryDis(rs.getString("can_entry_dis"));
//                transaction.setReactiveClient(rs.getString("reactive_client"));
//                transaction.setReactiveMbr(rs.getString("reactive_mbr"));
//                transaction.setShUpdBy(rs.getString("sh_upd_by"));
//                transaction.setShUpdOn(rs.getTimestamp("sh_upd_on"));
//                transaction.setTax1(rs.getDouble("tax1"));
//                transaction.setTax2(rs.getDouble("tax2"));
//                transaction.setTax3(rs.getDouble("tax3"));
//                transaction.setTax4(rs.getDouble("tax4"));
//                transaction.setTax5(rs.getDouble("tax5"));
//                transaction.setAltChar1(rs.getString("alt_char1"));
//                transaction.setAltChar2(rs.getString("alt_char2"));
//                transaction.setAltChar3(rs.getString("alt_char3"));
//                transaction.setAltChar4(rs.getString("alt_char4"));
//                transaction.setAltChar5(rs.getString("alt_char5"));
//                transaction.setAltNum1(rs.getDouble("alt_num1"));
//                transaction.setAltNum2(rs.getDouble("alt_num2"));
//                transaction.setAltNum3(rs.getDouble("alt_num3"));
//                transaction.setAltNum4(rs.getDouble("alt_num4"));
//                transaction.setAltNum5(rs.getDouble("alt_num5"));
//                transaction.setNewClient(rs.getString("new_client"));
//                transaction.setNewMbr(rs.getString("new_mbr"));
//                transaction.setPmtExtraDiscount(rs.getDouble("pmt_extra_discount"));
//                transaction.setPmtExtraAmount(rs.getDouble("pmt_extra_amount"));
//                transaction.setManualDiscount(rs.getDouble("manual_discount"));
//                transaction.setManualAmount(rs.getDouble("manual_amount"));
//                transaction.setUsermbrDiscount(rs.getDouble("usermbr_discount"));
//                transaction.setClientDiscount(rs.getDouble("client_discount"));
//                transaction.setHoldVoid(rs.getString("hold_void"));
//                transaction.setPayBasAmt(rs.getDouble("pay_bas_amt"));
//                transaction.setPayDesc(rs.getString("pay_desc"));
//                transaction.setPayCode(rs.getString("pay_code"));
//                transaction.setCardNo(rs.getString("card_no"));
//                transaction.setPayCurr(rs.getString("pay_curr"));
//                transaction.setPayCurrAmt(rs.getDouble("pay_curr_amt"));
//                transaction.setOnbehalfPaid(rs.getString("onbehalf_paid"));
//                transaction.setOnbehalfLoc(rs.getString("onbehalf_loc"));
//                transaction.setOldCardNo(rs.getString("old_card_no"));
//                transaction.setTrxYear(rs.getInt("TRX_YEAR"));
//                transaction.setTrxMonth(rs.getInt("TRX_MONTH"));

                transactionDataList.add(transaction);
            }


            // 清理环境
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException | ClassNotFoundException e) {
            // 处理异常
            e.printStackTrace();
        }
        System.out.println("查询执行完成！");
        return transactionDataList;
    }

    // 示例：导出数据到CSV文件
    private static void exportToCSV(ResultSet resultSet, String filePath) throws SQLException, IOException {
        FileWriter writer = new FileWriter(filePath);

        while (resultSet.next()) {
            // 将结果写入CSV文件
            // 这里需要根据实际情况将数据写入CSV文件
        }

        writer.close();
    }
}

