<?php


namespace JinDouYun\Controller\Shop;


use JinDouYun\Controller\BaseController;
use JinDouYun\Dao\BaseDao;
use JinDouYun\Dao\Customer\DCustomerCardNum;
use JinDouYun\Dao\Department\DStaff;
use JinDouYun\Dao\Shop\DShopRostering;
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 ApiShopProject extends BaseController
{

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

    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 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 DStaff('default');
        $this->objStaff->setTable('qianniao_staff_'.$this->onlineEnterpriseId);

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


    /**
     * 列表
     */
    public function list()
    {
        $params = $this->request->getRawJson();

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


        $selectParams['enterprise_id'] = $this->onlineEnterpriseId;

//        $selectParams['shop_id'] = $this->shopId;
        //项目昵称
        if (isset($params['name']) && !empty($params['name'])) {
            $selectParams['name'] = $params['name'];
        }

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

        $result = $this->obj->list($selectParams);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            foreach ($returnData['data'] as &$item)
            {
                $item['sold'] = $this->objSub->count([['project', 'like', '%'.$item['id'].'%']]);
            }
            $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);
        if ($result->isSuccess()) {

            $result = $result->getData();
            $result['sold'] = $this->objSub->count([['project', 'like', '%'.$result['id'].'%']]);
            $result['result'] = html_entity_decode($result['result']);
            parent::sendOutput($result);
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }


    /**
     * 计算价格
     * @return void
     */
    public function calculation()
    {
        $id = $this->request->param('id');
        if (empty($this->onlineUserId)) parent::sendOutput('未登录', 1002);

        $project = $this->obj->get(['id' => $id]);

        $pay_price = 0;// 实际支付价格
        $discount_price = 0;// 优惠金额
        $customer = $this->objCustomer->get(['userCenterId' => $this->onlineUserId]);
        $numWhere = [
            ['customer_id', '=', $customer['id']],
            ['project_id', '=', $id],
            ['number', '>', 0],
        ];
        $card = $this->objCardNum->get($numWhere);
        $to_price = $project['price'];
        $cost_price = $project['cost_price'];
        $card_id = 0;
        if ($card) {
            $card_id = $card['id'];
            $discount_price = $project['price'];
        } else {
            $pay_price = $project['price'];
        }
        $user = $this->objCustomer->get(['userCenterId' => $this->onlineUserId]);
        $data = [
            'project' => $id,
            'customer_id' => $customer['id'],
            'pay_price' => $pay_price,
            'discount_price' => $discount_price,
            'to_price' => $to_price,
            'cost_price' => $cost_price,
            'order_id' => 'wx'.$customer['id'].time().$this->getRandPass(),
            'card_id' => $card_id,
            'memberBalance' => $user['memberBalance']
        ];
        $this->cache->hset($data['order_id'], $this->onlineUserId, json_encode($data));

        parent::sendOutput($data);
    }


    /**
     * 创建订单
     * @return void
     * @throws \Exception
     */
    public function create()
    {
        $params = $this->request->getRawJson();

        $order = $this->cache->hget($params['order_id'], $this->onlineUserId);
        if (empty($order)) parent::sendOutput('未查到订单',ErrorCode::$dberror);
        $order = json_decode($order);

        if ($params['staff_id']){
            $order->uid = $params['staff_id'];
        }else{
            $staff = $this->objSub->getStaff($params, $this->shopId);
            if ($staff == false)  parent::sendOutput('当前时间段未匹配到员工',ErrorCode::$dberror);
            $order->uid = $staff;
        }
        $base = new BaseDao();
        $base->beginTransaction();
        $orderInset = [
            'shop_id' => $this->shopId,
            'project' => $order->project,
            'customer_id' => $order->customer_id,
            'pay_price' => $order->pay_price,
            'discount_price' => $order->discount_price,
            'to_price' => $order->to_price,
            'cost_price' => $order->cost_price,
            'order_id' => $order->order_id,
            'card_id' => $order->card_id,
            'uid' => $order->uid,
            'pay_type' => $params['pay_type'],
            'time' => $params['time'],
            'remarks' => $params['remarks'],
        ];

        if ($order->pay_price == 0){
            $orderInset['paid'] = 1;
        }
        $orderRes = $this->objSub->insert($orderInset);
        $this->cache->hdel($params['order_id'], $this->onlineUserId);
        if ($orderRes->isSuccess()){
            if ($order->pay_price > 0){
                if ($params['pay_type'] == 1){
                    //余额支付
                    $res = $this->objSub->yuePay($orderInset);
                    if (!$res->isSuccess()){
                        parent::sendOutput($res->getData(), ErrorCode::$dberror);
                    }
                    $base->commit();
                    parent::sendOutput(['status' => 'complete', 'data' => '支付成功']);
                }elseif ($params['pay_type'] == 2){
                    //微信支付
                    $res = $this->objSub->wxPay($orderInset, $this->request->get_onlineip(), $params['source']);
                    $base->commit();
                    parent::sendOutput(['status' => 'weixinPay', 'data' => $res->getData()]);
                }elseif ($params['pay_type'] == 3){
                    //支付宝支付
                }
            }
            $base->commit();
            parent::sendOutput(['status' => 'complete', 'data' => '支付成功']);
        }else{
            $base->rollBack();
            parent::sendOutput($orderRes->getData(),ErrorCode::$dberror);
        }
    }

    /**
     * 待支付支付
     * @return void
     * @throws \Exception
     */
    public function payment()
    {
        $id = $this->request->param('id');
        $pay_type = $this->request->param('pay_type');
        $source = $this->request->param('source');
        $order = $this->objSub->details(['id' => $id]);
        if (!$order->isSuccess()) parent::sendOutput('订单不存在',ErrorCode::$dberror);
        $base = new BaseDao();
        $base->beginTransaction();

        $order = $order->getData();
        if ($pay_type == 1){
            //余额支付
            $res = $this->objSub->yuePay($order);
            if (!$res->isSuccess()){
                parent::sendOutput($res->getData(), ErrorCode::$dberror);
            }
            $base->commit();
            parent::sendOutput(['status' => 'complete', 'data' => '支付成功']);
        }elseif ($pay_type == 2){
            //微信支付
            $res = $this->objSub->wxPay($order, $this->request->get_onlineip(), $source);
            $base->commit();
            parent::sendOutput(['status' => 'weixinPay', 'data' => $res->getData()]);
        }elseif ($pay_type == 3){
            //支付宝支付
        }

        $base->rollBack();
        parent::sendOutput('支付方式不存在',ErrorCode::$dberror);
    }

    /**
     * 日期查找员工
     * @return void
     *
     */
    public function choice()
    {
        $time = $this->request->param('time');

        if (empty($time)) parent::sendOutput('选择预约时间', ErrorCode::$dberror);

        $join = 'Left Join qianniao_staff_'.$this->onlineEnterpriseId.' as b on a.uid = b.id';
//        $rostering = $this->objRostering->select([['a.time', 'like', '%'.$time.'%'], ['a.template_id', '>', 1], ['a.shop_id','=',$this->shopId]], 'a.*', 'id DESC', '', '', [], false, true, $join)->getData();

        $db = new DShopRostering('default');
        $db->setTable('qianniao_shop_rostering_'.$this->onlineEnterpriseId);
        $filed = 'a.*,b.staffName,b.avatar,b.evaluate,b.info,b.is_technician';
        $rostering = $db->select([['a.time', 'like', '%'.$time.'%'], ['a.template_id', '>', 1], ['a.shop_id','=',$this->shopId], ['b.is_technician' ,'=',  1]],$filed , 'a.id DESC', '', '', [], false, true, $join);
        foreach ($rostering as &$item)
        {
            $item['time_slot'] = json_decode($item['time_slot']);
            $item['clock'] = json_decode($item['clock']);
        }
        if (!empty($rostering)){
            parent::sendOutput($rostering);
        }
        parent::sendOutput('当天未找到员工', ErrorCode::$dberror);
    }


    /**
     * 员工可预约时间段
     * @return void
     */
    public function choice_time()
    {
        $time = $this->request->param('time');
        $uid = $this->request->param('uid');

        $rostering = $this->objRostering->details([['time', 'like', '%'.$time.'%'], ['uid', '=', $uid]])->getData();
       
        $rostering['time_slot'] = json_decode($rostering['time_slot']);
        $rostering['clock'] = json_decode($rostering['clock']);


        $Stime = strtotime($time);
        $Etime = strtotime($time) + 86400;
        $where[] = ['uid', '=', $uid];
        $where[] = ['time', '>=', $Stime];
        $where[] = ['time', '<=', $Etime];
        $order = $this->objSub->select($where)->getData();

        $rostering['reserved'] = [];
        if ($order){
            foreach ($order['data'] as $item)
            {
                $rostering['reserved'][] = date('H:i:s', $item['time']);
            }
        }

        parent::sendOutput($rostering);
    }


}
