<?php



namespace app\common\repositories\store\product;

use app\common\repositories\BaseRepository;
use app\common\repositories\system\merchant\MerchantRepository;
use ln\services\CopyProductService;
use ln\services\CrmebServeServices;
use ln\services\DownloadImageService;
use Exception;
use think\exception\ValidateException;
use app\common\dao\store\product\ProductCopyDao;
use think\facade\Db;

class ProductCopyRepository extends BaseRepository
{
    protected $host = ['taobao', 'tmall', 'jd', 'pinduoduo', 'suning', 'yangkeduo','1688'];

    protected $dao;

    /**
     * ProductRepository constructor.
     * @param dao $dao
     */
    public function __construct(ProductCopyDao $dao)
    {
        $this->dao = $dao;
    }

    public function copyProduct(array $data,?int $merId)
    {
        $type = $data['type'];
        $id = $data['id'];
        $shopid = $data['shopid'];
        $url = $data['url'];
        $apikey = systemConfig('copy_product_apikey');
        if ((!$type || !$id) && $url) {
            $url_arr = parse_url($url);
            if (isset($url_arr['host'])) {
                foreach ($this->host as $name) {
                    if (strpos($url_arr['host'], $name) !== false) {
                        $type = $name;
                    }
                }
            }
            $type = ($type == 'pinduoduo' || $type == 'yangkeduo') ? 'pdd' : $type;
            try{
                switch ($type) {
                    case 'taobao':
                    case 'tmall':
                        $params = [];
                        if (isset($url_arr['query']) && $url_arr['query']) {
                            $queryParts = explode('&', $url_arr['query']);
                            foreach ($queryParts as $param) {
                                $item = explode('=', $param);
                                if (isset($item[0]) && $item[1]) $params[$item[0]] = $item[1];
                            }
                        }
                        $id = $params['id'] ?? '';
                        break;
                    case 'jd':
                        $params = [];
                        if (isset($url_arr['path']) && $url_arr['path']) {
                            $path = str_replace('.html', '', $url_arr['path']);
                            $params = explode('/', $path);
                        }
                        $id = $params[1] ?? '';
                        break;
                    case 'pdd':
                        $params = [];
                        if (isset($url_arr['query']) && $url_arr['query']) {
                            $queryParts = explode('&', $url_arr['query']);
                            foreach ($queryParts as $param) {
                                $item = explode('=', $param);
                                if (isset($item[0]) && $item[1]) $params[$item[0]] = $item[1];
                            }
                        }
                        $id = $params['goods_id'] ?? '';
                        break;
                    case 'suning':
                        $params = [];
                        if (isset($url_arr['path']) && $url_arr['path']) {
                            $path = str_replace('.html', '', $url_arr['path']);
                            $params = explode('/', $path);
                        }
                        $id = $params[2] ?? '';
                        $shopid = $params[1] ?? '';
                        break;
                    case '1688':
                        $params = [];
                        if (isset($url_arr['query']) && $url_arr['query']) {
                            $path = str_replace('.html', '', $url_arr['path']);
                            $params = explode('/', $path);
                        }
                        $id = $params[2] ?? '';
                        $shopid = $params[1] ?? '';
                        $type = 'alibaba';
                        break;

                }
            }catch (Exception $exception){
                throw new ValidateException('url有误');
            }
        }
        $result = CopyProductService::getInfo($type, ['itemid' => $id, 'shopid' => $shopid], $apikey);

        if ($result['status']) {
            $this->add([
                'type'  => $data['type']?: 'copy',
                'num'   => -1,
                'info'   => $data['url'],
                'message' => '复制商品「'.$result['data']['store_name'] .'」'
            ],$merId);
            return ['info' => $result['data']];
        } else {
            throw new ValidateException($result['msg']);
        }
    }

    /**
     * TODO 一号通复制
     * @param array $data
     * @param int|null $merId
     * @return array
     * @author Qinii
     * @day 7/27/21
     */
    public function crmebCopyProduct(array $data,?int $merId)
    {
        $result = app()->make(CrmebServeServices::class)->copy()->goods($data['url']);
        if ($result) {
            $this->add([
                'type'  => 'copy',
                'num'   => -1,
                'info'   => $data['url'],
                'message' => '复制商品「'.$result['store_name'] .'」'
            ],$merId);
        }

        if (!is_array($result['slider_image'])){
            $result['slider_image']  = json_decode($result['slider_image']);
        }
        if ($result['items']) {
            foreach ($result['items'] as $k => $item) {
                if ($item['value'] == '') unset($result['items'][$k]);
            }
            $result['spec_type'] = 1;
            $result['info'] = app()->make(CopyProductService::class)->formatAttr($result['items']);
        }else{
            $result['spec_type'] = 0;
            $result['info'] = null;
        }

        return ['info' => $result];
    }
    /**
     * TODO 添加记录并修改数据
     * @param $data
     * @param $merId
     * @author Qinii
     * @day 2020-08-06
     */
    public function add($data,$merId)
    {
        $make = app()->make(MerchantRepository::class);
        $getOne = $make->get($merId);

        switch ($data['type']) {
            case 'mer_dump':
                //nobreak;
            case 'pay_dump':
                $field = 'export_dump_num';
                break;
            case 'sys':
                //nobreak;
            case 'taobao':
                //nobreak;
            case 'jd':
                //nobreak;
            case 'pay_copy':
                //nobreak;
            case 'copy':
                $field = 'copy_product_num';
                break;
            default:
                break;
        }


        $number = $getOne[$field] + $data['num'];
        $arr = [
            'type'  => $data['type'],
            'num'   => $data['num'],
            'info'   => $data['info']??'' ,
            'mer_id'=> $merId,
            'message' => $data['message'] ?? '',
            'number' => ($number < 0) ? 0 : $number,
        ];
        Db::transaction(function()use($arr,$make,$field){
            $this->dao->create($arr);
            if ($arr['num'] < 0) {
                $make->sumFieldNum($arr['mer_id'],$arr['num'],$field);
            } else {
                $make->addFieldNum($arr['mer_id'],$arr['num'],$field);
            }
        });
    }

    /**
     * TODO 默认赠送复制次数
     * @param $merId
     * @author Qinii
     * @day 2020-08-06
     */
    public function defaulCopyNum($merId)
    {
        if(systemConfig('copy_product_status')){
            $data = [
                'type' => 'sys',
                'num' => systemConfig('copy_product_defaul'),
                'message' => '赠送次数',
            ];
            $this->add($data,$merId);
        }
    }

    public function getList(array $where,int $page, int $limit)
    {
        $query = $this->dao->search($where)->with([
            'merchant' => function ($query) {
                return $query->field('mer_id,mer_name');
            }
        ]);
        $count = $query->count();
        $list = $query->page($page,$limit)->select();
        return compact('count','list');
    }

    /**
     * 保存复制商品
     * @Author:Qinii
     * @Date: 2020/10/9
     * @param array $data
     */
    public function create(array $data)
    {
        $serve = app()->make(DownloadImageService::class);
        if (is_int(strpos( $data['image'], 'http')))
            $arcurl =  $data['image'];
        else
            $arcurl = 'http://' . ltrim( $data['image'], '\//');
        $image = $serve->downloadImage($arcurl,'',systemConfig('upload_type'));
        $data['image'] = $image['path'];
        app()->make(ProductRepository::class)->create($data, 0);
    }
}
