<?php

namespace app\controller\manager;

use app\model\Business as BusinessModel;
use app\model\Log;
use app\model\Member as MemberModel;
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 Agency extends Base
{

    /**
     * 添加
     *
     * @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, '请输入正确的手机号码');
            }

            $item['roles'] = MemberModel::STAFF_ROLE_ID;
            $item['status'] = MemberModel::COMMON_ON;
            $item['pid'] = $this->auth["user_id"];
            $item['business_code'] = $this->auth["business_code"];

            $roles = [MemberModel::STAFF_ROLE_ID];

            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();
        $this->data['business'] = BusinessRepository::getInstance()->getBusinessAll();

        return $this->view();
    }

    /**
     * 添加平台商
     *
     * @return Json|View
     * @throws Exception
     */
    public function addChannel()
    {
        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, '请输入正确的手机号码');
            }

            $item['roles'] = MemberModel::ANENT_ROLE_ID;
            $item['status'] = MemberModel::COMMON_ON;
            $item['pid'] = 0;


            $roles = [MemberModel::ANENT_ROLE_ID];


            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();
        $this->data['business'] = BusinessRepository::getInstance()->getBusinessAll();

        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, '请输入正确的手机号码');
            }

            Db::startTrans();
            try {

                $info->save($item);
                Db::commit();
                return $this->json();
            } catch (ValidateException $e) {
                Db::rollback();
                return $this->json(4001, $e->getError());
            }
        }

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

    /**
     * 编辑
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function editChannel()
    {
        $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, '请输入正确的手机号码');
            }

            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]);
                    }

                    //修改下级工作人员的平台商号
                    BusinessModel::where("pid",$info['id'])->update(["business_code"=>$item['business_code']]);
                }

                $info->save($item);
                Db::commit();
                return $this->json();
            } catch (ValidateException $e) {
                Db::rollback();
                return $this->json(4001, $e->getError());
            }
        }

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

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

        return $this->view();
    }

    /**
     * 工作人员列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function index()
    {

        if ($this->request->isPost()) {
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);
            //只查询拥有渠道商的账号
            $whereMap = [['roles', "=", MemberModel::STAFF_ROLE_ID], ['id', "<>", 1]];
            $orders = ['id' => 'asc'];
            //如果是渠道商或者工作人员  只查看自己的商家
            if (MemberModel::is_agency($this->auth['roles'])) {
                $whereMap[] = ["pid", "=", $this->auth['user_id']];
            }
            $list = MemberModel::findList($whereMap, [], $page, $size, null, $orders);
            return $this->json(0, 'success', $list);
        }
        return $this->view();
    }

    /**
     * 渠道商列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function channelList()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);
            //只查询拥有渠道商的账号
            $whereMap = [['roles', "=", MemberModel::ANENT_ROLE_ID], ['id', "<>", 1]];
            $orders = ['id' => 'asc'];

            $list = MemberModel::findList($whereMap, [], $page, $size, null, $orders);

            $list["list"]->each(function ($item) {
                //管理的商家数
                $item->business_count = BusinessRepository::getInstance()->agencyHasBusinessCount($item['business_code']);
                //管理的商家的优惠券数
                $item->coupon_count = BusinessRepository::getInstance()->agencyHasCouponCount($item['business_code']);
            });
            return $this->json(0, 'success', $list);
        }
        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
     */
    public function del(): Json
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a', []);
            if (empty($ids)) {
                $ids[] = input('post.id/d');
            }
            foreach ($ids as $id) {
                if ($id == 1) {
                    return $this->json(5000, "错误的删除操作");
                }
            }
            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
     */
    public function delChannel(): Json
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a', []);
            if (empty($ids)) {
                $ids[] = input('post.id/d');
            }
            foreach ($ids as $id) {
                if ($id == 1) {
                    return $this->json(5000, "错误的删除操作");
                }
                if(MemberModel::hasStaff($id)){
                    return $this->json(5000, "还存在员工,不能删除");
                }
            }
            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 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();
    }

}