<?php

namespace App\Console\Commands;

use App\Facades\CommonService;
use App\Http\Controllers\TestController;
use App\Models\FatLog;
use App\Models\NewFatLog;
use App\Models\OfflineOrder;
use App\Models\Order;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\Version;
use App\Services\FatService;
use App\Services\OfflineOrderService;
use DB;
use Illuminate\Console\Command;
use Log;

class ImportFatLog extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:dma {type}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {   
        $this->info("导入体脂秤信息");

        $type = $this->argument("type");

        switch($type) {
            case "user":
                $content = file_get_contents(storage_path("user.txt"));
                $contentList = explode("\n", $content);
                
                foreach($contentList as $content) {
                    $res = json_decode($content);
                    if (empty($res)) {
                        dd($content);
                    }
                    $dataList = $res->data;
                    foreach($dataList as $data) {
                        $user = $this->importStoreUser($data);
                        if ($user && $user->account_id) {
                            $this->info("成功导入用户[{$user->id}]");
                        }
                
                    }
                }
                break;
            case "fat_log":
                $users = User::whereNotNull("account_id")->get();
                foreach($users as $user) {
                    $file_path = storage_path("list/{$user->account_id}.txt");
                    $fat_content = file_get_contents($file_path);
                    $fat_content = str_replace("'", '"', $fat_content);
                    $res = json_decode($fat_content);
                    if (empty($res)) {
                        dd($fat_content);
                    }
                    if (!count($res->data)) {
                        $this->info("用户[{$user->id}]没有体重信息");
                        continue;
                    };
                    $this->importStoreFat($user, $res);   
                    $this->info("成功导入用户[{$user->id}]体重信息");
                }
                break;
            case "order":
                $users = User::withCount("payOrders")->whereNotNull("account_id")->get();
                foreach($users as $user) {
                    if ($user->pay_orders_count) {
                        $this->info("用户[{$user->id}]已有订单");
                        continue;
                    }
                    // 创建订单
                    $tradeNo = CommonService::getTradeNO();
                    DB::beginTransaction();
                    $order = Order::create([
                        'user_id' => $user->id,
                        'type' => 'SERVICE',
                        'type_id' => 1,
                        'price' => 0,
                        'pay_status' => 'PAID',
                        'trade_no' => $tradeNo,
                        'name' => $user->name,
                        'area_code' => 86,
                        "status" => Order::NOTSTART_STATUS,
                        "service_status"=> "NOINFO",
                        'mobile' => ctype_digit($user->mobile) ? $user->mobile : aesDecryptCBC($user->mobile),
                        'agency_id' => null,
                        'desc' => '友福健康服务',
                        'is_hook'=>1,
                    ]);

                    // 创建线下订单
                    OfflineOrder::create([
                        'order_id' => $order->id,
                        'name' => $order->name,
                        'area_code' => 86,
                        'mobile' =>$order->mobile,
                        'contract_no'=>$order->mobile,
                        'pay_type' => 1,
                        'bank_name' => null,
                        'bank_num' => null,
                        'agency_id' => null,
                        'price' => 0,
                    ]);
                    DB::commit();
                    $this->info("成功导入用户[{$user->id}]dma订单");
                }
                break;
            default:
                return Command::SUCCESS;
        }

        return Command::SUCCESS;
    }

    
    public function importStoreFat($user, $res)
    {
        $fatService = new FatService();
        foreach($res->data as $data) {
            $exists = NewFatLog::where("old_id", $data->id)->exists();
            if ($exists) continue;
            $log = [
                ["e_name"=>"Weight", "score"=>$data->weight],
                ["e_name"=>"BMI", "score"=>$data->bmi],
                ["e_name"=>"Bodyfat", "score"=>$data->bodyfat],
                ["e_name"=>"Subfat", "score"=>$data->subfat],
                ["e_name"=>"Water", "score"=>$data->water],
                ["e_name"=>"Muscle", "score"=>$data->muscle],
                ["e_name"=>"Visfat", "score"=>$data->visfat],
                ["e_name"=>"Bone", "score"=> number_format($data->bone / 10, 2, ".", "") ],
                ["e_name"=>"BMR", "score"=>$data->bmr * 10],
                ["e_name"=>"BodyShape", "score"=>$data->body_shape],
                ["e_name"=>"Protein", "score"=>$data->protein],
                ["e_name"=>"LBM", "score"=>$data->fat_free_weight],
                ["e_name"=>"Sinew", "score"=>$data->sinew],
                ["e_name"=>"BodyAge", "score"=>$data->bodyage],
                ["e_name"=>"Score", "score"=>$data->score],
            ];
            $user->fat_device = 1; // 云康宝
            $res = $fatService->saveFatLog($user,["data"=>$log, "time"=>$data->created_at, "old_id"=>$data->id, "init_data"=>"cs20h", "device_model"=>"CS20H"],Version::TYPE_APP,true);
        }
    }

    public function importStoreUser($data)
    {
        $user = User::where("account_id", $data->id)->first();
        if ($user) return $user;
        if (!$data->phone) return null; 
        $en_phone = aesEncryptCBC($data->phone);
        $user = User::where(function($sql) use($en_phone, $data) {
            $sql->where("mobile", $data->phone)->orWhere("mobile", $en_phone);
        })->whereIn("source", [1,4])->first();
        if ($user) {
            User::where("id", $user->id)->update(["account_id"=>$data->id]);
            $user->account_id = $data->id;
            return $user;
        };
        DB::beginTransaction();
        $user = User::create([
            "name"=>$data->account_name,
            "mobile"=>$en_phone,
            "birthday"=>$data->birthday,
            "sex"=>$data->gender?:2,
            "stature"=>$data->height,
            "avatar"=>$data->avatar,
            "source"=>4,
            "account_id"=>$data->id,
            "unit"=>"kg",
            "fat_device"=>1,
        ]);

        UserInfo::create(['user_id'=>$user->id]);
        DB::commit();
        return $user;
    }

}


