<?php

namespace app\admin\controller\medical;

use support\exception\BusinessException;
use support\Request;
use app\admin\validate\medical\SalesmanValidate;
use app\controller\Curd;
use app\model\MedicalSalesman;
use support\Response;

class SalesmanController extends Curd
{
    public function __construct()
    {
        $this->model = new MedicalSalesman();
        $this->validate = true;
        $this->validateClass = new SalesmanValidate();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'salesman_addTime';
        $where['salesman_is_del'] = 0;
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'shop' => function ($query) {
                $query->select('shop_id', 'shop_name');
            }
        ]);
        
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item) {
            $item->salesman_status = strval($item->salesman_status);
            unset($item->salesman_password);
        }

        return $items;
    }

    /**
     * @Desc insert 数据处理
     * @Author Gorden
     * @Date 2024/3/4 9:57
     *
     * @param Request $request
     * @return array
     * @throws \support\exception\BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        // 验证手机号是否已存在
        if ($this->model->phoneExist($data['salesman_phone'])) {
            throw new BusinessException('手机号已存在');
        }
        // 用户已存在
        if ($this->model->usernameExist($data['salesman_username'])) {
            throw new BusinessException('用户名已存在');
        }

        return $data;
    }

    /**
     * @Desc 执行写入数据
     * @Author Gorden
     * @Date 2024/3/4 9:39
     *
     * @param $data
     * @return mixed|null
     */
    protected function doInsert($data)
    {
        $data['salesman_salt'] = random_string(6);
        $data['salesman_password'] = md5(sha1($data['salesman_password'] . $data['salesman_salt']));
        $primary_key = $this->model->getKeyName();
        $model_class = get_class($this->model);
        $model = new $model_class;
        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        $model->save();
        return $primary_key ? $model->$primary_key : null;
    }

    /**
     * @Desc 数据处理
     * @Author Gorden
     * @Date 2024/3/4 10:17
     *
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        // 其他账号下是否存在当前手机号
        if ($model->phoneIsInOtherAccountExist($data['salesman_phone'], $data['salesman_id'])) {
            throw new BusinessException('手机号已存在');
        }
        // 其他账号下是否存在当前用户名
        if ($model->usernameIsInOtherAccountExist($data['salesman_username'], $data['salesman_id'])) {
            throw new BusinessException('用户名已存在');
        }

        $passwordFiled = 'salesman_password';
        if (isset($data[$passwordFiled])) {
            // 密码为空，则不更新密码
            if ($data[$passwordFiled] === '') {
                unset($data[$passwordFiled]);
            } else {
                $data[$passwordFiled] = md5(sha1($data[$passwordFiled] . $model->salesman_slat));
            }
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * @Desc 修改状态
     * @Author Gorden
     * @Date 2024/3/4 10:20
     *
     * @param Request $request
     * @return \support\Response
     */
    public function updateStatus(Request $request)
    {
        return $this->updateField($request->post('salesman_id'), 'salesman_status', $request->post('salesman_status'));
    }

    /**
     * @Desc 软删除
     * @Author Gorden
     * @Date 2024/3/4 10:22
     *
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
        $this->doSoftDelete($ids, ['salesman_is_del' => 1]);

        return json_success('success');
    }
}