<?php

namespace App\Admin\Forms\User;

use App\Admin\Service\PermService;
use App\Admin\Service\UserService;
use App\Models\Cms\CmsUser;
use App\Models\Inquiry;
use App\Models\User;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class TransferUserHandle extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        try {
            $ids = explode(",", $input['id']);
            UserService::transferUser($ids, $input['sale_id']);
            return $this
                ->response()
                ->success(trans('admin.update_succeeded'))
                ->refresh();
        } catch (\Throwable $throwable) {
//            var_dump((string)$throwable);
            return $this->response()->error(trans('admin.update_failed') . ": {$throwable->getMessage()}");
        }
    }

    public function getCmsUserList()
    {
        $where = [];
        $where[] = [
            function ($query) {
                $adminUser = "userId";
                $nowSaleId = getAdminUserId();
                $role = PermService::getUserRoles($nowSaleId);
                if ($nowSaleId == 1000 || $role[0] == PermService::ROLE_SALE_DIRECTOR) {
                    return $query;
                }
                if ($role[0] == PermService::ROLE_SALE_LEADER) {//销售经理可以查看同部门
                    $userIds = PermService::getSubUserId($nowSaleId);
                    if (!empty($userIds)) {
                        return $query->whereIn($adminUser, $userIds);
                    }
                } elseif ($role[0] == PermService::ROLE_SALE) {//销售可以查看同组
                    //查看同组
                    $user_info = CmsUser::getInfoByUserId($nowSaleId);
                    if (empty($user_info) || !$user_info['department_id']) {
                        return $query->where($adminUser, $nowSaleId);
                    }
                    // 获取同组部门的人员
                    $sub_user_ids = CmsUser::getUserIdsByDepartmentIds([$user_info['department_id']]);
                    return $query->whereIn($adminUser, $sub_user_ids);
                }
            }
        ];
        return CmsUser::where($where)->pluck('name', 'userId')->toArray();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->disableResetButton();
        $this->hidden('id')->attribute('id', 'id');
        $this->select('sale_id')->options($this->getCmsUserList())->default(0)->required();
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [

        ];
    }
}