<?php


namespace JinDouYun\Controller\Shop;


use JinDouYun\Controller\BaseController;
use JinDouYun\Dao\BaseDao;
use JinDouYun\Dao\Customer\DCustomerCardNum;
use JinDouYun\Dao\Department\DStaffComment;
use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\Customer\MCustomerCard;
use JinDouYun\Model\Shop\MShopProject;
use JinDouYun\Model\Shop\MShopRostering;
use JinDouYun\Model\Shop\MShopSubscribe;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\Ding;
use Mall\Framework\Factory;

class ApiShopSubscribe extends BaseController
{

    private $obj;
    private $objCustomer;
    private $objCard;
    private $objRostering;
    private $objSub;
    private $objProject;

    public function __construct($isCheckAcl = true, $isMustLogin = false, $checkToken = true, $getAreaCode = false, $checkShopToken = true, $checkSupplierToken = false)
    {
        parent::__construct($isCheckAcl, $isMustLogin, $checkToken, $getAreaCode, $checkShopToken, $checkSupplierToken);
        $authorization = $this->request->getServerParam('HTTP_AUTHORIZATION');
        if (!empty($authorization)) {
            self::getUserIdByAuthorization();
        }
        $shopToken = $this->request->param('SHOP-TOKEN');
        if (!empty($shopToken)){
            self::getShopIdByShopToken($shopToken);
        }
        $this->obj = new MShopSubscribe($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->objProject = new MShopProject($this->onlineEnterpriseId, $this->onlineUserId);

        $this->cache = Factory::cache('user');
    }


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

        $customer = $this->objCustomer->get(['userCenterId' => $this->onlineUserId]);
        $selectParams['customer_id'] = $customer['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'];
        }
        // 时间
        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->obj->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 details()
    {
        $where = [];
        $id = $this->request->param('id');
        if (!empty($id)) {
            $where['id'] = $id;
        }
        $result = $this->obj->details($where)->getData();
        $project_id = explode(',', $result['project']);
        $result['project'] = [];
        foreach ($project_id as $vo)
        {
            $project = $this->objProject->get(['id' => $vo], 'id,name,price,ot_price,info,image');
            $result['project'][] = $project;
        }
//        $project = $this->objProject->select([['id', 'in', $result['project']]], 'id,name,price,ot_price,info,image');

        parent::sendOutput($result);
    }

    /**
     * 申请退款
     * @return void
     */
    public function ApplyForRefund()
    {
        $id = $this->request->param('id');
        $refund_remarks = $this->request->param('refund_remarks');
        $order = $this->obj->details(['id' => $id]);
        if (!$order->isSuccess()) parent::sendOutput('订单不存在',ErrorCode::$dberror);
        $order = $order->getData();

        if ($order['status'] == 1) parent::sendOutput('订单已完成',ErrorCode::$dberror);
        if ($order['refund'] == 1) parent::sendOutput('已申请退款，请耐心等待',ErrorCode::$dberror);

        $res =  $this->obj->update(['refund' => 1, 'refund_remarks' => $refund_remarks], $id);
        if ($res->isSuccess())parent::sendOutput('提交申请成功');
        parent::sendOutput($res->getData(), ErrorCode::$dberror);
    }


    /**
     * 员工订单
     * @return void
     */
    public function staff_order()
    {

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

        $customer = $this->objCustomer->get(['userCenterId' => $this->onlineUserId]);
        $selectParams['customer_id'] = $customer['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'];
        }

        // 时间
        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->obj->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 update()
    {
        $id = $this->request->param('id');
        $param['uid'] = $this->request->param('uid');
        $param['project'] = $this->request->param('project');
        $param['discount_price'] = $this->request->param('discount_price');
        $param['to_price'] = $this->request->param('to_price');
        $param['stay_price'] = $this->request->param('stay_price');

        $data = $this->obj->details(['id' => $id]);

        if (!$data->isSuccess()) parent::sendOutput('订单不存在', $data->getErrorCode());
        $project = $this->Mproject->select([['id', 'in', $param['project']]]);
        $cost_price = 0;
        foreach ($project as $item) {
            $cost_price += $item['cost_price'];
        }

        $param['cost_price'] = $cost_price;

        $param['time'] = strtotime($param['time']);
        $res = $this->obj->update($param, $id);
        if ($res->isSuccess()) {
            parent::sendOutput('修改成功');
        } else {
            parent::sendOutput($res->getData(), $res->getErrorCode());
        }
    }

    /**
     * 取消预约订单
     * @return void
     */
    public function cancel()
    {
        $params = $this->request->getRawJson();
        if (!$params['id']) $this->sendOutput('参数为空', ErrorCode::$paramError);
        $data = $this->obj->details(['id' => $params['id']]);


        if (!$data->isSuccess()) parent::sendOutput('订单不存在', $data->getErrorCode());
        $data = $data->getData();
        if ($data['status'] == 1) parent::sendOutput('订单已完成', 1005);
        if ($data['paid'] == 1){
            $this->obj->refund($data);
        }
        $res = $this->obj->update(['status' => -1, 'completeTime' => time()], $params['id']);
        if ($res->isSuccess()) {
            parent::sendOutput('取消成功');
        } else {
            parent::sendOutput($res->getData(), $res->getErrorCode());
        }

    }

    /**
     * 评价
     * @return void
     */
    public function comment()
    {
        $params = $this->request->getRawJson();
        $db = new DStaffComment('default');

        $customer = $this->objCustomer->get(['userCenterId' => $this->onlineUserId]);

        if (empty($params['uid'])) $this->sendOutput('选择员工', ErrorCode::$paramError);
        if (empty($params['comment'])) $this->sendOutput('请填写评论', ErrorCode::$paramError);
        if (empty($params['score'])) $this->sendOutput('请添加评分', ErrorCode::$paramError);

        $order_id = $params['order_id'];
        unset($params['order_id']);
        $order = $this->obj->details(['id' => $order_id])->getData();
        if ($order['is_evaluate'] == 1) $this->sendOutput('该订单已评价', ErrorCode::$paramError);

        $params['customer_id'] = $customer['id'];
        $params['en_id'] = $this->onlineEnterpriseId;
        $res = $db->insert($params);
        if ($res){
            $this->obj->update(['is_evaluate' => 1], $order_id);
            $this->sendOutput('评价成功');
        }
        $this->sendOutput('评价失败',ErrorCode::$paramError);

    }

    /**
     * 评价列表
     * @return void
     */
    public function comment_list()
    {
        $params = $this->request->getRawJson();
        $db = new DStaffComment('default');

        if (empty($params['id']))  $this->sendOutput('参数为空',ErrorCode::$paramError);
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $limit = $pageParams['limit'];
        $offset = $pageParams['offset'];
        $id = $params['id'];

        $list = $db->select(['uid' => $id, 'en_id' => $this->onlineEnterpriseId], '*', 'id DESC', $limit, $offset);
        foreach ($list as &$item)
        {
            $item['customer'] = $this->objCustomer->get(['id' => $item['customer_id']]);
        }
        $count = $db->count(['uid' => $id, 'en_id' => $this->onlineEnterpriseId]);
        $pageData = [
            'pageIndex' => $params['page'],
            'pageSize' => $params['pageSize'],
            'pageTotal' => $count,
        ];
        parent::sendOutput($list, 0, $pageData);

    }




}
