<?php

namespace app\controller\manager;

use app\model\Log;
use app\model\Member as MemberModel;
use app\model\Role as RoleModel;
use app\model\Business as BusinessModel;
use app\repository\BusinessRepository;
use Exception;
use tauthz\facade\Enforcer;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;
use think\response\Redirect;
use think\response\View;

/**
 * (后台)人员管理
 *
 * Class Member
 * @package app\controller\manager
 */
class Member extends Base
{
    /**
     * 删除
     *
     * @return Json
     */
    public function del(): Json
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a', []);
            if (empty($ids)) {
                $ids[] = input('post.id/d');
            }
            MemberModel::deleteByIds($ids);
            foreach ($ids as $id) {
                Enforcer::deleteRolesForUser($id);
            }
            Log::write(get_class().'Del', 'del', '涉及到的ID为:'.implode(',', $ids));
            return $this->json();
        }
        return $this->json(4001, '非法请求!');
    }

    /**
     * 个人详情
     *
     * @return Json|View|Redirect
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function profile()
    {
        $id = $this->auth['user_id'] ?? 0;

        if (!$item = MemberModel::findById($id)) {
            if ($this->request->isAjax()) {
                return $this->json(4001, '记录不存在');
            }
            return $this->error('记录不存在');
        }

        if ($this->request->isPost()) {
            $post = input('post.');

            $validate = $this->validateByApi($post, [
                'mobile|手机号'  => 'require|unique:member,mobile,'.$id,
                'nickname|昵称' => 'require|chsAlphaNum|min:2|max:10',
                'remark|备注信息' => 'max:255',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!checkMobile($post['mobile'])) {
                return $this->json(4002, '请输入正确的手机号码');
            }

            try {
                $item->save($post);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item'] = $item;

        return $this->view();
    }

    /**
     * 编辑
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function edit()
    {
        $id = input('id/d', 0);

        if (!$info = MemberModel::findById($id)) {
            return $this->json(4001, '记录不存在');
        }

        if ($this->request->isPost()) {
            $item = input('post.');

            $validate = $this->validateByApi($item, [
                'mobile|手机号'  => 'require|unique:member,mobile,'.$id,
                'nickname|昵称' => 'require|chsAlphaNum|min:2|max:10',
                'remark|备注信息' => 'max:255',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!checkMobile($item['mobile'])) {
                return $this->json(4002, '请输入正确的手机号码');
            }

            $roles = [];
            if ($item['roles']) {
                $roles = $item['roles'];
                $item['roles'] = implode(',', $item['roles']);
            }


            Db::startTrans();
            try {
                //之前关联的商家不为空 并且已经改变  吧之前的商家 从代理商变成普通商家
                if ($info['business_code'] != $item['business_code']) {
                    if($info['business_code']!="_" ){
                        $oldBusiness = BusinessRepository::getInstance()->findOneByWhere(["code" => $info['business_code']]);
                        if (!empty($oldBusiness)) {
                            $oldBusiness->save(["is_agency" => BusinessModel::COMMON_OFF]);
                        }
                    }
                    //如果改变了关联商家
                    if($item['business_code']!="_"){
                        $Business = BusinessRepository::getInstance()->findOneByWhere(["code" => $item['business_code']]);
                        if (empty($Business)) {
                            Db::rollback();
                            return $this->json(4001, "指定商家不存在");
                        }
                        $Business->save(["is_agency" => BusinessModel::COMMON_ON]);
                    }
                }

                $info->save($item);
                //删除所有角色
                Enforcer::deleteRolesForUser($id);
                //新增角色
                foreach ($roles as $role) {
                    Enforcer::addRoleForUser($id, $role);
                }
                Db::commit();
                return $this->json();
            } catch (ValidateException $e) {
                Db::rollback();
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item'] = $info;
        $this->data['roleJson'] = $this->roleJson(explode(',', $info['roles']));

        $this->data['business'] = BusinessRepository::getInstance()->getBusinessAll();

        return $this->view();
    }

    /**
     * 单个字段编辑
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function modify(): Json
    {
        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'field' => 'require',
                'value' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!$info = MemberModel::findById($item['id'])) {
                return $this->json(4001, '记录不存在');
            }

            $update = [$item['field'] => $item['value']];

            try {
                $info->save($update);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }
        return $this->json(4000, '非法请求');
    }

    /**
     * 添加
     *
     * @return Json|View
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $item = input('post.');

            $validate = $this->validateByApi($item, [
                'username|用户名' => 'require|alphaDash|min:4|max:16|unique:member',
                'mobile|手机号'   => 'require|unique:member',
                'nickname|昵称'  => 'require|chsAlphaNum|min:2|max:10',
                'password|密码'  => 'require|min:4|max:16',
                'remark|备注信息'  => 'max:255',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!checkMobile($item['mobile'])) {
                return $this->json(4002, '请输入正确的手机号码');
            }

            $roles = [];
            if ($item['roles']) {
                $roles = $item['roles'];
                $item['roles'] = implode(',', $item['roles']);
            }

            Db::startTrans();
            try {
                $item['password'] = md5($item['password'].$item['username']);
                $member = MemberModel::create($item);
                foreach ($roles as $role) {
                    Enforcer::addRoleForUser($member['id'], $role);
                }
                Db::commit();
                return $this->json();
            } catch (ValidateException $e) {
                Db::rollback();
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['roleJson'] = $this->roleJson();
        return $this->view();
    }

    /**
     * 修改密码
     *
     * @return Json|View|Redirect
     * @throws Exception
     */
    public function password()
    {
        $id = input('id/d', 0);

        if (!$item = MemberModel::findById($id)) {
            if ($this->request->isAjax()) {
                return $this->json(4001, '记录不存在');
            }
            return $this->error('记录不存在');
        }

        if ($this->request->isPost()) {
            $post     = input('post.');
            $validate = $this->validateByApi($post, [
                'password|密码' => 'require|confirm',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            $password = md5($post['password'].$item['username']);

            try {
                $item->save(['password' => $password]);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item'] = $item;

        return $this->view();
    }

    /**
     * 个人修改密码
     *
     * @return Json|View
     * @throws Exception
     */
    public function myPassword()
    {
        $id = $this->auth['user_id'] ?? 0;
        if (!$item = MemberModel::findById($id)) {
            return $this->json(4001, '记录不存在');
        }

        if ($this->request->isPost()) {
            $post     = input('post.');
            $validate = $this->validateByApi($post, [
                'old-password|旧密码' => 'require',
                'password|密码'      => 'require|confirm',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if ($item['password'] !== md5($post['old-password'].$item['username'])) {
                return $this->json(4002, '原始密码错误');
            }

            $password = md5($post['password'].$item['username']);

            try {
                $item->save(['password' => $password]);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item'] = $item;
        return $this->view();
    }

    /**
     * 列表
     *
     * @return View|Json
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page         = input('page/d', 1);
            $limit        = input('size/d', 20);
            $searchParams = input('searchParams');
            $where        = [];
            if ($searchParams) {
                foreach ($searchParams as $key => $param) {
                    if (!empty($param)) {
                        $where[] = [$key, 'like', '%'.$param.'%'];
                    }
                }
            }

            $items = MemberModel::findList($where, [], $page, $limit, function ($q) {
                return $q->order('id', 'desc');
            });

            return $this->json(0, '操作成功', $items);
        }
        return $this->view();
    }

    /**
     * 构造角色json数据
     *
     * @param  array  $selected
     * @return false|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function roleJson(array $selected = [])
    {
        $roles    = RoleModel::where('status', RoleModel::STATUS_NORMAL)
            ->order('sort', 'desc')
            ->select()
            ->toArray();
        foreach ($roles as $k => $m) {
            $roles[$k]['checked'] = in_array($m['id'], $selected);
            $roles[$k]['spread']  = true;
        }
        return json_encode($roles, JSON_UNESCAPED_UNICODE);
    }
}