<?php

namespace App\Console\Commands\Temp;

use App\Modules\Book\Models\BookConfig;
use Illuminate\Console\Command;
use Hashids;
use Matrix\Exception;
use OSS\OssClient;
use OSS\Core\OssException;
use DB;

class GenAMSXmlFile extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'gen_ams_xml_file';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '腾讯商品库xml生成';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private $emails = [
        'lisy@zw88.net',
//        'songdb@iqiyoo.com',
       'zhoulj@iqiyoo.com',
//        'zhaoy@zw88.net'
    ];

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->genProductXml();

    }

    /**
     * genProductXml
     */
    public function genProductXml()
    {
        //筛选出上架状态为2的书籍上传
        $now          = date('Y-m-d H:i:s');
        $gdt_new_bids = DB::table('gdt_new_books')->where('is_deleted', 0)->where('start_time', '<=', $now)->where('end_time', '>=', $now)->pluck('bid')->toArray();
        $books        = BookConfig::join('books', 'book_configs.bid', '=', 'Books.id')
            ->leftjoin('book_categories', 'book_categories.id', 'books.category_id')
            ->leftjoin('chapters', 'books.last_cid', 'chapters.id')
            ->select(
                'books.intro',
                'books.status',
                'books.size',
                'books.chapter_count',
                'books.last_chapter',
                'book_configs.book_name',
                'book_configs.bid',
                'book_configs.cover',
                'book_configs.vip_seq',
                'book_configs.cover',
                'book_configs.is_on_shelf',
                'book_categories.id as second_category_id',
                'book_categories.pid as first_category_id',
                'book_categories.channel_name as first_category_name',
                'book_categories.category_name as second_category_name',
                'chapters.recent_update_at as latest_renew_time',
                'chapters.sequence as latest_renew_chapter'
            )
            //->where('book_configs.is_on_shelf','2')
            ->where(function ($query) {
                $query->where('book_configs.is_on_shelf', '2');
//                     ->orWhereIn('book_configs.bid', []);//豁免名单
            })
            ->get();
        $string       = <<<XML
<?xml version='1.0' encoding='utf-8'?>
<product_set>
</product_set>
XML;

        $xml = new \SimpleXMLElement($string);

        foreach ($books as $book) {
            //在管理后台设置为新书的书籍标记成新书
            $is_new_book = in_array($book->bid, $gdt_new_bids) ? '是' : '否';
            $bid         = Hashids::encode($book->bid);
            $data        =
                array(
                    'product_id'           => $bid,
                    'product_name'         => $book->book_name,
                    'first_category_id'    => $book->first_category_id,
                    'second_category_id'   => $book->second_category_id,
                    'first_category_name'  => $book->first_category_name,
                    'second_category_name' => $book->second_category_name,
                    'expiration_time'      => '2022-05-19 23:59:59',
                    'target_url_mobile'    => 'https://site8y1vm7kwvv850opx.wd.amanbook.com/detail?id=' . $bid,
                    'target_url_wechat'    => 'https://site8y1vm7kwvv850opx.wd.amanbook.com/detail?id=' . $bid,
                    'description'          => $this->special_filter(htmlspecialchars($book->intro)),
                    'image_url'            => $book->cover,
                    'word_count'           => $book->size,
                    'serial_status'        => $book->status == 1 ? '完结' : '连载',
                    'chapter_count'        => $book->chapter_count,
                    'started_pay_chapter'  => $book->vip_seq,
                    'latest_renew_time'    => $book->latest_renew_time,
                    'latest_renew_chapter' => $book->latest_renew_chapter,
                    'if_new_book'          => $is_new_book,
                    'pay_status'           => '付费',
                );
            $item        = $xml->addChild('product');
            if (is_array($data)) {
                foreach ($data as $key => $row) {
                    //生成子节点
                    try {
                        $node = $item->addChild($key, $row);

                    } catch (\Exception $e) {
                        $msg = "======腾讯商品库xml生成出错=====" . date("y-m-d H:i:s" . "\n");
                        \Log::info($msg);
                        \Log::info($e->getMessage());
                        $notify = MessageNotify::mail([
                            'to_emails'   => implode(",", $this->emails),
                            'subject'     => $msg,
                            'body'        => $e->getMessage(),
                            'delay_times' => 0,
                        ]);
                        $notify->notify();
                        exit();
                    }

                }
            }
        }
        $file_path = 'storage/tx_product.xml';
        echo $xml->asXML($file_path);

        //上传到OSS
        $ori_file    = DB::table('tencent_product_configs')->where('type', 'SITE_MAP_XML_URL')->first();
        $verify_code = md5_file($file_path);
        if ($ori_file && $ori_file->verify_code == $verify_code) {
            \Log::info("======腾讯商品库xml已是最新=====" . date("y-m-d H:i:s" . "\n"));
        } else {
            $file_name = 'tx_product_wdy.xml';

            //解析一遍看是否出错
            try {
                $load_xml = simplexml_load_file($file_path);

            } catch (\Exception $e) {

                $msg = "======腾讯商品库xml解析出错=====" . date("y-m-d H:i:s" . "\n");
                \Log::info($msg);
                \Log::info($e->getMessage());
                $notify = MessageNotify::mail([
                    'to_emails'   => implode(",", $this->emails),
                    'subject'     => $msg,
                    'body'        => $e->getMessage(),
                    'delay_times' => 0,
                ]);
                $notify->notify();
                //删除文件以防权限问题
                if (file_exists($file_path)) unlink($file_path);
                exit();
            }
            $url = $this->saveXmlToOss($file_name, $file_path);
            DB::table('tencent_product_configs')
                ->updateOrInsert(
                    ['type' => 'SITE_MAP_XML_URL'],
                    [
                        'value'       => $url,
                        'updated_at'  => date('Y-m-d H:i:s'),
                        'verify_code' => $verify_code,
                    ]
                );
        }
        //上传到OSS后删除,防止权限问题
        if (file_exists($file_path)) unlink($file_path);
        \Log::info("======腾讯商品库xml生成=====" . date("y-m-d H:i:s" . "\n"));
        return;


    }


    public function dealSpecialCharacters($char)
    {
        $char = preg_replace("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", '', $char);
        $char = preg_replace("/&/", '&amp', $char);
        $char = preg_replace("/'/", '&apos', $char);
        $char = preg_replace("/\"/", '&quot', $char);
        $char = preg_replace("/</", '&lt', $char);
        $char = preg_replace("/>/", '&gt', $char);

        return $char;
    }

    private function special_filter($string)
    {
        if (!$string) return '';

        $new_string = '';
        for ($i = 0; isset($string[$i]); $i++) {
            $asc_code = ord($string[$i]);    //得到其asc码

            // 以下代码旨在过滤非法字符
            // ** 数值 8、9、10 和 13 可以分别转换为退格符、制表符、换行符和回车符。
            // 这些字符都没有图形表示,但是对于不同的应用程序,这些字符可能会影响文本的显示效果。
            if (in_array($asc_code, [8, 9, 10, 13], true)) {
                $new_string .= '';
            } else {
                $new_string .= $string[$i];
            }
        }

        return trim($new_string);
    }

    /**
     * 将xml保存到oss
     * @return string
     */
    function saveXmlToOss($file_name, $file)
    {
        $accessKeyId     = env('OSS_ACCESS_ID');
        $accessKeySecret = env('OSS_ACCESS_KEY');
        $endpoint        = env('OSS_END_POINT');
        $bucket          = env('OSS_BUCKET');
        try {
            $ossClient  = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $upload_res = $ossClient->uploadFile($bucket, $file_name, $file);
            \Log::info('saveXmlToOss:'.$bucket.' $file_name:'.$file_name.' $file:'.$file);
            $url        = str_ireplace('wangduyun.oss-cn-hangzhou.aliyuncs.com', 'cdn-novel.wd.amanbook.com', $upload_res['oss-request-url']);
            $url        = str_ireplace('http://', 'https://', $url);

        } catch (OssException $e) {
            \Log::info($e->getMessage());
        }
        return $url;
    }

}