package com.chinacreator.process.service;

import com.chinacreator.process.bean.TencentBillChannel;
import com.chinacreator.process.bean.TencentBillLResult;
import com.chinacreator.process.bean.TencentBillLog;
import com.chinacreator.process.bean.TencentBillOrder;
import com.chinacreator.process.dao.TencentBillDao;
import com.chinacreator.process.util.ftp.FtpUtil;
import com.chinacreator.process.util.ftp.SFtpUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class TencentBillService
{
    private static Logger logger;
    private static SimpleDateFormat sdf;
    @Autowired
    private TencentBillDao dao;
    
    static {
        TencentBillService.logger = Logger.getLogger((Class)TencentBillService.class);
        TencentBillService.sdf = new SimpleDateFormat("yyyyMMdd");
    }
    
    public void Bill(final TencentBillChannel ch, final String billtype, final String datestr) {
        if ("1".equals(billtype)) {
            if (datestr == null || "".equals(datestr.trim()) || datestr.trim().length() != 8) {
                    TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u8d26\u671f\u5f02\u5e38");
                    return;
            }
        }
        else {
            if (!"2".equals(billtype)) {
                TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u7c7b\u578b\u5f02\u5e38");
                return;
            }
            if (datestr == null || "".equals(datestr.trim()) || datestr.trim().length() != 6) {
                TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u8d26\u671f\u5f02\u5e38");
                return;
            }
        }
        if ("1".equals(billtype) || "2".equals(billtype)) {
            TencentBillLog log = this.dao.existBillLog(datestr, billtype, ch.getCpid(), ch.getSpid());
            if (log == null) {
                final TencentBillLResult flagFiles = this.createFile(ch, billtype, datestr);
                final String filenames = flagFiles.getFilenames();
                final String filepath = flagFiles.getFilepath();
                String billstatus = flagFiles.isResult() ? "0" : "1";
                String code = "";
                String info = "";
                if ("0".equals(billstatus)) {
                    final TencentBillLResult flag = this.ftpFile(ch, filepath, filenames, datestr);
                    code = flag.getCode();
                    info = flag.getInfo();
                    if (!flag.isResult()) {
                        billstatus = "2";
                    }
                }
                log = new TencentBillLog();
                log.setId(String.valueOf(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())) + String.valueOf((int)((Math.random() * 9.0 + 1.0) * 1000.0)));
                log.setBilldate(datestr);
                log.setBilltype(billtype);
                log.setCpid(ch.getCpid());
                log.setSpid(ch.getSpid());
                log.setDatacounts(flagFiles.getCounts());
                log.setFilecounts(flagFiles.getFiles());
                log.setFiles(filenames);
                log.setFilepath(filepath);
                log.setResultcode(code);
                log.setErrorinfo(info);
                log.setStatus(billstatus);
                this.dao.saveBillLog(log);
            }
        }
    }
    
    public void BillRetry3(final TencentBillChannel ch, final TencentBillLog log) {
        if (log == null) {
            return;
        }
        final String billtype = log.getBilltype();
        final String datestr = log.getBilldate();
        if ("1".equals(billtype)) {
            if (datestr == null || "".equals(datestr.trim()) || datestr.trim().length() != 8) {
                TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u8d26\u671f\u5f02\u5e38");
                return;
            }
        }
        else {
            if (!"2".equals(billtype)) {
                TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u7c7b\u578b\u5f02\u5e38");
                return;
            }
            if (datestr == null || "".equals(datestr.trim()) || datestr.trim().length() != 6) {
                TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u8d26\u671f\u5f02\u5e38");
                return;
            }
        }
        if ("1".equals(billtype) || "2".equals(billtype)) {
            final TencentBillLResult flagFiles = this.createFile(ch, billtype, datestr);
            final String filenames = flagFiles.getFilenames();
            final String filepath = flagFiles.getFilepath();
            String billstatus = flagFiles.isResult() ? "0" : "1";
            String code = "";
            String info = "";
            if ("0".equals(billstatus)) {
                final TencentBillLResult flag = this.ftpFile(ch, filepath, filenames, datestr);
                code = flag.getCode();
                info = flag.getInfo();
                if (!flag.isResult()) {
                    billstatus = "2";
                }
            }
            final TencentBillLog nlog = new TencentBillLog();
            nlog.setId(String.valueOf(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())) + String.valueOf((int)((Math.random() * 9.0 + 1.0) * 1000.0)));
            nlog.setBilldate(datestr);
            nlog.setBilltype(billtype);
            nlog.setCpid(ch.getCpid());
            nlog.setSpid(ch.getSpid());
            nlog.setDatacounts(flagFiles.getCounts());
            nlog.setFilecounts(flagFiles.getFiles());
            nlog.setFiles(filenames);
            nlog.setFilepath(filepath);
            nlog.setResultcode(code);
            nlog.setErrorinfo(info);
            nlog.setStatus(billstatus);
            this.dao.saveBillLog(nlog);
            this.dao.updatetBillLog(log.getId());
        }
    }
    
    public void BillRetry4(final TencentBillChannel ch, final TencentBillLog log) {
        if (log == null) {
            return;
        }
        final String billtype = log.getBilltype();
        final String datestr = log.getBilldate();
        if ("1".equals(billtype)) {
            if (datestr == null || "".equals(datestr.trim()) || datestr.trim().length() != 8) {
                TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u8d26\u671f\u5f02\u5e38");
                return;
            }
        }
        else {
            if (!"2".equals(billtype)) {
                TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u7c7b\u578b\u5f02\u5e38");
                return;
            }
            if (datestr == null || "".equals(datestr.trim()) || datestr.trim().length() != 6) {
                TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u8d26\u671f\u5f02\u5e38");
                return;
            }
        }
        if (("1".equals(billtype) || "2".equals(billtype)) && ("0".equals(log.getStatus()) || "1".equals(log.getStatus()))) {
            String billstatus = "0";
            String code = "";
            String info = "";
            final TencentBillLResult flag = this.ftpFile(ch, log.getFilepath(), log.getFiles(), datestr);
            code = flag.getCode();
            info = flag.getInfo();
            if (!flag.isResult()) {
                billstatus = "2";
            }
            this.dao.updatetBillLogFtp(log.getId(), billstatus, code, info);
        }
    }
    
    public TencentBillLResult createFile(final TencentBillChannel ch, final String billtype, final String datestr) {
        final TencentBillLResult res = new TencentBillLResult();
        res.setResult(true);
        final String FILE_PATH = ch.getFilepath();
        final int FILE_SISE = ch.getFilesize();
        final int PAGE_SISE = ch.getPagesize();
        String filenames = "";
        final String filepath = String.valueOf(FILE_PATH) + ch.getCpid() + "_" + ch.getSpid() + "/" + datestr.substring(0, 6) + "/";
        final File filedir = new File(filepath);
        if (!filedir.exists()) {
            filedir.mkdirs();
        }
        int counts = 0;
        int files = 0;
        try {
            if ("1".equals(billtype)) {
                counts = this.countForDay(ch.getCpid(), ch.getSpid(), datestr);
            }
            else {
                counts = this.countForMonth(ch.getCpid(), ch.getSpid(), datestr);
            }
            TencentBillService.logger.info((Object)(">>>\u8bb0\u5f55\u603b\u6570" + counts));
            if (counts > 0) {
                files = ((counts % FILE_SISE != 0) ? 1 : 0) + counts / FILE_SISE;
                for (int k = 1; k <= files; ++k) {
                    final String sortno = "0000" + k;
                    final String filename = String.valueOf(datestr) + "_" + ch.getCpid() + "_" + sortno.substring(sortno.length() - 4, sortno.length()) + ".req";
                    filenames = String.valueOf((filenames.length() >= 1) ? new StringBuilder(String.valueOf(filenames)).append(",").toString() : "") + filename;
                    final File file = new File(String.valueOf(filepath) + filename);
                    if (file.exists()) {
                        file.renameTo(new File(String.valueOf(filepath) + filename + "." + new Date().getTime()));
                    }
                    file.createNewFile();
                    TencentBillService.logger.info((Object)(">>>\u751f\u6210\u6587\u4ef6\uff1a" + filename));
                    int filecount = 0;
                    if (counts - (k - 1) * FILE_SISE >= FILE_SISE) {
                        filecount = FILE_SISE;
                    }
                    else {
                        filecount = counts - (k - 1) * FILE_SISE;
                    }
                    final BufferedWriter out = new BufferedWriter(new FileWriter(file));
                    out.write(String.valueOf(counts) + "\r\n");
                    if (filecount > 0) {
                        for (int pages = ((filecount % PAGE_SISE != 0) ? 1 : 0) + filecount / PAGE_SISE, i = 1; i <= pages; ++i) {
                            List<TencentBillOrder> bills = new ArrayList<TencentBillOrder>();
                            if ("1".equals(billtype)) {
                                bills = this.pageQueryForDay(ch.getCpid(), ch.getSpid(), datestr, i + (k - 1) * FILE_SISE / PAGE_SISE, PAGE_SISE);
                            }
                            else {
                                bills = this.pageQueryForMonth(ch.getCpid(), ch.getSpid(), datestr, i + (k - 1) * FILE_SISE / PAGE_SISE, PAGE_SISE);
                            }
                            if (bills != null && bills.size() > 0) {
                                int y = (k - 1) * FILE_SISE + (i - 1) * PAGE_SISE;
                                for (final TencentBillOrder bo : bills) {
                                    ++y;
                                    final StringBuffer sb = new StringBuffer();
                                    sb.append(y).append("|");
                                    sb.append((bo.getOrderid() == null) ? "" : bo.getOrderid()).append("|");
                                    sb.append((bo.getUserid() == null) ? "" : bo.getUserid()).append("|");
                                    sb.append((bo.getBusitype() == null) ? "" : bo.getBusitype()).append("|");
                                    sb.append((bo.getOptime() == null) ? "" : bo.getOptime()).append("|");
                                    sb.append((bo.getResultcode() == null) ? "" : bo.getResultcode()).append("|");
                                    sb.append((bo.getResultinfo() == null) ? "" : bo.getResultinfo());
                                    sb.append("\r\n");
                                    out.write(sb.toString());
                                }
                            }
                        }
                    }
                    out.flush();
                    out.close();
                }
            }
            else {
                final String filename2 = filenames = String.valueOf(datestr) + "_" + ch.getCpid() + "_0001.req";
                files = 1;
                final File file2 = new File(String.valueOf(filepath) + filename2);
                if (file2.exists()) {
                    file2.renameTo(new File(String.valueOf(filepath) + filename2 + "." + new Date().getTime()));
                }
                file2.createNewFile();
                TencentBillService.logger.info((Object)(">>>\u751f\u6210\u6587\u4ef6\uff1a" + filename2));
                final BufferedWriter out2 = new BufferedWriter(new FileWriter(file2));
                out2.write(String.valueOf(counts) + "\r\n");
                out2.flush();
                out2.close();
            }
        }
        catch (Exception e) {
            TencentBillService.logger.info((Object)">>>\u5bf9\u8d26\u6587\u4ef6\u751f\u6210\u5931\u8d25");
            res.setResult(false);
        }
        res.setCounts(counts);
        res.setFiles(files);
        res.setFilepath(filepath);
        res.setFilenames(filenames);
        return res;
    }
    
    public TencentBillLResult ftpFile(final TencentBillChannel ch, final String filepath, final String filenames, final String datestr) {
        final TencentBillLResult res = new TencentBillLResult();
        boolean flag = false;
        String code = "";
        String info = "";
        TencentBillService.logger.info((Object)(">>>\u76ee\u5f55\uff1a" + filepath));
        TencentBillService.logger.info((Object)(">>>\u6587\u4ef6\u5217\u8868\uff1a" + filenames));
        if ("ftp".equals(ch.getFtptype().toLowerCase())) {
            final FtpUtil util = new FtpUtil();
            String ftppath = ch.getFtpdir();
            if (ftppath != null || !"".equals(ftppath)) {
                ftppath = ftppath.replace("{yyyyMM}", datestr.substring(0, 6));
            }
            flag = util.UpBillFiles(ch.getFtpurl(), ch.getFtpuser(), ch.getFtppwd(), ch.getFtpport(), ftppath, filepath, filenames);
            code = util.getErrorcode();
            info = util.getErrorinfo();
        }
        else if ("sftp".equals(ch.getFtptype().toLowerCase())) {
            final SFtpUtil util2 = new SFtpUtil();
            String ftppath = ch.getFtpdir();
            if (ftppath != null || !"".equals(ftppath)) {
                ftppath = ftppath.replace("{yyyyMM}", datestr.substring(0, 6));
            }
            flag = util2.UpBillFiles(ch.getFtpurl(), ch.getFtpuser(), ch.getFtppwd(), ch.getFtpport(), ftppath, filepath, filenames);
            code = util2.getErrorcode();
            info = util2.getErrorinfo();
        }
        else {
            code = "9999";
            info = "FTP\u914d\u7f6e\u5f02\u5e38";
        }
        res.setResult(flag);
        res.setCode(code);
        res.setInfo(info);
        return res;
    }
    
    public List<TencentBillOrder> pageQueryForDay(final String cpid, final String spid, final String datestr, final int pageno, final int pagesize) {
        try {
            final Date date = TencentBillService.sdf.parse(datestr);
            final String starttime = TencentBillService.sdf.format(date);
            final Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(5, 1);
            final String endtime = TencentBillService.sdf.format(cal.getTime());
            return this.dao.pageQuery(cpid, spid, starttime, endtime, pageno, pagesize);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public int countForDay(final String cpid, final String spid, final String datestr) {
        try {
            final Date date = TencentBillService.sdf.parse(datestr);
            final String starttime = TencentBillService.sdf.format(date);
            final Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(5, 1);
            final String endtime = TencentBillService.sdf.format(cal.getTime());
            return this.dao.counts(cpid, spid, starttime, endtime);
        }
        catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public List<TencentBillOrder> pageQueryForMonth(final String cpid, final String spid, final String monthstr, final int pageno, final int pagesize) {
        try {
            final Date date = TencentBillService.sdf.parse(String.valueOf(monthstr) + "01");
            final Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(2, 1);
            final String endtime = TencentBillService.sdf.format(cal.getTime());
            return this.dao.pageQuery(cpid, spid, null, endtime, pageno, pagesize);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public int countForMonth(final String cpid, final String spid, final String monthstr) {
        try {
            final Date date = TencentBillService.sdf.parse(String.valueOf(monthstr) + "01");
            final Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(2, 1);
            final String endtime = TencentBillService.sdf.format(cal.getTime());
            return this.dao.counts(cpid, spid, null, endtime);
        }
        catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    public static void main(final String[] args) {
    }
}