<?php

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

require_once realpath(dirname(__FILE__) . '/TestCase.php');

set_time_limit(-1);
ini_set('memory_limit', '4096m');

$file = getcwd() . '/' . $argv[1];

$array = [];

$packages = DB::connection('vd_old')->table('ckb_add_value_package')->where('del_status', 10)->get()->keyBy('package_sn');

if (($handle = fopen($file, 'r')) !== false) {
    $i = 0;

    while (($data = fgetcsv($handle)) !== false) {
        $i ++;

        $custom_no = trim(str_replace('\t', '', $data[1]));

        if ($i < 3 || $custom_no === '用户编号' || empty($custom_no)) {
            continue;
        }

        $startTime = DB::connection('vd_old')->table('ckb_custom_handle_log')->selectRaw('MAX(valid_end_time) as valid_end_time')
            ->where('custom_no', $custom_no)
            ->where('type', 14)->first();

        $startTime = $startTime->valid_end_time + 1;

        $logs = DB::connection('vd_old')->table('ckb_custom_handle_log')->where('custom_no', $custom_no)
            ->where('type', 11)->get();

        echo $custom_no . PHP_EOL;

        $custom = DB::connection('vd_old')->table('ckb_custom')->where('custom_no', $custom_no)->first();

        $content = $data[23];

        $package = $packages[$content];


        if(!$package){
            throw new \Exception('未找到套餐包');
        }

        foreach ($logs as $item) {
            $endTime = strtotime("+ {$package->service_cycle} month", $startTime) - 1;

            $data = [
                'type' => 14,
                'content' => $content,
                'valid_start_time' => $startTime,
                'valid_end_time' => $endTime,
                'sale_account' => 0,
                'order_account' => 0,
                'task_number' => 'change_renew_to_renew_package',
            ];

            DB::connection('vd_old')->table('ckb_custom_handle_log')->where('id', $item->id)->update($data);

            $userOrder = [
                'package_id' => $content,
                'new_package_id' => $content,
                'imsi' => $custom->imsi,
                'company' => $item->company,
                'pay_type' => $item->pay_type,
                'service_type' => 13,
                'pay_value' => 0,
                'order_time' => $item->create_time,
                'pay_status' => 10,
                'valid_start_time' => $startTime,
                'valid_end_time' => $endTime,
                'create_time' => $item->create_time,
                'task_number' => 'change_renew_to_renew_package',
                'sim' => $custom->card_number,
            ];

            DB::connection('vd_old')->table('ckb_user_order')->insert($userOrder);

            $startTime = $endTime + 1;
        }
    }
    fclose($handle);
}
