<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\Order as OrderModel;
use app\api\model\Setting as SettingModel;
use app\api\service\Order as OrderService;
use app\api\service\TransferRecord;
use app\api\service\User as UserService;
use app\common\enum\OrderType;
use app\common\model\TransferRecord as TransferRecordModel;
use app\common\model\UploadFile;
use app\common\service\qrcode\Extract as ExtractQRcode;
use cores\exception\BaseException;
use think\response\Json;
use app\common\model\MerchantRemarks as MerchantRemarksModel;
use app\api\service\Setting as SettingService;
use app\common\model\Standard as StandardModel;
use think\facade\Db;

/**
 * 我的订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Controller
{
    /**
     * 我的订单列表
     * @param string $dataType 订单类型
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DbException
     */
    public function list(string $dataType): Json
    {
        $model = new OrderModel;
        $list = $model->getList($dataType);
        return $this->renderSuccess(compact('list'));
    }

    public function del()
    {
        $model = new OrderModel;
        $res = $model->del();
        if ($res) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError('删除失败');
    }

    public function orderfast()
    {
        $model = new OrderModel;
        $res = $model->orderfast();
        if ($res) {
            return $this->renderSuccess('催单成功');
        }
        return $this->renderError('催单失败');
    }

    /**
     * 订单详情信息
     * @param int $orderId 订单ID
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(int $orderId): Json
    {
        // 订单详情
        $model = OrderModel::getUserOrderDetail($orderId);
        $MerchantRemarks = new MerchantRemarksModel;
        $merchant = $MerchantRemarks->orderRemarkList($orderId);
        $merchant = $MerchantRemarks->orderRemarkList($orderId);
        if ($merchant) {
            foreach ($merchant as $key => $value) {
                // 初始化 $image_id 为 null 或者一个默认值
                $image_id = null;
        
                if (isset($value['image_id']) && !empty($value['image_id'])) {
                    $decoded_image_id = json_decode($value['image_id'], true);
                    
                    // 检查 json_decode 是否成功并且结果中存在 'image_id' 键
                    if (is_array($decoded_image_id) && isset($decoded_image_id['image_id'])) {
                        $image_id = $decoded_image_id['image_id'];
                    }
                }
        
                if ($image_id !== null) { // 确保 $image_id 已经被设置
                    $item['image_id'] = $image_id;
                    $value['image_url'] = $MerchantRemarks->getRemarkImage($item['image_id']);
                }
            }
        }
        $model['merchant'] = $merchant;
        
        //获取商户id
        $merchantId = $model['merchant_id'];
        $storeId = $model['store_id'];
        //获取客服设置
        $service = new SettingService;
        $customer = $service->getGoodsCustomer($merchantId,$storeId);

        return $this->renderSuccess([
            'order' => $model,  // 订单详情
            'setting' => [
                // 积分名称
                'points_name' => SettingModel::getPointsName(),
            ],
            'customer' => $customer,
        ]);
    }

    /**
     * 获取调货单物流跟踪信息
     * @param int $orderId 订单ID
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function expressSearch(string $expressNo): Json
    {
        if (empty($expressNo)) {
            return $this->renderError('物流单号不能为空');
        }
        $transferRecordService = new TransferRecord();
        $data = $transferRecordService->getExpressByExpressNo($expressNo);
        $express = [];
        if (!empty($data['traces'])) {
            $express['items'] = $data['traces'];
            $express['express_name'] = $data['express']['express_name'];
            $express['express_no'] = $data['express_no'];
            return $this->renderSuccess($express);
        }
        return $this->renderError('暂无物流信息');

    }

    /**
     * 获取物流跟踪信息
     * @param int $orderId 订单ID
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function express(int $orderId): Json
    {
        $service = new OrderService;
        $express = $service->express($orderId);
        return $this->renderSuccess(compact('express'));
    }

    /**
     * 取消订单
     * @param int $orderId
     * @return Json
     * @throws BaseException
     */
    public function cancel(int $orderId): Json
    {
        $model = OrderModel::getDetail($orderId);
        if ($model->cancel()) {
            return $this->renderSuccess($model->getMessage());
        }
        return $this->renderError($model->getError() ?: '订单取消失败');
    }

    /**
     * 确认收货
     * @param int $orderId
     * @return Json
     * @throws BaseException
     */
    public function receipt(int $orderId): Json
    {
        $model = OrderModel::getDetail($orderId);
        if ($model->receipt()) {
            return $this->renderSuccess('确认收货成功');
        }
        return $this->renderError($model->getError());
    }

    /**
     * 获取当前用户行为数量
     * @return Json
     * @throws BaseException
     */
    public function actionCounts(): Json
    {
        $model = new OrderModel;
        $counts = $model->getActionCounts();
        $data = [
            'reservation_number' => $counts['reservation_number'],//预约记录
            'view_number' => $counts['view_number'],//浏览记录
            'send_number' => $counts['send_number'],//发货数量
            'integral_number' => $counts['integral_number'],//积分数量
            'coupon_number' => $counts['coupon_number'],//优惠券
            'goods_collect_number' => $counts['goods_collect_number'],//收藏商品数量
            'cart_number' => $counts['cart_number'],//购物车数量
            'take_goods_number' => $counts['take_goods_number'],//发货记录&提货记录
        ];
        return $this->renderSuccess($data);
    }

    /**
     * 获取当前用户待处理的订单数量
     * @return Json
     * @throws BaseException
     */
    public function todoCounts(): Json
    {
        $model = new OrderModel;
        $goods_counts = $model->getTodoCounts(OrderType::ORDER);
        $service_counts = $model->getTodoCounts(OrderType::SERVER);
        $recovery_counts = $model->getTodoCounts(OrderType::RECOVERY);
        $dealer_counts = $model->getTodoCounts(OrderType::DEALER);
//         var_dump($dealer_counts);
        $data = [
            'goods_order' => [
                'payment_number' => $goods_counts['payment_number'],//待付款
                'delivery_number' => $goods_counts['delivery_number'],//待发货
                'received_number' => $goods_counts['received_number'],//待收货
                'finish_number' => $goods_counts['finish_number'],//已完成
            ],
            'service_order' => [
                'confirm_number' => $service_counts['confirm_number'],//待确认
                'service_number' => $service_counts['service_number'],//待服务
                'payment_number' => $service_counts['payment_number'],//待支付
                'check_number' => $service_counts['check_number'],//已完成
            ],
            'recovery_order' => [
                'accepted_number' => $recovery_counts['accepted_number'],//待确认
                'already_number' => $recovery_counts['already_number'],//待服务ALREADY
                'cancel_number' => $recovery_counts['cancel_number'],//已取消
                'finish_number' => $recovery_counts['finish_number'],//已完成
            ],
            'distribution_order' => [//分销订单
                'payment_number' => $dealer_counts['payment_number'],//待付款
                'delivery_number' => $dealer_counts['delivery_number'],//待发货
                'received_number' => $dealer_counts['received_number'],//待收货
                'finish_number' => $dealer_counts['finish_number'],//已完成
                'retund_number' => $dealer_counts['refund_number'],//退款中
            ],
        ];
        return $this->renderSuccess($data);
    }

    /**
     * 获取自提核销二维码
     * @param int $orderId
     * @param string $channel 二维码渠道(小程序码、h5码)
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function extractQrcode(int $orderId, string $channel = 'H5'): Json
    {
        // 订单详情
        $order = OrderModel::getDetail($orderId);
        // 判断是否为待核销订单
        if (!$order->checkExtractOrder($order)) {
            return $this->renderError($order->getError());
        }
        // 当前用户信息
        $userInfo = UserService::getCurrentLoginUser();
        // 创建二维码
        $Qrcode = new ExtractQRcode($userInfo, $orderId, $channel);
        return $this->renderSuccess(['qrcode' => $Qrcode->getImage()]);
    }

    /**
     * 调货列表
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function transferList(): Json
    {
        $params = $this->request->param();
        $where = [];
        if (!empty($params['search'])) {
            $where[] = ['goods_sn', 'like', "%{$params["search"]}%"];
        }
        $list = TransferRecordModel::where('status', 1)
            ->where($where)
            ->order("id desc")
            ->paginate(10)->each(function ($item, $key) {
                $goods_sn = explode("、", $item['goods_sn']);
                $goods_num = explode("、", $item['goods_num']);
                $goods_price = explode("、", $item['goods_price']);
                $goods = [];
                $total_price = 0;
                foreach ($goods_sn as $seq => $value) {
                    $price = (float)$goods_price[$seq] ?? 0.00;
                    $goods[] = [
                        'name' => $value,
                        'price' => $price,
                        'num' => $goods_num[$seq] ?? 0,
                        "image" => 'https://imgservice5.suning.cn/uimg1/b2c/image/nXmtUUkwKxasCEBIX90d7w.png'
                    ];
                    $total_price += $price;
                }
                $item['goods'] = $goods;
                $item['total_price'] = $total_price;
                $transfer_image_ids = UploadFile::whereIn('file_id', explode(",", $item['transfer_image_id']))->field('file_id,file_path,file_type,storage,domain')->select();
                foreach ($transfer_image_ids as &$transfer_image_id) {
                    $transfer_image_id['file_path'] = getUrl($transfer_image_id['file_path'], $transfer_image_id['domain']);
                }

                $chat_image_ids = UploadFile::whereIn('file_id', explode(",", $item['chat_image_id']))->field('file_id,file_path,file_type,storage,domain')->select();
                foreach ($chat_image_ids as &$chat_image_id) {
                    $chat_image_id['file_path'] = getUrl($chat_image_id['file_path'], $chat_image_id['domain']);
                }
                $item['transfer_image_ids'] = $transfer_image_ids;
                $item['chat_image_ids'] = $chat_image_ids;
                return $item;
            })->toArray();
        return $this->renderSuccess($list);
    }


    public function editTransfer(): Json
    {
        $params = $this->request->param();
        $id = $params['id'] ?? 0;
        unset($params['id']);
        TransferRecordModel::where('id', $id)->update($params);
        return $this->renderSuccess('ok');
    }

    public function addTransfer(): Json
    {
        $params = $this->request->param();
        $storeid = request()->header()['storeid'];
        $params['user_id'] = \app\api\service\User::getCurrentLoginUserId();
        $params['store_id'] = $storeid;
        TransferRecordModel::create($params);
        return $this->renderSuccess('ok');
    }

    /**
      * 添加商家备注
      * @param int $orderId
      */
      public function addRemark(int $orderId): Json
      {   
          $data = $this->postForm();
          $data['store_id'] = $this->storeId;
          $data['user_id'] = $this->user['user_id'];
          $data['order_id'] = $orderId;
          $model = new MerchantRemarksModel;
          if(isset($data['image_id']) && !empty($data['image_id'])){
              $image_ids = $data['image_id'];
              $image = array(
                  "image_id" => $image_ids
              );
              $data['image_id'] = json_encode($image); 
          }
          if ($model->add($data)) {
              return $this->renderSuccess('操作成功');
          }
          return $this->renderError($model->getError() ?: '操作失败');
      }

    /**
     * 查看商家备注
     * @param int $orderId
     * @return Json
     */
    public function getRemark(int $orderId): Json
    {   
        $model = new MerchantRemarksModel;
        // 备注详情
        $list = $model->getRemarkImage($orderId);
        foreach ($list as $key => $value) {
            if (isset($value['image_id'])) {
                // 解码 JSON 字符串并确保返回的是数组
                $decodedImageId = json_decode($value['image_id'], true);
    
                if (is_array($decodedImageId) && isset($decodedImageId['image_id'])) {
                    $value['image_id'] = $decodedImageId['image_id'];                   
                    $value['image_url'] = UploadFile::getFileList($value['image_id']);
                }
            }
        }
        return $this->renderSuccess(compact('list'));    

    }

    /**
     * 提交审单记录
     */ 
    public function submitStandard(int $orderId): Json
    {
        $data = $this->postForm();
        $order = new OrderModel();
        $model = new StandardModel;
        $storeId = $this->storeId;
        $userId = $this->user['user_id'];
        $data['store_id'] = $storeId;
        $data['user_id'] = $userId;
        $data['order_id'] = $orderId;
        $data['standard_status'] = 30;
        $orderDetail = Db::name('order')->where('order_id',$orderId)->field('standard_num,order_id')->find();
        $standard_num = $model->where('order_id',$orderId)->count();

        if($orderDetail['standard_num'] == 0 && $standard_num > 0)
        {
            return $this->renderError('记录重复');
        }
        if($orderDetail['standard_num'] == 1 && $standard_num > 2)
        {
            return $this->renderError('记录重复');
        }
        if($orderDetail['standard_num'] >= 2)
        {
            return $this->renderError('记录重复');
        }

        try {
            Db::startTrans();
            if ($model->insertStandard($data)) {

                Db::name('order')->where('order_id',$orderId)->Inc('standard_num',1)->update(["standard_status"=>30,"is_standard"=>0]);
                Db::commit();
                return $this->renderSuccess('提交成功');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError($e->getMessage());
        }
 
 
    }

}