<?php

namespace app\traits\account;

use app\model\Account;
use app\model\ApplyStaff;

trait ApplyStaffTrait
{
    /**
     * 获取申请员工记录
     * @param $userCode
     * @return ApplyStaff|array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getApplyStaffByUserCode($userCode)
    {
        return ApplyStaff::with(["business","account"])->where("user_code",$userCode)->find();
    }

    /**
     * 获取指定商家申请员工记录
     * @param $userCode
     * @return ApplyStaff|array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getApplyStaffByUserCodeAndBusinessCode($userCode,$businessCode)
    {
        return ApplyStaff::with(["business","account"])->where("user_code",$userCode)->where("business_code",$businessCode)->find();
    }


    /**
     * 创建一个加入员工申请
     * @param $userCode
     * @param $businessCode
     */
    public function createApplyStaff($userCode,$businessCode)
    {
        $data = [
            "user_code"=>$userCode,
            "business_code"=>$businessCode,
            "status"=>ApplyStaff::status_default,
            "create_time"=>date("Y-m-d H:i:s"),
        ];
        ApplyStaff::create($data);
    }

    /**
     * 获取商家的员工列表
     * @param $businessCode
     * @param $mainCode
     * @return Account
     */
    public function getStaffListByBusinessCode($businessCode,$mainCode,$keyword)
    {
        $where = [
            ["type","=",Account::type_staff],
            ["main_code","=",$mainCode],
            ["business_code","=",$businessCode],
        ];
        if(!empty($keyword)){
            $where [] = ["nick_name","like","%{$keyword}%"] ;
        }
        $field = [
            "nick_name as nickName",
            "avatar_url as avatarUrl",
            "gender",
            "user_code",
        ];
        return Account::where($where)->field($field)->select()->toArray();
    }
    /**
     * 获取商家的员工申请列表
     * @param $businessCode
     * @param $mainCode
     * @return Account
     */
    public function getApplyStaffListByBusinessCode($businessCode,$keyword)
    {
        $where = [
            ["a.business_code","=",$businessCode],
            ["a.status","=",ApplyStaff::status_default],
        ];

        if(!empty($keyword)){
            $where[] = ["b.nick_name","like","%{$keyword}%"] ;
        }
        $field = [
            "b.nick_name as nickName",
            "b.avatar_url as avatarUrl",
            "b.gender",
            "b.user_code",
            "a.create_time",
        ];
        return ApplyStaff::alias("a")
            ->join("account b","a.user_code = b.user_code")
            ->where($where)
            ->field($field)
            ->select()
            ->toArray();
    }
}