<?php

/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2023/6/6
 * Time: 17:58
 */

namespace app\api\controller\shopro;

use app\admin\model\Addr;
use app\admin\model\shopro\goods\Goods as GoodsModel;
use app\admin\model\shopro\order\Goodsorder as GoodsorderModel;
use app\admin\model\shopro\order\Goodsorder as Goodsorders;
use app\admin\model\users\Users;
use app\admin\model\users\UsersAddr;
use app\api\model\PaymentLogModel;
use app\common\controller\Api;
use think\Db;
use think\Exception;

class Goodsorder extends Api
{

    protected $noNeedLogin = ['batchorder'];
    protected $noNeedRight = ['*'];

    /**
     * 订单列表
     */
    public function orderList()
    {
        $page = $this->request->param("page", 1);
        $status = $this->request->param("status", null); //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已发货(已自提),3=已完成
        $delivery_type = $this->request->param("delivery_type", 1); //发货方式:1=自提,2=物流配送
        $map = ['o.user_id' => $this->auth->id];
        if ($status != null) {
            $map['o.status'] = $status;
        }
        $map['delivery_type'] = $delivery_type;
        $list = Goodsorders::alias('o')
            ->join('goods g', 'o.goods_id = g.goods_id', 'left')
            ->where($map)
            ->field('o.*,g.title,g.intro,g.mall_price,g.price,g.photo')
            ->page($page)
            ->limit($this->pageSize)
            ->order('o.createtime desc')
            ->select();
        if (!$list) {
            $this->error('订单已不存在');
        }
        foreach ($list as $key => $val) {
            switch ($val['status']) {
                case -2:
                    $val['status_remark'] = '交易关闭';
                    break;
                case -1:
                    $val['status_remark'] = '交易关闭';
                    break;
                case 0:
                    $val['status_remark'] = '未支付';
                    break;
                case 1:
                    $val['status_remark'] = '已支付';
                    break;
                case 2:
                    $val['status_remark'] = '已发货(已自提)';
                    break;
                case 3:
                    $val['status_remark'] = '已完成';
                    break;
            }
        }
        $this->success('获取成功', ['list' => $list]);
    }

    /**
     * 订单列表
     */
    public function orderDetail()
    {
        $order_id = $this->request->param("order_id", 0);
        $map = ['o.id' => $order_id];
        $info = Goodsorders::alias('o')
            ->join('goods g', 'o.goods_id = g.goods_id', 'left')
            ->join('users_addr ua', 'ua.id = o.addr_id', 'left')
            ->join('addr a', 'a.ID = ua.area_id', 'left')
            ->where($map)
            ->field('o.*,g.title,g.intro,g.mall_price,g.price,g.photo,ua.address,ua.name,ua.mobile,a.MergerName')
            ->find();
        if (!$info) {
            $this->error('订单已不存在');
        }
        switch ($info['status']) {
            case -2:
                $info['status_remark'] = '交易关闭';
                break;
            case -1:
                $info['status_remark'] = '交易关闭';
                break;
            case 0:
                $info['status_remark'] = '未支付';
                break;
            case 1:
                $info['status_remark'] = '已支付';
                break;
            case 2:
                $info['status_remark'] = '已发货(已自提)';
                break;
            case 3:
                $info['status_remark'] = '已完成';
                break;
        }
        $this->success('获取成功', ['info' => $info]);
    }


    /**
     * 创建订单
     */
    public function addOrder()
    {
        $goods_id = $this->request->param('goods_id');
        if (empty($goods_id)) {
            $this->error("商品id有误");
        }
        $addr_id = $this->request->param('addr_id');
        if (empty($addr_id)) {
            $this->error("地址id有误");
        }
        $num = $this->request->param('num', 1);
        if ($num < 1) {
            $this->error("数量有误");
        }
        $activity_type = $this->request->param('activity_type', null);

        $remark = $this->request->param('remark');
        $goods = GoodsModel::where(['goods_id' => $goods_id])->find();
        $addr = UsersAddr::where(['id' => $addr_id])->find();
        try {
            Db::startTrans();
            $order_data = [
                'user_id' => $this->auth->id,
                'order_sn' => getOrdersn('goods'),
                'addr_id'   => $addr_id,
                'goods_id' => $goods_id,
                'total_amount' => ($goods['mall_price'] * $num) + $goods['goods_freight'],
                'pay_fee' => ($goods['mall_price'] * $num) + $goods['goods_freight'],
                'dispatch_amount' => $goods['goods_freight'],
                'status' => 0,
                'createtime' => time(),
                'delivery_type' => 2,
                'activity_list' => $activity_type,
                'num' => $num,
                'remark' => $remark,
                'phone' => $addr['mobile'],
                'consignee' => $addr['name'],
                'province_id' => $addr['province_id'],
                'city_id' => $addr['city_id'],
                'area_id' => $addr['area_id'],
                'address' => $addr['address'],
                'province_name' => Addr::where(['ID' => $addr['province_id']])->value("Name"),
                'city_name' => Addr::where(['ID' => $addr['city_id']])->value("Name"),
                'area_name' => Addr::where(['ID' => $addr['area_id']])->value("Name"),
            ];
            $order = GoodsorderModel::create($order_data);
            Db::commit();
            $this->success("下单成功", $order);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('提交订单失败', $e->getMessage());
        }
    }

    //订单支付
    public function orderPay()
    {
        $order_id = $this->request->param('order_id');
        if (empty($order_id)) {
            $this->error("订单id有误");
        }
        $order = GoodsorderModel::where(['id' => $order_id])->find();
        if (empty($order)) {
            $this->error("订单不存在");
        }
        if ($order['status'] != 0) {
            $this->error("该订单不是有效支付订单");
        }
        $is_shopping = $this->request->param('is_shopping', 0); //是否使用购物金
        $goods = GoodsModel::where(['goods_id' => $order['goods_id']])->find();
        if ($is_shopping == 1 && !in_array(2, explode(",", $goods['activity_list']))) {
            $this->error("该商品暂不能使用购物金");
        }

        try {
            Db::startTrans();
            $users = Users::where(['id' => $this->auth->id])->find();
            $pay_arr = [
                'user_id' => $this->auth->id,
                'order_sn' => $order['order_sn'],
                'order_id' => $order_id,
                'need_pay' => $order['pay_fee'],
                'order_type' => 'goods',
                'status' => 1,
                'createtime' => time(),
            ];

            if ($is_shopping == 1) { //使用购物金
                if ($users['shopping_money'] < $order['pay_fee']) {
                    $this->error("对不起，您的购物金不足");
                }
                $pay_arr['pay_way'] = 'shopping';
                $payment_log = PaymentLogModel::create($pay_arr);
                Users::addShoppingmoney($this->auth->id, -$order['pay_fee'], 9, "您购买" . $goods['title'] . "使用购物金抵扣" . $order['pay_fee'], $payment_log['id'], $pay_arr['order_id'], $users['shopping_money'], ($users['shopping_money'] - $order['pay_fee'])); //赠送购物金
                $ret = PaymentLogModel::dealGoodsBack(['out_trade_no' => $order['order_sn']]); //支付成功后回调
                GoodsorderModel::where(['id' => $order_id])->update(['activity_list' => '2']); //活动类型
                if (isset($ret) && $ret != true) {
                    Db::rollback();
                    $this->error('支付失败');
                }
                Db::commit();
                $this->success("支付成功", $ret);
            } else { //使用微信
                $pay_arr['pay_way'] = 'weixin';
                $payment_log = PaymentLogModel::create($pay_arr);
                Db::commit();
                $this->success('', $payment_log);
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('提交订单失败', $e->getMessage());
        }
    }

    /**
     * 定时任务取消订单
     */
    public function JobFailureOrder()
    {
        $order_id = $this->request->param("order_id");
        if (!empty($order_id)) {
            $order = GoodsorderModel::where(['id' => $order_id])->find();
            if (empty($order)) {
                $this->error("订单不存在");
            }
            if ($order['status'] != 0) {
                $this->error("该订单不是有效支付订单");
            }
            GoodsorderModel::where(['id' => $order_id])->update(['status' => '-1']);
            $this->success('订单取消成功');
        } else {
            GoodsorderModel::where(['status' => 0, 'createtime' => ['EGT', time() - 1800]])->update(['status' => '-2']); //
        }
    }

    /**
     * 确定订单
     */
    public function  confirmOrder()
    {
        $order_id = $this->request->param("order_id");
        $order = GoodsorderModel::where(['id' => $order_id])->find();
        if (empty($order)) {
            $this->error("订单不存在");
        }
        if ($order['status'] != 2) {
            $this->error("该订单暂未发货");
        }
        GoodsorderModel::where(['id' => $order_id])->update(['status' => '3']);
        //执行分佣
        Commission::divideCommission($order['order_sn']);
        $this->success('确认收货');
    }
    /**
     * 已发货订单自动确认完成
     */
    public function batchOrder()
    {
        $order = GoodsorderModel::where(['status' => 2])->select();
        if ($order) {
            foreach ($order as $k => $v) {
                GoodsorderModel::where(['id' => $v['id']])->update(['status' => '3']);
            }
        }
    }
}
