<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\shops;


use app\common\model\shops\ShopOrderLogistic;
use app\common\model\shops\ShopOrders;
use app\common\logic\BaseLogic;
use app\workerapi\logic\shops\ShopOrderLogic;
use think\db\Query;
use think\facade\Db;


/**
 * ShopOrders逻辑
 * Class ShopOrdersLogic
 * @package app\adminapi\logic\shops
 */
class ShopOrdersLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/08/04 13:49
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            ShopOrders::create([
                'shop_order_type' => $params['shop_order_type'],
                'worker_id' => $params['worker_id'],
                'sn' => $params['sn'],
                'real_name' => $params['real_name'],
                'mobile' => $params['mobile'],
                'address' => $params['address'],
                'pay_time' => strtotime($params['pay_time']),
                'pay_status' => $params['pay_status'],
                'pay_sn' => $params['pay_sn'],
                'paw_way' => $params['paw_way'],
                'order_terminal' => $params['order_terminal'],
                'amount_total' => $params['amount_total'],
                'amount' => $params['amount'],
                'transaction_id' => $params['transaction_id'],
                'refund_status' => $params['refund_status'],
                'refund_transaction_id' => $params['refund_transaction_id'],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/08/04 13:49
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            ShopOrders::where('id', $params['id'])->update([
                'shop_order_type' => $params['shop_order_type'],
                'worker_id' => $params['worker_id'],
                'sn' => $params['sn'],
                'real_name' => $params['real_name'],
                'mobile' => $params['mobile'],
                'address' => $params['address'],
                'pay_time' => strtotime($params['pay_time']),
                'pay_status' => $params['pay_status'],
                'pay_sn' => $params['pay_sn'],
                'paw_way' => $params['paw_way'],
                'order_terminal' => $params['order_terminal'],
                'amount_total' => $params['amount_total'],
                'amount' => $params['amount'],
                'transaction_id' => $params['transaction_id'],
                'refund_status' => $params['refund_status'],
                'refund_transaction_id' => $params['refund_transaction_id'],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/08/04 13:49
     */
    public static function delete(array $params): bool
    {
        return ShopOrders::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/08/04 13:49
     */
    public static function detail($params): array
    {
        return ShopOrders::with([
            'worker'=>function(Query $query) {
                $query->field("id,worker_number,real_name");
            },'orderGoods'=>function(Query $query){
                $query->field("id,sn,shop_goods_id,goods_name,goods_image,goods_banners,description,specs_type,custom_attribute_items,specs,number,service_total,service_fee")->append(['spec_arr']);
            },'orderlogistic'=>function (Query $query) {
                $query->field("id,order_id,shop_goods_id,express_id,logistic_number,logistic_status,create_time,update_time")->append(['logistic_status_text']);
                $query->with('express');
            }])->findOrEmpty($params['id'])->toArray();
    }

    public static function logisticInfo($params):array
    {
        $detail = ShopOrders::with(['orderlogistic'=>function (Query $query) {
            $query->field("id,order_id,shop_goods_id,express_id,logistic_number,logistic_status")->append(['logistic_status_text']);
        },'orderGoods'=>function(Query $query){
            $query->field("id,sn,shop_goods_id,goods_name,goods_image,goods_banners,description,specs_type,custom_attribute_items,specs,number,service_total,service_fee")->append(['spec_arr']);
        }])->findOrEmpty($params['id'])->toArray();
        $orderGoods = [];
        if(isset($detail['orderGoods'])){
            foreach ($detail['orderGoods'] as $orderGood){
                $orderGoods[$orderGood['shop_goods_id']] = $orderGood;
            }
        }
        $detail['goods'] = $orderGoods;
        return $detail;
    }

    public static function saveLogistic($params)
    {
        try{
            Db::startTrans();
            $orderModel = ShopOrders::with(['orderlogistic'=>function (Query $query) {
                $query->field("id,order_id,shop_goods_id,express_id,logistic_number,logistic_status");
            }])->findOrEmpty($params['id']);

            if($orderModel->isEmpty()){
                throw  new \Exception('订单不存在');
            }
            if(!in_array($orderModel->shop_order_type,[2,3,4])){
                throw  new \Exception('订单类型不支持');
            }
            $existIds = $orderModel->orderlogistic()->column('id');
            $takeOverFlag = true;
            $deliverGoodsFlag = true;
            $saveLogisticArr = [];
            $updateLogisticArr = [];
            foreach ($params['logistic_data'] as $logistic){
                if(intval($logistic['logistic_status']) ===  0){
                    $takeOverFlag = false;
                }
                if(intval($logistic['logistic_status'])!== 3){
                    $deliverGoodsFlag = false;
                }
                if(!empty($logistic['id']) && in_array($logistic['id'],$existIds)){
                    $updateLogisticArr[$logistic['id']] = [
                        'shop_goods_id' => $logistic['shop_goods_id'],
                        'express_id' => $logistic['express_id'],
                        'logistic_number' => $logistic['logistic_number'],
                        'logistic_status' => $logistic['logistic_status'],
                        'update_time' => time(),
                    ];
                    array_splice($existIds,array_search($logistic['id'], $existIds),1);
                    continue;
                }
                $saveLogisticArr[] = [
                    'order_id' => $orderModel->id,
                    'shop_goods_id' => $logistic['shop_goods_id'],
                    'express_id' => $logistic['express_id'],
                    'logistic_number' => $logistic['logistic_number'],
                    'logistic_status' => $logistic['logistic_status'],
                    'create_time' => time(),
                    'update_time' => time(),
                ];
            }
            if(!empty($updateLogisticArr)){
                ShopOrderLogistic::updateWhenCase($updateLogisticArr);
            }
            if(!empty($saveLogisticArr)){
                ShopOrderLogistic::insertAll($saveLogisticArr);
            }
            if(!empty($existIds)){
                ShopOrderLogistic::destroy($existIds);
            }
            if($takeOverFlag && $orderModel->shop_order_type !== 3){
                $orderModel->shop_order_type = 2;
                $orderModel->save();
            }
            Db::commit();
            return true;
        } catch(\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }

    }
}