<?php


namespace JinDouYun\Controller\Department;


use JinDouYun\Controller\BaseController;
use JinDouYun\Dao\BaseDao;
use JinDouYun\Dao\Customer\DCustomerCardNum;
use JinDouYun\Dao\Department\DStaffReflect;
use JinDouYun\Dao\Shop\DShopRostering;
use JinDouYun\Dao\UserCenter\DUserCenter;
use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\Customer\MCustomerCard;
use JinDouYun\Model\Department\MStaff;
use JinDouYun\Model\Department\MStaffStock;
use JinDouYun\Model\Shop\MShopProject;
use JinDouYun\Model\Shop\MShopRostering;
use JinDouYun\Model\Shop\MShopSubscribe;
use JinDouYun\Model\Shop\MShopTemplate;
use JinDouYun\Model\System\MBasicSetup;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\Ding;
use Mall\Framework\Factory;

class ApiStaff extends BaseController
{

    private $obj;
    private $objCustomer;
    private $objCard;
    private $objRostering;
    private $objSub;
    private $objStaff;
    private $Mrostering;
    private $staff;
    private $Mstock;
    private $objDStaffRewardDesc;

    public function __construct($isCheckAcl = true, $isMustLogin = true, $checkToken = true, $getAreaCode = false, $checkShopToken = true, $checkSupplierToken = false)
    {
        parent::__construct($isCheckAcl, $isMustLogin, $checkToken, $getAreaCode, $checkShopToken, $checkSupplierToken);

        $shopToken = $this->request->param('SHOP-TOKEN');
        if (!empty($shopToken)) {
            self::getShopIdByShopToken($shopToken);
        }
        $this->obj = new MShopProject($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objCard = new MCustomerCard($this->onlineEnterpriseId);
        $this->objCardNum = new DCustomerCardNum('default');
        $this->objRostering = new MShopRostering($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objSub = new MShopSubscribe($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objStaff = new MStaff($this->onlineEnterpriseId, $this->onlineUserId);
        $this->Mrostering = new MShopRostering($this->onlineEnterpriseId, $this->onlineUserId);
        $this->staff = new MStaff($this->onlineEnterpriseId, $this->onlineUserId);
        $this->Mstock = new MStaffStock($this->onlineEnterpriseId, $this->onlineUserId);

        $this->objDStaffRewardDesc = new DUserCenter('default');
        $this->objDStaffRewardDesc->setTable('qianniao_staff_reward_desc_' . $this->onlineEnterpriseId);
    }


    /**
     *排班详情
     * @return void
     */
    public function scheduling_details()
    {
        $param = $this->request->getRawJson();
//        $user = $this->staff->getStaffInfo(['userCenterId' => $this->onlineUserId, 'shopId' => $this->shopId])->getData();
//        if (!$user)  parent::sendOutput('不是该店铺店员', 1);

//        $staff = $this->staff->getStaffInfo(['userCenterId' => $param['uid'], 'shopId' => $this->shopId])->getData();

        $uid = $this->onlineUserId;
//        $offset = $param['offset'] ? $param['offset'] : 0;
//        $limit = $param['limit'] ? $param['limit'] : 100;
        $month = $param['month'] ? $param['month'] : date('Y-m', time());
        $where = [];

        if ($month) {
            $where[] = ['time', 'like', '%' . $month . '%'];
        }
        if (isset($param['export'])) {
            $where['export'] = $param['export'];
        }
//        $where[] = ['shop_id', '=', $this->shopId];
//        $staff = $this->objStaff->getStaffData(['userCenterId' => $this->onlineUserId])->getData();
//        if (empty($staff)) parent::sendOutput('该用户不是店员', ErrorCode::$dberror);;

        $where[] = ['uid', '=', $param['staffId']];
        $rostering = $this->Mrostering->select($where, '*', 'time DESC');
        if ($rostering->isSuccess()) {
            $returnData = $rostering->getData();
            parent::sendOutput($returnData['data'], 0);
        } else {
            parent::sendOutput($rostering->getData(), ErrorCode::$dberror);
        }
    }


    /**
     * 服务列表列表
     */
    public function list()
    {
        if (empty($this->onlineUserId)) parent::sendOutput('未登录', ErrorCode::$dberror);
        $params = $this->request->params();
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];


        $staff = $this->objStaff->getStaffData(['userCenterId' => $this->onlineUserId])->getData();
        if (empty($staff)) parent::sendOutput('该用户不是店员', ErrorCode::$dberror);
        $selectParams['uid'] = $staff['id'];
        if ($this->shopId) {
            $selectParams['shop_id'] = $this->shopId;
        }
        //昵称
        if (isset($params['nickname']) && !empty($params['nickname'])) {
            $selectParams['nickname'] = $params['nickname'];
        }
        //uid
        if (isset($params['uid']) && !empty($params['uid'])) {
            $selectParams['uid'] = $params['uid'];
        }

        if (isset($params['type']) && !empty($params['type'])) {
            $selectParams['type'] = $params['type'];
        }

        $selectParams['status'] = 1;
        // 时间
        if (isset($params['start_time']) && !empty($params['start_time']) and isset($params['end_time']) && !empty($params['end_time'])) {
            $response = [];

            $dt_start = strtotime($params['start_time']);
            $dt_end = strtotime($params['end_time']);
            while ($dt_start <= $dt_end) {
                array_push($response, date('Y-m-d', $dt_start));
                $dt_start = strtotime('+1 day', $dt_start);
            }
            $selectParams['time'] = $response;
        }

        $result = $this->objSub->list($selectParams);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }

    }

    /**
     * 修改预约订单，修改服务员工
     * @return void
     */
    public function upSubscribe()
    {
        $id = $this->request->param('id');
        $staffId = $this->request->param('staffId');
        $subscribe = $this->objSub->details(['id' => $id])->getData();

        $staff = $this->objStaff->getStaffData(['userCenterId' => $this->onlineUserId])->getData();
        if (empty($staff)) parent::sendOutput('该用户不是店员', ErrorCode::$dberror);

        if ($subscribe['status'] == 1) parent::sendOutput('订单已完成', ErrorCode::$dberror);
        if ($subscribe['uid'] == $staffId) parent::sendOutput('服务人员未变动', ErrorCode::$dberror);

        $res = $this->objSub->update(['uid' => $staffId], $id);

        if ($res) {
            parent::sendOutput('修改成功');
        }
        parent::sendOutput($res->getData(), ErrorCode::$dberror);
    }


    /**
     * 新增项目
     * @return void
     */
    public function addProject()
    {
        $id = $this->request->param('id');
        $projectId = $this->request->param('projectId');

        $project = $this->obj->select([['id', 'in', $projectId]]);
        $subscribe = $this->objSub->details(['id' => $id])->getData();
        if ($subscribe['status'] == 1) parent::sendOutput('订单已完成', ErrorCode::$dberror);
        foreach ($project as $item) {
            $subscribe['to_price'] += $item['price'];
            $subscribe['cost_price'] += $item['cost_price'];
            $subscribe['stay_price'] += $item['price'];
        }
        $projectIDs = array_merge(explode(',', $subscribe['project']), explode(',', $projectId));
        $res = $this->objSub->update(['to_price' => $subscribe['to_price'], 'cost_price' => $subscribe['cost_price'], 'stay_price' => $subscribe['stay_price'], 'project' => implode(',', $projectIDs)], $id);
        if ($res) {
            parent::sendOutput('添加成功');
        }
        parent::sendOutput($res->getData(), ErrorCode::$dberror);
    }


    /**
     * 订单完成
     * @return void
     */
    public function complete()
    {
        $params = $this->request->getRawJson();
        if (!$params['id']) $this->sendOutput('参数为空', ErrorCode::$paramError);
        $data = $this->objSub->details(['id' => $params['id']]);

        if (!$data->isSuccess()) parent::sendOutput('订单不存在', $data->getErrorCode());
        $data = $data->getData();
        if ($data['status'] == 1) parent::sendOutput('该订单已完成', 1005);
        $res = $this->objSub->update(['status' => 1, 'paid' => 1, 'completeTime' => time(), 'pay_price' => $data['pay_price'] + $data['stay_price']], $params['id']);
        if ($res->isSuccess()) {
            $this->staff->stock($data['uid']); // 发放员工股份
            $this->staff->recommend($data, $this->shopId); // 发放客户提成
            $this->staff->service($data, $this->shopId); // 发放员工提成
            parent::sendOutput('成功');
        } else {
            parent::sendOutput($res->getData(), $res->getErrorCode());
        }

    }

    /**
     * 所有员工
     * @return void
     */
    public function staffAll()
    {

        $params = $this->request->params();
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

//        $selectParams['shopId'] = $this->shopId;
        $result = $this->objStaff->getAllStaff($selectParams);

        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }

    }


    /**
     * 申请提现
     */
    public function addReflectDetail()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $ReflectDetailDate = [
            'staffId' => getArrayItem($params, 'staffId', ''),
            'userCenterId' => $this->onlineUserId,
            'reflectType' => getArrayItem($params, 'reflectType', ''),
            'money' => getArrayItem($params, 'money', ''),
            'reflectInfo' => getArrayItem($params, 'reflectInfo', []),
            'reflectStatus' => getArrayItem($params, 'reflectStatus', 4),
            'auditStatus' => getArrayItem($params, 'auditStatus', 1),
        ];

        foreach ($ReflectDetailDate as $key => $value) {
            if (empty($value) && $value !== 0) {
                $this->sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }
        $ReflectDetailDate['en_id'] = $this->onlineEnterpriseId;
        $ReflectDetailDate['reflectInfo'] = json_encode($ReflectDetailDate['reflectInfo']);
        $ReflectDetailDate['remark'] = getArrayItem($params, 'remark', '');
        $ReflectDetailDate['createTime'] = time();

        $result = $this->objStaff->addReflectDetail($ReflectDetailDate);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 员工提现列表
     * @return void
     */
    public function getWithdrawal()
    {
        $params = $this->request->params();

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $limit = $pageParams['limit'];
        $offset = $pageParams['offset'];

        $selectParams['en_id'] = $this->onlineEnterpriseId;
        $selectParams['userCenterId'] = $this->onlineUserId;
        if (isset($params['auditStatus']) and !empty($params['auditStatus'])) {
            $selectParams['auditStatus'] = $params['auditStatus'];
        }

        if (isset($params['staffId']) and !empty($params['staffId'])) {
            $selectParams['staffId'] = $params['staffId'];
        }

        if (isset($params['reflectStatus']) and !empty($params['reflectStatus'])) {
            $selectParams['reflectStatus'] = $params['reflectStatus'];
        }

        if (isset($params['end']) and !empty($params['end']) && isset($params['start']) and !empty($params['start'])) {
            $selectParams[] = ['createTime', '>=', strtotime($params['start'])];
            $selectParams[] = ['createTime', '<=', strtotime($params['end'])];
        }

        $db = new DStaffReflect('default');
        $list = $db->select($selectParams, '*', 'id DESC', $limit, $offset);
        foreach ($list as &$item) {
            $item['reflectInfo'] = json_decode($item['reflectInfo']);
        }

        $count = $db->count($selectParams);
        $pageData = [
            'pageIndex' => $params['page'],
            'pageSize' => $params['pageSize'],
            'pageTotal' => $count,
        ];
        parent::sendOutput($list, 0, $pageData);
    }


    /**
     * 更新排班详情
     * @return void
     * @throws \Exception
     */
    public function update_roster()
    {
        $id = $this->request->params();
        $time = date('Y-m-d', time());
        $db = new DShopRostering('default');
        $db->setTable('qianniao_shop_rostering_' . $id['id']);

        $list = $db->select([['time', '<', $time], ['status', '=', 0]]);
        $MTem = new MShopTemplate($id['id']);
        $Mstaff = new MStaff($id['id']);
        foreach ($list as &$item) {
            $staff = $Mstaff->getStaffInfo(['id' => $item['uid']])->getData();
            $time_slot = json_decode($item['time_slot']);
            $time_count = 0;
            foreach ($time_slot as $item) {
                $time_count += count($item);
            }
            $clock = json_decode($item['clock']);
            if (empty($clock)) {
                $db->update(['status' => -1], $item['id']);
            } else {
                $price = 0;
                foreach ($clock as $vo) {
                    if ($vo->timeResult == 'Normal') {
                        $tem_price = $MTem->details(['shift_id' => $item['template_id']])->getData();
                        $price += $tem_price['single_time'];
                    }
                }
                if ($price > 0) {
                    $balance = $staff['reward'] + $price;
                    $rewardTotal = $staff['rewardTotal'] + $price;
                    $Mstaff->clockReward($price, $balance, $staff['userCenterId'], $staff['id'], $this->shopId, $rewardTotal);
                }
                if (count($time_slot) != count($clock)) {
                    $db->update(['status' => -1], $item['id']);
                }
            }
        }
    }


    public function ExaminationRecord()
    {
        $params = $this->request->params();

        $db = new DShopRostering('default');
        $db->setTable('qianniao_shop_rostering_' . $this->onlineEnterpriseId);

        $list = $this->objStaff->getAllStaffData([['shopId', '>', 0]])->getData();

        foreach ($list as &$item) {
            $item['abnormal'] = 0;
            $item['no_clocking'] = 0;
            $item['late'] = 0;
            $item['early'] = 0;
            $item['normal'] = 0;
            $item['clock_in'] = 0;
            $rostering = $db->select([['time', 'like', '%' . $params['month'] . '%'], ['uid', '=', $item['id']]]);
            foreach ($rostering as $vo) {
                if ($vo['time'] < date('Y-m-d H:i:s', time())) {
                    if ($vo['status'] == -1) {
                        $item['abnormal'] += 1; //异常天数
                    }
                    $time_slot = json_decode($vo['time_slot']);
                    $time_count = 0;
                    foreach ($time_slot as $v) {
                        $time_count += count($v);
                        $item['clock_in'] += count($v);//应打卡次数
                    }

                    $clock = json_decode($vo['clock']);
                    if ($clock) {
                        foreach ($clock as $vs) {
                            if ($vs->timeResult == 'Late') {
                                $item['late'] += 1; //迟到次数
                            }
                            if ($vs->timeResult == 'Early') {
                                $item['early'] += 1; // 早退次数
                            }
                            if ($vs->timeResult == 'Normal') {
                                $item['normal'] += 1; // 正常打卡次数
                            }
                        }
                        $item['no_clocking'] += $time_count - count($clock);//缺卡次数
                    } else {
                        $item['no_clocking'] += $time_count; //缺卡次数
                    }
                }


            }
        }
        parent::sendOutput($list);

    }

    /**
     * 排班详情
     * @return void
     * @throws \Exception
     */
    public function ExaminationDetails()
    {
        $params = $this->request->params();

        $db = new DShopRostering('default');
        $db->setTable('qianniao_shop_rostering_' . $this->onlineEnterpriseId);

        $data = $this->objStaff->getStaffInfo([['shopId', '>', 0], ['id', '=', $params['staffId']]])->getData();

        $data['abnormal'] = 0;
        $data['no_clocking'] = 0;
        $data['late'] = 0;
        $data['early'] = 0;
        $data['normal'] = 0;
        $data['clock_in'] = 0;
        $rostering = $db->select([['time', 'like', '%' . $params['month'] . '%'], ['uid', '=', $data['id']]]);
        if ($rostering) {
            foreach ($rostering as $vo) {
                if ($vo['time'] < date('Y-m-d H:i:s', time())) {
                    if ($vo['status'] == -1) {
                        $data['abnormal'] += 1; //异常天数
                    }
                    $time_slot = json_decode($vo['time_slot']);
                    $time_count = 0;
                    foreach ($time_slot as $v) {
                        $time_count += count($v);
                        $data['clock_in'] += count($v);//应打卡次数
                    }

                    $clock = json_decode($vo['clock']);
                    if ($clock) {
                        foreach ($clock as $vs) {
                            if ($vs->timeResult == 'Late') {
                                $data['late'] += 1; //迟到次数
                            }
                            if ($vs->timeResult == 'Early') {
                                $data['early'] += 1; // 早退次数
                            }
                            if ($vs->timeResult == 'Normal') {
                                $data['normal'] += 1; // 正常打卡次数
                            }
                        }
                        $data['no_clocking'] += $time_count - count($clock);//缺卡次数
                    } else {
                        $data['no_clocking'] += $time_count; //缺卡次数
                    }
                }

            }
        }

        parent::sendOutput($data);

    }

    /**
     * 员工股份列表
     */
    public function stock_list()
    {
        $params = $this->request->params();
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        $staff = $this->staff->getStaffInfo(['userCenterId' => $this->onlineUserId])->getData();
        //uid
        if (isset($params['name']) && !empty($params['name'])) {
            $selectParams['name'] = $params['name'];
        }
        if (isset($params['pm']) && !empty($params['pm'])) {
            $selectParams['pm'] = $params['pm'];
        }
        $selectParams['staff_id'] = $staff['id'];
        $result = $this->Mstock->list($selectParams);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }
    }


    /**
     * 股权提现
     * @return void
     */
    public function StockWithdrawal()
    {
        $params = $this->request->params();
        $staff = $this->staff->getStaffInfo(['userCenterId' => $this->onlineUserId])->getData();

        if ($staff['use_stock'] < $params['number']) {
            parent::sendOutput('可用余额不足', ErrorCode::$dberror);
        }
        $dbConfig = new MBasicSetup($this->onlineEnterpriseId);
        $config = $dbConfig->getBasicField('stock_exchange')->getData();

        $money = $params['number'] * $config['stock_exchange'];// 实际兑换金额

        $res = $this->objStaff->exchange($params['number'], $money, $staff);
        if ($res) {
            parent::sendOutput('兑换成功');
        }
        parent::sendOutput('兑换失败');
    }

    /**
     * 员工转介绍
     * @return void
     */
    public function Referral()
    {
        $params = $this->request->params();
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];
        $staff = $this->staff->getStaffInfo(['userCenterId' => $this->onlineUserId])->getData();
        $list = $this->objCustomer->select(['recommenderType' => 2, 'recommenderId' => $staff['id']], $selectParams['limit'], $selectParams['offset']);
        $count = $this->objCustomer->count(['recommenderType' => 2, 'recommenderId' => $staff['id']]);
        $list = !empty($list) ? $list : [];
        $data = [
            'count' => $count
        ];
        parent::sendOutput($list, 0, $data);

    }


    /**
     * 全勤奖
     * @return void
     */
    public function attendance()
    {
        $staff = $this->objStaff->getAllStaff(['limit' => 10000, 'offset' => 0])->getData()['data'];
        $setting = new MBasicSetup($this->onlineEnterpriseId);
        $attendance = $setting->getBasicField('attendance')->getData(); //全勤奖

        $start = date('Y-m-01', strtotime('-1 month'));
        $end = date('Y-m-t', strtotime('-1 month'));

        $db = new DShopRostering('default');
        $db->setTable('qianniao_shop_rostering_'.$this->onlineEnterpriseId);
        foreach ($staff as $item)
        {
            $data = $db->select([['time', '>=', $start], ['time', '<=', $end], ['uid','=', $item['id']]]);
            if ($data){
                //上个月又排班
                $yc = $db->select([['time', '>=', $start], ['time', '<=', $end], ['uid','=', $item['id']], ['status', '=', -1]]);//查找上个月是否有异常打卡
                if (empty($yc)){
                    $balance = $item['reward'] + $attendance['attendance'];
                    //如果没有异常打卡发放全勤奖
                    $insertRewardDesc = [
                        'userCenterId' => $item['userCenterId'],
                        'staffId' => $item['id'],
                        'shopId' => $item['shopId'],
                        'customerId' => 0,
                        'title' => '发放'.date('Y-m', strtotime('-1 month')).'全勤提成',
                        'amount' => $attendance['attendance'],
                        'originId' => 0,
                        'changeAmount' => $balance,
                        'type' => 5,
                        'source' => 4,
                        'createTime' => time(),
                        'updateTime' => time(),
                    ];
                    $this->objStaff->updateStaff(['reward' => $balance], ['id' => $item['id']]);
                    $this->objDStaffRewardDesc->insert($insertRewardDesc);

                }

            }
        }
        echo '发放成功';

    }









}
