<?php
/**
 * @Copyright (c) 2019  XIGU Inc. All rights reserved.
 * @Link https://www.vlcms.com
 * @License江苏溪谷网络科技有限公司版权所有
 */

namespace app\common\logic;

use app\common\api\PlatformApi;
use app\common\model\ManagerPlatform as mManagerPlatform;
use app\common\validate\Manager as vManager;
use app\common\model\Manager as mManager;
use app\common\model\Role as mRole;
use think\Db;

class Staff extends Base
{


    public function lists($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['m.id', '=', $param['id']];
        }
        if (!empty($param['department_id'])) {
            $where[] = ['d.id', '=', $param['department_id']];
        }
        $status = input('status');
        if ($status === '1' || $status === '0') {
            $where[] = ['m.status', '=', $status];
        }
        if (!empty($param['start_time'])) {
            $where[] = ['m.create_time', ['>', strtotime($param['start_time'])], ['=', 0], 'or'];
        }
        if (!empty($param['end_time'])) {
            $where[] = ['m.create_time', ['<', strtotime($param['end_time']) + 86400 - 1], ['=', 0], 'or'];
        }
        $field = "m.id,m.name,m.realname,m.mobile,m.creator,m.activation,ma.role_id,mi.department_id,d.name as department_name,m.create_time,m.status";
        $mManager = new mManager();
        $result['count'] = $mManager -> alias('m')
                -> join(['oa_manager_auth' => 'ma'], 'm.id = ma.manager_id', 'left')
                -> join(['oa_manager_item' => 'mi'], 'm.id = mi.manager_id', 'left')
                -> join(['oa_department' => 'd'], 'mi.department_id= d.id', 'left')
                -> where($where)
                -> count();
        $result['page'] = $page;
        $result['limit'] = $limit;
        $managerList = $mManager -> alias('m')
                -> field($field)
                -> join(['oa_manager_auth' => 'ma'], 'm.id = ma.manager_id', 'left')
                -> join(['oa_manager_item' => 'mi'], 'm.id = mi.manager_id', 'left')
                -> join(['oa_department' => 'd'], 'mi.department_id= d.id', 'left')
                -> where($where)
                -> page($page, $limit)
                -> order('id')
                -> select();
        if (!empty($managerList)) {
            //获取角色列表
            $mRole = new mRole();
            $role_lists = $mRole -> where('status', 'in', '0,1') -> column('id,name');
            $result['data'] = $managerList;
            $mManagerPlatform = new mManagerPlatform();
            foreach ($result['data'] as &$v) {
                $v['role_name'] = !empty($role_lists[$v['role_id']]) ? $role_lists[$v['role_id']] : '';
                $v['platform_total'] = $mManagerPlatform -> where('manager_id', '=', $v['id']) -> count();
                if ($v['id'] == config('administrators_id')) {
                    $v['role_name'] = '超级管理员';
                    $v['is_admin'] = 1;
                } else {
                    $v['is_admin'] = 0;
                }
            }
            unset($v);
        }
        return $result;
    }

    public function selectLists($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $where = [];
        $where [] = ['m.status', 'in', '0,1'];
        $field = "m.id,m.name,m.realname,ma.role_id";
        $mManager = new mManager();
        $managerList = $mManager -> alias('m')
                -> field($field)
                -> join(['oa_manager_auth' => 'ma'], 'm.id = ma.manager_id', 'left')
                -> join(['oa_manager_item' => 'mi'], 'm.id = mi.manager_id', 'left')
                -> where($where)
                -> order('create_time')
                -> select();
        if (!empty($managerList)) {
            $result['data'] = $managerList;
        }
        return $result;
    }

    public function create($param)
    {
        $result = ['code' => 200, 'msg' => '员工添加成功', 'data' => []];
        $vManager = new vManager();
        if (!$vManager -> scene('createStaff') -> check($param)) {
            $result['code'] = '800001';
            $result['msg'] = $vManager -> getError();
            return $result;
        }
        Db ::startTrans();
        try {
            //创建管理员
            $mManager = new mManager();
            $mManager -> name = $param['name'];
            $mManager -> pid = empty($param['pid']) ? 0 : $param['pid'];
            $mManager -> nickname = $param['name'];
            $mManager -> password = data_encrypt($param['password']);
            $mManager -> verify_password = data_encrypt($param['verify_password']);
            $mManager -> realname = empty($param['realname']) ? '' : $param['realname'];
            $mManager -> mobile = $param['mobile'];
            $mManager -> status = $param['status'];
            $mManager -> creator_id = $this -> getManagerId();
            $mManager -> creator = $this -> getManagerName();
            $mManager -> activation = 1;
            $mManager -> entry_date = $param['entry_date'];
            $mManager -> qq = empty($param['qq']) ? '' : $param['qq'];
            $mManager -> duty = empty($param['duty']) ? '' : $param['duty'];
            $mManager -> isUpdate(false) -> allowField(true) -> save();
            //写入角色关联表
            $mManager -> auth() -> save(['manager_id' => $mManager -> id, 'role_id' => $param['role_id']]);
            if (!empty($param['department_id'])) {
                //写入推广员所属部门表
                $sData = [];
                $sData['manager_id'] = $mManager -> id;
                $sData['department_id'] = $param['department_id'];
                $mManager -> item() -> isUpdate(false) -> save($sData);
            }
            Db ::commit();
        } catch (\Exception $e) {
            $result['code'] = 900002;
            $result['msg'] = $this -> errorCode(600002);
            Db ::rollback();
        }
        return $result;
    }

    public function detail($param)
    {
        $detail = [];
        if (!empty($param['id'])) {
            $where = [];
            $where [] = ['m.status', 'in', '0,1'];
            $where [] = ['m.id', '=', $param['id']];
            $field = 'm.id,m.name,m.nickname,m.mobile,m.qq,m.duty,m.realname,m.status,m.entry_date,m.pid,
                      mb.is_type,mb.card_num,mb.bank_name,mb.card_name,mb.mobile as bank_mobile,mb.province,mb.city,mb.district,mb.branch,mb.alipay_account,mb.alipay_name,
                      mi.department_id,
                      ma.role_id';
            $mManager = new mManager();
            $detail = $mManager -> alias('m')
                    -> field($field)
                    -> join(['oa_manager_auth' => 'ma'], 'm.id = ma.manager_id', 'left')
                    -> join(['oa_manager_item' => 'mi'], 'm.id = mi.manager_id', 'left')
                    -> join(['oa_manager_bank' => 'mb'], 'm.id = mb.manager_id', 'left')
                    -> where($where)
                    -> find();
        }
        return $detail;
    }


    /**
     * @查看
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2020\12\1 0001 13:45
     */
    public function look($param)
    {
        $detail = [];
        if (!empty($param['id'])) {
            $where = [];
            $where [] = ['m.status', 'in', '0,1'];
            $where [] = ['m.id', '=', $param['id']];
            $field = 'm.id,m.name,mi.department_id,ma.role_id,m.mobile,m.realname,m.status,m.entry_date,m.qq,m.duty,
            mb.mobile as bank_mobile,mb.alipay_account,mb.alipay_name,mb.is_type,mb.card_num,
            mb.bank_name,mb.card_name,mb.province,mb.city,mb.district,mb.branch';
            $mManager = new mManager();
            $detail = $mManager -> alias('m')
                    -> field($field)
                    -> join(['oa_manager_auth' => 'ma'], 'm.id = ma.manager_id', 'left')
                    -> join(['oa_manager_item' => 'mi'], 'm.id = mi.manager_id', 'left')
                    -> join(['oa_manager_bank' => 'mb'], 'm.id = mb.manager_id', 'left')
                    -> where($where)
                    -> find();
        }
        return $detail;
    }

    public function update($param)
    {
        $result = ['code' => 200, 'msg' => '修改成功', 'data' => []];
        $vManager = new vManager();
        if (!$vManager -> scene('updateStaff') -> check($param)) {
            $result['code'] = 900001;
            $result['msg'] = $vManager -> getError();
            return $result;
        }
        $mManager = $this -> detail(['id' => $param['id']]);
        if (empty($mManager)) {
            $result['code'] = 900004;
            $result['msg'] = $this -> errorCode(900004);
            return $result;
        }
        $stat = new Stat();
        $managerSubIds = $stat -> getSubManagerIds($mManager['id']);
        if (in_array($param['pid'], $managerSubIds)) {
            $result['code'] = 900013;
            $result['msg'] = $this -> errorCode(900013);
            return $result;
        }
        Db ::startTrans();
        try {
            //更新manager表
            $mManager -> pid = $param['pid'];
            $mManager -> mobile = $param['mobile'];
            $mManager -> status = $param['status'];
            if (!empty($param['password'])) {
                $mManager -> password = data_encrypt($param['password']);
            }
            if (!empty($param['verify_password'])) {
                $mManager -> verify_password = data_encrypt($param['verify_password']);
            }
            if (!empty($param['realname'])) {
                $mManager -> realname = $param['realname'];
            }
            if (!empty($param['entry_date'])) {
                $mManager -> entry_date = $param['entry_date'];
            }
            $mManager -> creator_id = $this -> getManagerId();
            $mManager -> creator = $this -> getManagerName();
            $mManager -> activation = 1;
            $mManager -> qq = empty($param['qq']) ? '' : $param['qq'];
            $mManager -> duty = empty($param['duty']) ? '' : $param['duty'];
            $mManager -> isUpdate(true) -> allowField(true) -> save();
            //更新manager_auth表
            $mManager -> auth() -> isUpdate(true) -> save(['role_id' => $param['role_id']]);
            if (!empty($param['department_id'])) {
                //更新manager_item表
                $mManager -> item() -> isUpdate(true) -> save(['department_id' => $param['department_id']]);
            }
            Db ::commit();
        } catch (\Exception $e) {
            $result['code'] = 900003;
            $result['msg'] = $this -> errorCode(900003);
            Db ::rollback();
        }
        return $result;
    }


    public function enable($param)
    {
        $result = ['code' => 200, 'msg' => '员工启用成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['m.id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, 1)) {
            $result['code'] = 900006;
            $result['msg'] = $this -> errorCode(900006);
        }
        return $result;
    }


    public function disable($param)
    {
        $result = ['code' => 200, 'msg' => '员工禁用成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['m.id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, 0)) {
            $result['code'] = 900007;
            $result['msg'] = $this -> errorCode(900007);
        }
        return $result;
    }


    public function delete($param)
    {
        $result = ['code' => 200, 'msg' => '员工删除成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['m.id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, - 1)) {
            $result['code'] = 900010;
            $result['msg'] = $this -> errorCode(900010);
        }
        return $result;
    }


    private function reStatus($where, $status)
    {
        try {
            $mManager = new mManager();
            $mManager -> alias('m')
                    -> join(['oa_manager_item' => 'mi'], 'm.id = mi.manager_id')
                    -> where($where)
                    -> update(['status' => $status]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }


    /**
     * @员工绑定平台
     *
     * @author: zsl
     * @since: 2021/3/2 11:55
     */
    public function bindPlatform($param = [])
    {
        $result = ['code' => 200, 'msg' => '绑定平台成功', 'data' => []];
        $vManager = new vManager();
        if (!$vManager -> scene('bind') -> check($param)) {
            $result['code'] = '800001';
            $result['msg'] = $vManager -> getError();
            return $result;
        }
        //新建推广员
        if (empty($param['promote_account']) || empty($param['promote_password'])) {
            $param['promote_account'] = rand_str(12);
            $param['promote_password'] = rand_str(12);
            $param['is_create'] = 1;
        }
        //验证是否绑定过
        $mManager = new mManager();
        $where = [];
        $where[] = ['manager_id', '=', $param['manager_id']];
        $where[] = ['platform_id', '=', $param['platform_id']];
        $mManagerPlatform = $mManager -> platform() -> where($where) -> find();
        if (!empty($mManagerPlatform)) {
            $result['code'] = 0;
            $result['msg'] = '此渠道已绑定过';
            return $result;
        }
        //验证账号是否被绑定
        $where = [];
        $where[] = ['promote_account', '=', $param['promote_account']];
        $where[] = ['platform_id', '=', $param['platform_id']];
        $mManagerPlatform = $mManager -> platform() -> where($where) -> find();
        if (!empty($mManagerPlatform)) {
            $result['code'] = 0;
            $result['msg'] = '该账号已被绑定,请重试或修改推广员账号';
            return $result;
        }
        //调用绑定推广员接口
        $api = new PlatformApi();
        $bindRes = $api -> check($param) -> bind($param);
        if ($bindRes['code'] == 0) {
            $result['code'] = 0;
            $result['msg'] = $bindRes['msg'];
            return $result;
        }
        //添加记录
        $data = [
                'manager_id' => $param['manager_id'],
                'platform_id' => $param['platform_id'],
                'promote_account' => $param['promote_account'],
                'promote_password' => $param['promote_password'],
        ];
        $mManager -> platform() -> isUpdate(false) -> save($data);
        return $result;
    }


    /**
     * @已绑定平台列表
     *
     * @author: zsl
     * @since: 2021/3/2 20:33
     */
    public function bindPlatformLists($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $mManager = new mManager();
        $where = [];
        $where[] = ['manager_id', '=', $param['manager_id']];
        $platformLists = $mManager -> platform() -> alias('mp')
                -> field('mp.id,mp.manager_id,mp.platform_id,p.name as platform_name,mp.create_time,mp.promote_account')
                -> join(['oa_platform' => 'p'], 'mp.platform_id = p.id', 'left')
                -> where($where)
                -> select();
        $result['data'] = $platformLists ? $platformLists : [];
        return $result;
    }


    /**
     * @员工解绑平台
     *
     * @author: zsl
     * @since: 2021/3/3 9:16
     */
    public function unbindPlatform($param)
    {
        $result = ['code' => 200, 'msg' => '解绑成功', 'data' => []];
        $vManager = new vManager();
        if (!$vManager -> scene('unbind') -> check($param)) {
            $result['code'] = '800001';
            $result['msg'] = $vManager -> getError();
            return $result;
        }
        $mManger = new mManager();
        $where = [];
        $where[] = ['platform_id', '=', $param['platform_id']];
        $where[] = ['manager_id', '=', $param['manager_id']];
        $res = $mManger -> platform() -> where($where) -> delete();
        if (false === $res) {
            $result['code'] = 900014;
            $result['msg'] = $this -> errorCode(900014);
            return $result;
        }
        return $result;
    }


    private function errorCode($code)
    {
        $errorCode = [
                900001 => '',
                900002 => '员工添加失败',
                900003 => '员工修改失败',
                900004 => '员工不存在，或已被删除',
                900006 => '员工启用失败',
                900007 => '员工禁用失败',
                900008 => '当前管理员没有公会',
                900009 => '超级管理员不可操作',
                900010 => '员工删除失败',
                900011 => '该部门已存在组长',
                900012 => '原密码错误',
                900013 => '所属上级不能是自己或下属',
                900014 => '解绑失败',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }


}
