<?php
/**
 *
 * @file:RefundOrderSeivce.php
 * @Date: 2023/5/29
 * @Time: 09:48
 */


namespace Modules\OrderRefund\Services;

use App\Libs\Pay\Palmpay;
use Illuminate\Support\Facades\DB;
use Modules\Channel\Services\Order\OrderService;
use Modules\Manage\Models\Miniprogram;
use Modules\OrderRefund\Models\OrdersRefundVerify;
use Modules\User\Models\User;

class RefundOrderService extends BaseServices
{

    /**
     *  退款订单查询
     * name: orderList
     * @param array $param
     * date 2023/05/29 09:58
     */
    public static function orderList(array $param, $isAll = false)
    {
        $list = self::listQuery($param);
        $list->orderBy("orders_refund_verify.refund_status", 'asc')->orderBy("orders_refund_verify.id", 'desc')->select("orders_refund_verify.id", 'orders_refund_verify.order_id', "orders_refund_verify.uid", "orders_refund_verify.pt_verify_remark", "orders_refund_verify.user_id", "orders_refund_verify.sh_verify_remark", "orders_refund_verify.sh_verify_status", "orders_refund_verify.pt_verify_status", "orders_refund_verify.pay_at", "orders_refund_verify.refund_status", "orders_refund_verify.refund_no", "orders_refund_verify.trade_no", "orders_refund_verify.refund_price", "orders_refund_verify.order_price", "orders.puser_id", "orders.promotion_id", "orders.miniprogram_id", "orders.created_at as order_created_at", "orders.ranse_created_at", "promotions.name as promotion_name", 'orders.order_type', "orders.pay_merchant_source",'pay_merchants.name as pay_merchant_name','pay_merchants.payee_name','pay_merchants.pay_appid','miniprogram.play_name', "miniprogram.name as xcx_name");
        if ($isAll) {
            $list = $list->get();
        } else {
            $list = $list->paginate(getProp($param, 'limit', 15));
        }
        if (!$list->isEmpty()) {
            $types = array_column(OrderService::getOrderType(), null, 'value');
            $verifTxt = self::getVerifyText();
            foreach ($list as $val) {
                $val->username = $val->user_id > 0 ? User::where('id', $val->user_id)->value('username') : "";
                $val->company_name = "-";

                if (!$val->promotion_name) {
                    $val->promotion_name = "-";
                }
                $val->tip_text = $types[$val->order_type]['name'] ?? "-";
                $val->pay_name = '微信支付';
                $val->pt_verify_status_text = $verifTxt[$val->pt_verify_status]['name'] ?? "-";
                if ($val->puser_id > 0) {
                    $val->sh_verify_status_text = $verifTxt[$val->sh_verify_status]['name'] ?? "-";
                    $val->can_pay = $val->sh_verify_status == 1 && $val->pt_verify_status == 1 ? 1 : 0;
                } else {
                    $val->sh_verify_status_text = "-";
                    $val->can_pay = $val->pt_verify_status == 1 ? 1 : 0;
                }
                $val->pay_appid = $val->pay_appid ?: '-';
                $val->pay_merchant_name = $val->pay_merchant_name ?: '-';
                $val->payee_name = $val->payee_name ?: '-';
                $val->xcx_name = $val->xcx_name ?: '-';
                $val->play_name = $val->play_name ?: '-';
                $val->promotion_title = $val->promotion_title ?: '-';
                $val->status_text = $val->refund_status == 1 ? "已退款" : "已付款";
            }
        }
        return $list;
    }

    protected static function getVerifyText()
    {
        return [
            ['value' => 0, 'name' => "待审核"],
            ['value' => 1, 'name' => "审核通过"],
            ['value' => 2, 'name' => "审核不通过"],
        ];
    }

    /**
     *  构建查询语句
     * name: listQuery
     * @param array $param
     * date 2023/05/29 09:59
     */
    private static function listQuery(array $param)
    {
        $sql = OrdersRefundVerify::query()->leftJoin("orders", 'orders_refund_verify.order_id', '=', 'orders.id')->leftJoin('promotions', 'orders.promotion_id', '=', 'promotions.id')
            ->where('orders_refund_verify.refund_status', getProp($param, 'refund_status', 0))->leftJoin('pay_merchants', 'pay_merchants.id', '=', 'orders_refund_verify.pay_merchant_id')->leftJoin('miniprogram', 'miniprogram.id', '=', 'orders.miniprogram_id');
        if (!empty(getProp($param, 'user_id'))) {
            $sql->where('orders.user_id', $param['user_id']);
        }
        // 公司查询
        if (!empty(getProp($param, 'puser_id'))) {
            $sql->where('orders.puser_id', $param['puser_id']);
        }
        // 小程序
        if (!empty(getProp($param, 'miniprogram_id'))) {
            $sql->where('orders.miniprogram_id', $param['miniprogram_id']);
        }

        // 推广id
        if (!empty(getProp($param, 'promotion_id'))) {
            $sql->where('orders.promotion_id', $param['promotion_id']);
        }
        // 状态查询
        if (!empty(getProp($param, 'status'))) {
            $sql->where('orders.status', $param['status']);
        }

        // 充值项类型
        if (!empty(getProp($param, 'order_type'))) {
            $sql->where('orders.order_type', $param['order_type']);
        }
        // 用户
        if (!empty(getProp($param, 'uid'))) {
            $sql->where('orders.uid', $param['uid']);
        }
        // 订单号查询
        if (!empty(getProp($param, 'trade_no'))) {
            $sql->where('orders.trade_no', "like", "%" . $param['trade_no'] . "%");
            // $sql->where('orders.trade_no',  $param['trade_no']);
        }
        // 订单创建时间
        if (getProp($param, 'created_at_start', '')) {
            $sql->where('orders.created_at', ">=", $param['created_at_start']);
        }
        if (getProp($param, 'created_at_end', '')) {
            $end = $param['created_at_end'];
            if ($end == getProp($param, 'created_at_start', '')) {
                $end = date("Y-m-d", strtotime($end)) . " 23:59:59";
            }
            $sql->where('orders.created_at', "<=", $end);
        }
        // 退款时间
        if (getProp($param, 'pay_at_start', '')) {
            $sql->where('orders_refund_verify.pay_at', ">=", $param['pay_at_start']);
        }
        if (getProp($param, 'pay_at_start', '')) {
            $end = $param['pay_at_end'];
            if ($end == getProp($param, 'pay_at_start', '')) {
                $end = date("Y-m-d", strtotime($end)) . " 23:59:59";
            }
            $sql->where('orders_refund_verify.pay_at', "<=", $end);
        }

        // 支付配置信息查询
        if (getProp($param, 'pay_merchant_name', '')) {
            // 支付名称
            $sql->where("pay_merchants.name", $param['pay_merchant_name']);
        }
        if (getProp($param, 'payee_name', '')) {
            // 收款主体
            $sql->where("pay_merchants.payee_name", "like", "%" . $param['payee_name'] . "%");
        }
        if (getProp($param, 'pay_appid', '')) {
            // 商户号
            $sql->where("pay_merchants.pay_appid", $param['pay_appid']);
        }

        return $sql;
    }

    /**
     * 申请退款
     * name: applyRefund
     * @param $param
     *  $param [
     *      "order_id" =>  1, // 订单id
     *      'price' =>  1, // 金额
     *      'create_user_id' => 1, // 申请人id
     *  ];
     * date 2023/05/29 11:46
     */
    public static function applyRefund($param)
    {
        $order = DB::table('orders')->where('id', $param['order_id'])->first();
        if (empty($order)) {
            self::throwErrMsg('订单不存在！');
        }
        if ($order->status != "PAID") {
            self::throwErrMsg('此订单未付款，无需退款！');
        }
        if ($param['price'] > $order->price) {
            self::throwErrMsg('退款金额不能超过支付金额！');
        }

        $data = [
            'create_user_id' => $param['create_user_id'],
            'refund_no' => self::CreateRefundNo("RE"),
            'order_id' => $order->id,
            'puser_id' => $order->puser_id,
            'user_id' => $order->user_id,
            'pay_merchant_id' =>  $order->pay_merchant_id,
            'uid' => $order->uid,
            'order_price' => $order->price,
            'trade_no' => $order->trade_no,
            'third_orderid' => $order->third_orderid,
            'refund_price' => $param['price'],
        ];
        if (OrdersRefundVerify::updateOrCreate(['order_id' => $data['order_id']], $data)) {
            return '操作成功';
        }
        return '操作失败';
    }

    /**
     *  生成退款单号
     * name: CreateRefundNo
     * date 2023/05/29 13:46
     */
    private static function CreateRefundNo($prefix = '', $time = 0)
    {
        $time = $time == 0 ? time() : $time;
        $billno = $prefix . date('YmdHis', $time) . random(4, true);
        if (!empty($table)) {
            while (1) {
                $count = OrdersRefundVerify::where('refund_no', $billno)->value('id');
                if (empty($count)) {
                    break;
                }
                $billno = $prefix . date('YmdHis') . random(4, true);
            }
        }
        return $billno;

    }

    /**
     *  更新审核状态
     * name: updateRefundVerify
     * @param $refundId 退款id
     * @param array $param
     * @param int $isPlatform 是否平台 1是 0否
     * @return string
     * date 2023/05/29 16:43
     */
    public static function updateRefundVerify($refundId, array $param, $isPlatform = 0)
    {
        $info = OrdersRefundVerify::where('id', $refundId)->first();
        if (!$info) {
            self::throwErrMsg("退款申请不存在");
        }

        if ($isPlatform == 0 && $info->puser_id < 1) {
            self::throwErrMsg("无需商户审核");
        }

        if ($isPlatform == 1 && $info->pt_verify_status == 1) {
            self::throwErrMsg("已审核通过无需再次操作");
        } else if ($isPlatform == 0 && $info->sh_verify_status == 1) {
            self::throwErrMsg("已审核通过无需再次操作");
        }
        $res = OrdersRefundVerify::where('id', $refundId)->update($param);
        return $res ? "操作成功" : "操作失败";
    }

    /**
     *  退款操作
     * name: payToUser
     * @param mixed $refundId 申请id
     * @param array $option 操作人信息
     * date 2023/05/29 16:53
     */
    public static function payToUser(mixed $refundId, array $option)
    {
        $info = OrdersRefundVerify::where('id', $refundId)->first();
        if (!$info) {
            self::throwErrMsg("退款申请不存在");
        }
        if ($info->status == 1) {
            self::throwErrMsg("已退款，无需再次操作");
        }

        // 放弃审核
        // if ($info->puser_id >  0){
        //     if ($info->pt_verify_status != 1  || $info->sh_verify_status != 1){
        //         self::throwErrMsg("双方审核未全部通过，不能退款");
        //     }
        // }else{
        //     if ($info->pt_verify_status != 1 ){
        //         self::throwErrMsg("审核未通过，不能退款");
        //     }
        // }


        DB::beginTransaction();
        try {
            $payParam = [
                'third_orderid' => $info->third_orderid,
                'price' => $info->order_price,
                'refund_no' => $info->refund_no,
                'refund_price' => $info->refund_price,
            ];
            $appid = DB::table(getMiniProgramTableName(1, 'users'))->where('id', $info->uid)->value('appid');
            $resut = (new Palmpay(['subAppid' => $appid]))->refund($payParam);
            if (!$resut['status']) {
                self::throwErrMsg($resut['msg']);
            }
            $param = [
                'refund_status' => 1,
                'pay_at' => get_date(),
                'pay_op_user' => $option,
            ];
            OrdersRefundVerify::where('id', $refundId)->update($param);
            DB::table('orders')->where('id', $info->order_id)->update(['status'=> "REFUND"]);
            DB::commit();
            return "操作成功";
        } catch (\Exception $exception) {
            DB::rollBack();
            self::throwErrMsg($exception->getMessage());
        }
        self::throwErrMsg("操作失败");

    }

}
