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


use app\adminapi\logic\property\PropertyOrderLogic as AdminPropertyOrderLogic;
use app\adminapi\logic\user\UserLogic;
use app\api\logic\PropertyOrderLogic as ApiPropertyOrderLogic;
use app\common\model\equity\EquityConfig;
use app\common\model\equity\EquityOrder;
use app\common\logic\BaseLogic;
use app\common\model\equity\UserEquity;
use app\common\model\property\PropertyOrder;
use app\common\model\user\User;
use Exception;
use think\facade\Db;


/**
 * EquityOrder逻辑
 * Class EquityOrderLogic
 * @package app\adminapi\logic
 */
class EquityOrderLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/12/25 13:32
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            // 通过手机号查询用户是否注册 - 已注册绑定id ，未注册注册再绑定id
            $userId = UserLogic::getUserIdByMobile($params['mobile']);

            EquityOrder::create([
                'user_id' => $userId,
                'description' => $params['description']??'',
                'price' => $params['price']??0,
                'create_order_time' => $params['create_order_time']?strtotime($params['create_order_time']):0,
                'service_work_id' => $params['service_work_id']??0,
                'equity_id' => $params['equity_id']??0,
                'status' => $params['status']??1,
                'property_head_id' => $params['property_head_id']??0,
                '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/12/25 13:32
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            // 通过手机号查询用户是否注册 - 已注册绑定id ，未注册注册再绑定id
            $userId = UserLogic::getUserIdByMobile($params['mobile']);

            EquityOrder::where('id', $params['id'])->update([
                'user_id' => $userId,
                'description' => $params['description']??'',
                'price' => $params['price']??0,
                'create_order_time' => $params['create_order_time']?strtotime($params['create_order_time']):0,
                'service_work_id' => $params['service_work_id']??0,
                'equity_id' => $params['equity_id']??0,
                'status' => $params['status']??1,
                'property_head_id' => $params['property_head_id']??0,
                '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/12/25 13:32
     */
    public static function delete(array $params): bool
    {
        return EquityOrder::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/12/25 13:32
     */
    public static function detail($params): array
    {
        return EquityOrder::findOrEmpty($params['id'])->toArray();
    }


    public static function addOrder($params)
    {
        Db::startTrans();
        try {
            $equityOrder = EquityOrder::findOrEmpty($params['id'])->toArray();
            $userInfo = User::findOrEmpty($equityOrder['user_id'])->toArray();
            $equityConfigInfo = EquityConfig::findOrEmpty($params['equity_id'])->toArray();

            $userEquity = UserEquity::where([
                ['equity_id','=',$params['equity_id']],['user_id','=',$equityOrder['user_id']],
                ['number','>',0],['end_time','>=',time()]
            ])->findOrEmpty();
            if($userEquity->isEmpty()){
                $userEquity = UserEquity::create([
                    'user_id' => $equityOrder['user_id'],
                    'equity_id' => $params['equity_id'],
                    'remark' => $params['remark']??'',
                    'goods_id' => $equityConfigInfo['goods_id'],
                    'number' => $equityConfigInfo['number'],
                    'end_time' => (time()+$equityConfigInfo['day_num']*86400),
                ]);
            }
            $order_id = ApiPropertyOrderLogic::add([
                'property_head_id' => $equityOrder['property_head_id'],
                'householder_name' => $userInfo['nickname'],
                'householder_mobile' => $userInfo['mobile'],
                'address' => $params['address']??'',
                'remark' => ''
            ]);
            if (false === $order_id) {
                throw new Exception(ApiPropertyOrderLogic::getError());
            }
            $result = AdminPropertyOrderLogic::placeOrder([
                'id' => $order_id,
                'address' => $params['address'] ?? '',
                'appointment_time' => $params['appointment_time'],
                'goods_id' => $equityConfigInfo['goods_id'],
                'pay_way' => $params['pay_way'],
                'contact_number' => $params['contact_number'] ?? '',
                'contact_people' => $params['contact_people'] ?? '',
                'user_equity_id' => $userEquity->id
            ]);
            if (false === $result) {
                throw new Exception(AdminPropertyOrderLogic::getError());
            }

            $orderInfo = PropertyOrder::where('id', $order_id)->findOrEmpty()->toArray();
            EquityOrder::where('id', $params['id'])->update([
                'service_work_id' => $orderInfo['work_id'],
                'equity_id' => $params['equity_id'],
                'status' => 2,
            ]);

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


}