<?php

namespace app\common\model\unishop;

use app\common\model\unishop\Product;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use think\Db;
class OrderProduct extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'unishop_order_product';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];

    /**
     * 插入订单商品表
     * @param array $goodArr 商品信息
     * @param int $user_id   用户ID
     * @param int $order_id  订单ID
     * @return bool
     */
    public function add(array $goodArr,int $user_id,int $order_id){
        try {
            $Goods = new Product();
            foreach ($goodArr as $key=>$value){
                $good_info = Db::name("unishop_product")->find($value['goods_id']);
                if(!empty($good_info)){
                    $data['user_id'] = $user_id;
                    $data['order_id'] = $order_id;
                    $data['product_id'] = $value['goods_id'];
                    $data['title'] = $good_info['title'];
                    $data['image'] = $good_info['image'];
                    $data['number'] = $value['buy_number'];
                    $data['price'] = $good_info['sales_price'];
                    $data['product_json'] = json_encode($good_info,JSON_UNESCAPED_UNICODE);
                    $data['amounts'] = $Goods->computePrice($value['goods_id'],$value['buy_number']);
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    $data['spec'] = 0;
                    $data['images'] = $good_info['images'];

                    self::insert($data);

                }
            }

            return  true;
        }catch (Exception $e) {

            return false;
        }

    }
    

}
