<?php

namespace app\admin\controller;

use app\admin\model\system\SystemAttachment;
use app\admin\model\system\SystemAttachmentCategory;
use app\Request;
use crmeb\services\UtilService;
use think\facade\Log;


class PublicAdmin
{
    /**
     * 上传远程图片
     * 
     * 参数
     * 
     * {
     *  "products": [{
     *    "name": "product name",
     *    "images":[
     *      [主图列表], [属性图列表], [详情图列表],
     *    ]
     *   }, {},
     *   {}
     *  ]
     * }
     */
    public function reg_images(Request $request)
    {
        list($products) = UtilService::postMore([
            ['products', []]
        ], $request, true);
        $key = $request->param('k');
        if ($key != 'twong') {
            return app('json')->fail('unknown');
        }

        $parent = strftime('%Y-%m');
        $upload_type = 5;
        // 新建月份分类
        $res = SystemAttachmentCategory::where(['pid'=>0, 'name'=>$parent])->find();
        if (!$res) {
            $res = SystemAttachmentCategory::create([
                'pid'=> 0,
                'name' => $parent
            ]);
            if (!$res) {
                return app('json')->fail("新建分类失败");
            }
            $res = $res->toArray();
        } else {
            $res = $res->toArray();
        }

        $has_error = false;

        foreach($products as $pdt) {
            // 新建产品分类
            if (!isset($pdt['name'])) {
                return app('json')->fail('参数错误, 产品名为空');
            }
            if (!isset($pdt['images']) || count($pdt['images']) < 3 ||
                (count($pdt['images'][0]) <= 0 || count($pdt['images'][2]) <= 0)) {
                return app('json')->fail('参数错误, 请检查产品信息:' . $pdt['name']);
            }
            // 产品名称取 10 个字符
            $pname = mb_substr($pdt['name'], 0, 10);
            // 避免重复
            $pdt_cate = SystemAttachmentCategory::where(['pid'=>$res['id'], 'name'=>$pname])->find();
            if (!$pdt_cate) {
                $pdt_cate = SystemAttachmentCategory::create([
                    'pid' => $res['id'],
                    'name' => $pname,
                ]);
                if (!$pdt_cate) {
                    return app('json')->fail('新建产品分类失败');
                }
            }

            // 插入所有图片
            $pid = $pdt_cate->id;
            $now = time();
            for ($i=0; $i<3; $i++) {
                foreach($pdt['images'][$i] as $url) {
                    $fileInfo = [
                        'name' => basename($url),
                        'size' => 0,
                        'type' => 'image/jpeg',
                        'dir'  => $url,
                        'thumb_path' => $url,
                        'time' => $now,
                    ];
                    if ($fileInfo){
                        try {
                            $ok = SystemAttachment::attachmentAdd($fileInfo['name'], $fileInfo['size'], $fileInfo['type'], $fileInfo['dir'], $fileInfo['thumb_path'], $pid, $upload_type, $fileInfo['time']);
                            if(!$ok) {
                                $has_error = true;
                                Log::warning('upload image failed:' . $url . ' name:' . $pdt['name']);
                            }
                        } catch (\Exception $e) {
                            $has_error = true;
                            Log::warning('upload image exception:' . $url . 'name:' . $pdt['name'] . ' exception:' . $e->getMessage());
                        }                        
                    }else {
                        $has_error = true;
                        Log::warning('get image info failed:' . $url . ' name:' . $pdt['name']);
                    }
                }
            }
        } // foreach
        app('json')->successful(['code'=> 0, 'msg'=> $has_error ? 'error' : 'ok']);
    } // reg_images
}