<?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\property;


use app\adminapi\logic\user\UserLogic;
use app\api\logic\ServiceOrderLogic;
use app\common\logic\PaymentLogic;
use app\common\model\property\PropertyOrder;
use app\common\logic\BaseLogic;
use app\common\model\works\ServiceWork;
use think\Exception;
use think\facade\Db;
use think\facade\Log;


/**
 * PropertyOrder逻辑
 * Class PropertyOrderLogic
 * @package app\adminapi\logic
 */
class PropertyOrderLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/09/19 14:48
     */
    public static function add(array $params): bool
    {
        // 判断户主是否存在 返回户主id
        $propertyUserId = PropertyUserLogic::getPropertyUserIdByMobile($params);
        Db::startTrans();
        try {
            PropertyOrder::create([
                'property_head_id' => $params['property_head_id'],
                'property_user_id' => $propertyUserId,
                'remark' => $params['remark']
            ]);
            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/09/19 14:48
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            $upData = ['remark' => $params['remark']];
            if($params['order_status'] == 2){
                $upData['order_status'] = $params['order_status'];
            }
            $orderStatus = PropertyOrder::where('id', $params['id'])->value('order_status');
            if($orderStatus == 0){
                PropertyOrder::where('id', $params['id'])->update($upData);
            }
            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/09/19 14:48
     */
    public static function delete(array $params): bool
    {
        return PropertyOrder::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/09/19 14:48
     */
    public static function detail($params): array
    {
        return PropertyOrder::findOrEmpty($params['id'])->toArray();
    }


    /**
     * @notes 客服接单即由后台提交工单
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/09/19 14:48
     */
    public static function placeOrder(array $params): bool
    {
        // 客服手动下单
        /*
            1. 按照用户原预约下单参数创建 工单
            2. 由 工单id 状态-已接单 更新当前订单状态信息
            // 订单状态：0=未接单,1=已接单,2=取消单,3=已完结
        */

        $orderInfo = PropertyOrder::where('id', $params['id'])->findOrEmpty()->toArray();
        $propertyUserInfo = PropertyUserLogic::detail(['id'=>$orderInfo['property_user_id']]);
        $userInfo = UserLogic::detail($propertyUserInfo['user_id']);
        if($orderInfo['order_status'] != 0){
            self::setError('当前订单状态不允许操作');
            return false;
        }
        $propertyHeadInfo =  PropertyHeadLogic::detail(['id'=>$orderInfo['property_head_id']]);
        //$propertyHeadInfo['lon']  $propertyHeadInfo['lat']

        Db::startTrans();
        try {

            if($orderInfo['work_id'] == 0 && $orderInfo['order_status'] == 0){
                /*// 'address','appointment_time','pay_way','goods_id','contact_number','contact_people'
                'sn.require' => '订单编号错误',
                'address.require' => '请填写地址',
                'appointment_time.require' => '请填写预约上门时间',
                'appointment_time.dateFormat' => '预约上门时间格式错误',
                'pay_way.require' => '请选择支付方式',
                'goods_id.require' => '订单商品不存在',
                'contact_number.require' => '联系电话不存在',
                'contact_people.require' => '联系人不存在',*/
                // 物业地址拼接户主详细门牌号
                $params['address'] = $params['address']?:($propertyHeadInfo['address'].$propertyUserInfo['address']);
                $serviceOrderParams = array_merge($params,[
                    'user_id' => $propertyUserInfo['user_id'],
                    'terminal' => 4,
                    'user_info' => ['mobile'=>$userInfo['mobile']],
                    'lon' => $propertyHeadInfo['lon']?:0,
                    'lat' => $propertyHeadInfo['lat']?:0,
                ]);
                Log::write(json_encode($serviceOrderParams,JSON_UNESCAPED_UNICODE));
                $result = ServiceOrderLogic::submitOrder($serviceOrderParams);
                if($result === false){
                    throw new Exception(PropertyOrderLogic::getError());
                }
                // $result['order_id'] $result['work_id']
                $upData = [];
                if(isset($result['work_id']) && !empty($result['work_id'])){
                    $upData['work_id'] = $result['work_id'];
                    $upData['order_status'] = 1;
                }
                if($upData){
                    $propertyOrder =  PropertyOrder::where('id', $params['id'])->update($upData);
                }
                if($propertyOrder){
                    //订单信息  pay_way=2 goods  order_id
                    $params['from'] = 'goods';
                    $order = PaymentLogic::getPayOrderInfo(['order_id'=>$result['order_id']]);
                    Log::info('ServiceOrder:',$result);
                    if (false === $order) {
                        Log::info(PaymentLogic::getError());
                        return false;
                        //throw new Exception(PaymentLogic::getError());
                    }
                    if ($order['order_amount'] == 0) {
                        //0元时自动支付
                        $redirectUrl = $params['redirect'] ?? '/pages/payment/payment';
                        PaymentLogic::pay($params['pay_way'], $params['from'], $order, 4, $redirectUrl);
                    }
                }
            }

            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/09/19 14:48
     */
    public static function cancel(array $params): bool
    {
        Db::startTrans();
        try {
            $upData['order_status'] = 2;
            $orderStatus = PropertyOrder::where('id', $params['id'])->value('order_status');
            if($orderStatus == 0){
                PropertyOrder::where('id', $params['id'])->update($upData);
            }else{
                throw new Exception('当前订单状态不允许操作');
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }






}