<?php
namespace app\workerapi\logic\shops;
use app\common\logic\BaseLogic;
use app\common\model\article\Article;
use app\common\model\decorate\DecoratePage;
use app\common\model\decorate\DecorateTabbar;
use app\common\model\setting\PostageRegion;
use app\common\model\shops\ShopAddress;
use app\common\model\shops\ShopCart;
use app\common\model\shops\ShopGoods;
use app\common\model\shops\ShopGoodSpecsInventory;
use app\common\model\shops\ShopOrderGoods;
use app\common\model\shops\ShopOrders;
use app\common\model\user\UserAddress;
use app\common\service\ConfigService;
use app\common\service\FileService;
use think\db\Query;
use think\Exception;
use think\facade\Db;


/**
 * 订单
 */
class ShopOrderLogic extends BaseLogic
{
    /**
     * 提交订单
     * @param array $params
     * @return array|false
     */
    public static function submitOrder($params)
    {
        Db::startTrans();
        try {
            //获取购物车商品
            $shop_carts = ShopCart::whereIn('id',$params['shop_cart_id'])->where('worker_id',$params['user_id'])->select()->toArray();
            if(empty($shop_carts)){
                throw new Exception('购物车商品不存在');
            }
            $addressInfo = ShopAddress::field('area,address,house_number,contact_number,contact_people')->findOrEmpty($params['address_id']);
            if($addressInfo->isEmpty()){
                throw new \Exception('收货地址不存在');
            }
            //生成订单编号
            $sn = generate_sn(ShopOrders::class, 'sn');
            $shop_order_goods = array();

            $amount_total = 0;//总价
            $amount = 0;//应支付价格
            //验证商品库存是否存在
            foreach ($shop_carts as $v){
                $inventory = ShopGoodSpecsInventory::where('id',$v['goods_specs_inventory_id'])->findOrEmpty();
                $shop_good = ShopGoods::where('id',$v['shop_goods_id'])->findOrEmpty()->toArray();
                if($inventory->remaining_inventory<$v['number']){
                    throw new Exception($shop_good['goods_name'].'库存不足');
                }
                //新增订单商品镜像
                $shop_order_goods[] = [
                    'sn'=>$sn,
                    'shop_goods_id'=>$shop_good['id'],
                    'goods_category_ids' => $shop_good['goods_category_ids'],
                    'goods_category_id' => $shop_good['goods_category_id'],
                    'goods_name' => $shop_good['goods_name'],
                    'goods_image' => $shop_good['goods_image'],
                    'goods_banners' => $shop_good['goods_banners'],
                    'company_name' => $shop_good['company_name'],
                    'description' => $shop_good['description'],
                    'specs_type' => $shop_good['specs_type'],
                    'custom_attribute_items'=>json_encode($shop_good['custom_attribute_items'],JSON_UNESCAPED_UNICODE),
                    'goods_specs_inventory_id'=>$v['goods_specs_inventory_id'],
                    'specs'=>json_encode($inventory->specs,JSON_UNESCAPED_UNICODE),
                    'number'=>$v['number'],
                    'service_total'=>$inventory->service_total,
                    'service_fee'=>$inventory->service_fee
                ];

                //减少商品库存
                $inventory->remaining_inventory = $inventory->remaining_inventory-$v['number'];
                $inventory->save();

                $amount_total += $inventory['service_total']*$v['number'];
                $amount += $inventory['service_fee']*$v['number'];
            }

            //生成订单
            $order = ShopOrders::create([
                'shop_order_type' => 1,
                'worker_id' => $params['user_id'],
                'sn' => $sn,
                'real_name' => $addressInfo->contact_people,
                'mobile' => $addressInfo->contact_number,
                'address' => trim($addressInfo->area .$addressInfo->address . $addressInfo->house_number),
                'pay_status' => 0,
                'paw_way' => 2,
                'order_terminal' => $params['terminal'],
                'amount_total' => $amount_total,
                'order_amount' => $amount,
                'address_json' => $addressInfo->toArray()
            ]);

            //生成订单商品镜像
            $ShopOrderGoods = new ShopOrderGoods();
            $ShopOrderGoods->saveAll($shop_order_goods);
            //清除购物车商品
            ShopCart::whereIn('id',$params['shop_cart_id'])->delete();
            Db::commit();
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }

        return [
            'order_id' => (int)$order['id'],
        ];
    }

    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/18 13:51
     */
    public static function detail($params): array
    {
        $detail = ShopOrders::with(['orderGoods'=>function(Query $query){
            $query->field(['sn','goods_name','goods_image','number','service_fee','service_total','company_name','delivery_type','shop_goods_type','goods_specs_inventory_id','specs_type','custom_attribute_items','specs'])->append(['spec_arr','delivery_type_text','shop_goods_type_text']);
        }])->withCount('orderlogistic')->field('id, sn, real_name,mobile, address,address_json,pay_time, paw_way,pay_sn, pay_status, refund_status, refund_transaction_id,create_time,shop_order_type,amount_total, order_amount')
        ->append(['pay_way_text','pay_status_text','refund_status_text'])->where(['sn'=> $params['sn'],'worker_id'=>$params['worker_id']])->findOrEmpty()->toArray();
        if(empty($detail)){
            return [];
        }
        $orderGoodsArr = [];
        $companyNameArr = array_unique(array_column($detail['orderGoods'],'company_name'));
        foreach($companyNameArr as  $val) {
            $orderGoods = [];
            foreach ($detail['orderGoods'] as $goodVal) {
                if($val == $goodVal['company_name']){
                    unset($goodVal['goodsSpecsInventory'], $goodVal['custom_attribute_items'], $goodVal['specs'], $goodVal['sn'], $goodVal['goods_specs_inventory_id'],$goodVal['company_name']);
                    $orderGoods[] = $goodVal;
                }
            }
            if(!empty($orderGoods)){
                $orderGoodsArr[] = [
                    'company_name' => $val,
                    'goods' => $orderGoods
                ];
            }
        }
        $detail['orderGoods'] = $orderGoodsArr;
        return $detail;
    }


    public static function cancelOrder($params):bool
    {
        Db::startTrans();
        try {
            $orderModel =  ShopOrders::with('orderGoods.goodsSpecsInventory')->where([
                'shop_order_type' => 1,
                'worker_id' => $params['worker_id'],
                'sn'=>$params['sn']
            ])->findOrEmpty();
            if($orderModel->isEmpty()){
                throw new \Exception('订单不存在或不是待支付状态');
            }
            if($orderModel->orderGoods()->count() === 0){
                throw new \Exception('订单商品不存在');
            }
            $updateData = [];
            foreach($orderModel->orderGoods as $goods){
               if(isset($goods->goodsSpecsInventory->remaining_inventory)){
                   $updateData[$goods->goodsSpecsInventory->id] = ['remaining_inventory'=> $goods->goodsSpecsInventory->remaining_inventory+= $goods['number']];
               }
            }
            if(!empty($updateData)){
                ShopGoodSpecsInventory::updateWhenCase($updateData);
            }
            $orderModel->shop_order_type = 0;
            $orderModel->save();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * 物流详情
     * @param $params
     * @return array
     */
    public static function logisticDetail($params): array
    {

        try{
            $detail = ShopOrders::with(['orderGoods'=>function(Query $query){
                $query->field(['sn','shop_goods_id','goods_name','goods_image','company_name','delivery_type','shop_goods_type'])->append(['delivery_type_text','shop_goods_type_text']);
            },'orderlogistic' =>function (Query $query){
                $query->field(['id','order_id','express_id','shop_goods_id','logistic_number','logistic_status'])->append(['logistic_status_text']);
                $query->with('express');
            }])->field('id, sn')->where(['sn'=> $params['sn'],'worker_id'=>$params['worker_id']])->findOrEmpty()->toArray();
            if(empty($detail)){
                throw new \Exception('订单不存在');
            }
            $orderGoodsArr = [];
            $companyNameArr = array_unique(array_column($detail['orderGoods'],'company_name'));
            foreach($companyNameArr as  $val) {
                $orderGoods = [];
                foreach ($detail['orderGoods'] as $goodVal) {
                    if($val == $goodVal['company_name'] && !isset($orderGoods[$goodVal['shop_goods_id']])){
                        unset($goodVal['goodsSpecsInventory'], $goodVal['custom_attribute_items'], $goodVal['specs'], $goodVal['sn'], $goodVal['goods_specs_inventory_id'],$goodVal['company_name']);
                        $goodVal['logistic'] = [];
                        foreach($detail['orderlogistic'] as $logisticVal){
                            if($goodVal['shop_goods_id'] == $logisticVal['shop_goods_id']){
                                $logisticVal['expresss_name'] = $logisticVal['express']['name'];
                                unset($logisticVal['express']);
                                $goodVal['logistic'][] = $logisticVal;
                            }
                        }
                        $orderGoods[$goodVal['shop_goods_id']] = $goodVal;
                    }
                }
                if(!empty($orderGoods)){
                    $orderGoodsArr[] = [
                        'company_name' => $val,
                        'goods' =>array_values( $orderGoods)
                    ];
                }
            }
            return $orderGoodsArr;
        } catch(\Exception $e){
            self::setError($e->getMessage());
            return [];
        }
    }

    /**
     * 确认收货
     * @param $params
     * @return bool
     */
    public static function confirmReceipt($params):bool
    {
        try{
            Db::startTrans();
            $orderModel =  ShopOrders::where([
                'shop_order_type' => 2,
                'worker_id' => $params['worker_id'],
                'sn'=>$params['sn']
            ])->findOrEmpty();
            if($orderModel->isEmpty()){
                throw new \Exception('订单不存在或不是待收货状态');
            }
            $orderModel->shop_order_type = 4;
            $orderModel->save();
            Db::commit();
            return true;
        }catch(\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function deleteOrder($params):bool
    {
        try{
            $orderModel =  ShopOrders::where([
                'shop_order_type' => 0,
                'worker_id' => $params['worker_id'],
                'sn' => $params['sn']
            ])->findOrEmpty();
            if($orderModel->isEmpty()){
                throw new \Exception('订单不存在');
            }
            $orderModel->delete();
            return true;
        } catch(\Exception $e){
            self::setError($e->getMessage());
            return false;
        }
    }
}