<?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\user\UserLogic;
use app\common\model\equity\EquityConfig;
use app\common\model\equity\UserEquity;
use app\common\logic\BaseLogic;
use app\common\model\user\User;
use app\common\model\works\ServiceWork;
use think\facade\Db;
use think\facade\Validate;


/**
 * UserEquity逻辑
 * Class UserEquityLogic
 * @package app\adminapi\logic
 */
class UserEquityLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/12/19 11:43
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            $equityConfigInfo = EquityConfig::find($params['equity_id']);
            $max_id = UserEquity::max('id');
            if((int)$params['is_binding'] === 1){
                if(!Validate::checkRule($params['mobile'], 'require|mobile')){
                    throw new \Exception('请填写正确手机号');
                }
                // 通过手机号查询用户是否注册 - 已注册绑定id ，未注册注册再绑定id
                $userId = UserLogic::getUserIdByMobile($params['mobile']);
                $max_id++;
                UserEquity::create([
                    'user_id' => $userId,
                    'equity_id' => $params['equity_id'],
                    'remark' => $params['remark'],
                    'code' => generateRandomString((8-strlen($max_id)),2).$max_id,
                    'goods_id' => $equityConfigInfo['goods_id'],
                    'number' => $equityConfigInfo['number'],
                    'end_time' => (time()+$equityConfigInfo['day_num']*86400),
                ]);
            }else{
                for ($i=0;$i<$params['quantity'];$i++){
                    $max_id++;
                    $list[] = [
                        'user_id' => 0,
                        'equity_id' => $params['equity_id'],
                        'remark' => $params['remark'],
                        'code' => generateRandomString((8-strlen($max_id)),2).$max_id,
                        'goods_id' => $equityConfigInfo['goods_id'],
                        'number' => $equityConfigInfo['number'],
                        'end_time' => 0,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                }
                UserEquity::insertAll($list);
            }
            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/19 11:43
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            UserEquity::where('id', $params['id'])->update([
                'number' => $params['number']??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/19 11:43
     */
    public static function delete(array $params): bool
    {
        return UserEquity::destroy($params['id']);
    }


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


    public static function serviceWorkDetail($params): array
    {
        return ServiceWork::where('user_equity_id',$params['user_equity_id'])->append(['work_status_text'])->select()->toArray();
    }

}