<?php
/**
 * 商铺管理模块
 * Created by PhpStorm.
 * User: wxj
 * Date: 2019/10/31
 * Time: 15:02
 */

namespace JinDouYun\Model\Shop;

use AlibabaCloud\SDK\Dingtalk\Vcrm_1_0\Models\DescribeRelationMetaResponseBody\relationMetaDTOList\items\props\fields\relateProps;
use Exception;


use JinDouYun\Cache\SystemCache;
use JinDouYun\Dao\BaseDao;
use JinDouYun\Dao\Customer\DCustomerCard;
use JinDouYun\Dao\Customer\DCustomerCardNum;
use JinDouYun\Dao\Shop\DShopCard;
use JinDouYun\Dao\Shop\DShopCardBind;
use JinDouYun\Dao\Shop\DShopCardOrder;
use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\Customer\MMemberBalanceDetail;
use JinDouYun\Model\System\MPaymentSetting;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Model\MBaseModel;
use Monolog\Handler\IFTTTHandler;
use Util\WeiXin\Pay;


class MShopCardOrder extends MBaseModel
{

    private $obj;
    private $cutTable = 250000;
    private $enterpriseId;
    private $userCenterId;
    private $DCardBind;
    private $DCard;

    public function __construct($enterpriseId, $userCenterId = '')
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        parent::__construct($this->enterpriseId, $this->userCenterId);
        $this->obj = new DShopCardOrder('default');
        $this->DCardBind = new DShopCardBind('default');
        $this->DCard = new DShopCard('default');
        $this->DCustomerCard = new DCustomerCard('default');
        $this->DCustomerCardNum = new DCustomerCardNum('default');

    }

    /**
     * 列表
     * @param $where
     * @return mixed
     */
    public function list($where)
    {
        $limit = $where['limit'];
        unset($where['limit']);
        $offset = $where['offset'];
        unset($where['offset']);


        $join = 'Left Join qianniao_customer_'.$this->enterpriseId.' as b on a.customer_id = b.id';
        $join .= ' Left Join qianniao_shop_card as c on a.card_id = c.id';

        $wherein[] = ['a.enterprise_id' ,'=' ,$this->enterpriseId];
        if (isset($where['name']) and !empty($where['name'])){
            $wherein[] = ['b.id|b.name', '=', $where['name']];
        }
        if (isset($where['card_name']) and !empty($where['card_name'])){
            $wherein[] = ['c.id|c.name', '=', $where['card_name']];
        }

        if (isset($where['paid'])){
            $wherein[] = ['paid' , '=', 1];
        }

        if (isset($where['time'])){
            $wherein[]  = ['a.createTime', '>=', strtotime($where['time'][0])];
            $wherein[]  = ['a.createTime', '<=', strtotime($where['time'][1])];
        }



        $dbResult = $this->obj->select($wherein, 'a.*,b.name as user_name,c.name as card_name,c.image', 'id DESC', $limit, $offset, array(), true, false,$join);
        $count = $this->obj->count($wherein, [], $join);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->obj->error(), ErrorCode::$dberror);
        }

        $return = [
            'data' => $dbResult,
            'total' => $count,
        ];

        if($return === false){
            return ResultWrapper::fail($this->obj->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($return);
        }
    }


    /**
     * 详情
     * @param $where
     * @return mixed
     */
    public function details($where)
    {
        if(empty($where)){
            return ResultWrapper::success($where);
        }
        $dbResult = $this->obj->get($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->obj->error(), ErrorCode::$dberror);
        }

        return ResultWrapper::success(self::formatInfo($dbResult));

    }

    /**
     * Doc: (des="添加")
     * User: XMing
     * Date: 2020/7/15
     * Time: 10:42 上午
     * @throws Exception
     * @param array $params
     * @return ResultWrapper
     */
    public function insert(array $params)
    {
        $res = $this->obj->insert($params);
        if ($res){
            return ResultWrapper::success('添加成功');
        }else{
            return ResultWrapper::fail($this->obj->error(), ErrorCode::$dberror);
        }

    }

    public function update($params, $id)
    {
        $data = $this->obj->get($id);
        if (!$data){
            return ResultWrapper::fail('数据不存在', ErrorCode::$dberror);
        }

        $dbResult = $this->obj->update($params,$id);
        if($dbResult === false){
            return ResultWrapper::fail($this->obj->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success('修改成功');

    }

    /**
     * 完成订单发放优惠卡
     * @param $data
     * @return void
     */
    public function complete($data)
    {
        $this->obj->beginTransaction();
        $card = $this->DCardBind->select(['card_id' => $data['card_id']]);
        $res = true;
        if ($card) {
            $cardRes = $this->DCustomerCard->insert(['customer_id' => $data['customer_id'], 'enterprise_id' => $data['enterprise_id'], 'card_id' => $data['card_id']]);
            foreach ($card as $item)
            {
                $user_card = [
                    'customer_card' => $cardRes,
                    'enterprise_id' => $data['enterprise_id'],
                    'customer_id' => $data['customer_id'],
                    'project_id' => $item['project_id'],
                    'number' => $item['number']
                ];
                $res = $this->DCustomerCardNum->insert($user_card);
            }
            $res = $this->obj->update(['paid' => 1], $data['id']);
        }
        if ($res){
            $this->obj->commit();
            return true;
        }else{
            $this->obj->rollBack();
            return false;
        }
    }


    /**
     * 格式数据详情
     * @param $data
     * @return mixed
     */
    public function formatInfo($data)
    {
        return $data;
    }


    public function delete($where)
    {
        $res = $this->obj->delete($where);
        if ($res){
            return ResultWrapper::success('删除成功');
        }
        return ResultWrapper::fail($this->obj->error(), ErrorCode::$dberror);
    }


    /**
     * 微信支付
     * @param $params
     * @return mixed
     * @throws Exception
     */
    public function wxPay($params, $ip, $source)
    {
        $objSystemCache = new SystemCache();

        $objMPaymentSetting = new MPaymentSetting($this->userCenterId, $this->enterpriseId);
        $result = $objMPaymentSetting->getPayData(1);
        if (!$result->isSuccess() || empty($result->getData())) {
            return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
        }
        $payment = $result->getData();

        //获取客户信息
        $objMCustomer = new MCustomer($this->enterpriseId, $this->userCenterId);
        $customerData = $objMCustomer->getCustomerInfoByUserCenterId($this->userCenterId);

        if (!$customerData->isSuccess()) {
            return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode());
        }
        $customerData = $customerData->getData();

        //wx
        /********************生成小程序唤起支付用到的参数(原配置)*****/
        /**$weixinConfigData = Factory::config()->get('weixin');
         * if (empty($weixinConfigData)) {
         * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
         * }*/

        // 获取当前登录企业的小程序配置
        $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->enterpriseId);
        if (empty($miniprogramSetting)) {
            return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
        }
        $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid


        // 获取配置文件微信公众号
        /**$weixinConfigData = Factory::config()->get('weixin');
         * if (empty($weixinConfigData)) {
         * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
         * }*/

        switch ($source) {
            case StatusCode::$source['ByteProgram'];
                //$appid = $weixinConfigData['offiaccount']['appid'];
                $appid = $miniprogramSetting['appid'];
                $paySource = 'byteDanceH5';
                break;
            case StatusCode::$source['miniProgram'];
                $appid = $miniprogramSetting['appid'];
                $paySource = 'miniProgram';
                break;
            default :
                $appid = $payment['mobileAppid'];
                $paySource = 'APP';
                break;
        }
        $weixinConfigData = [
            'mch_id'        => $payment['mchId'],
            'apiPartnerKey' => $payment['apiPartnerKey'],
            'appid'         => $appid
        ];
        $attach = $this->enterpriseId . '|' . $this->userCenterId . '|' . implode('|', [$params['order_id']]);
        //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old
        $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
        $payParams = $objPay->unifiedorder($params['order_id'],$params['pay_price'], $ip, $paySource, '千鸟云商', $customerData['openId'], $attach);

        return ResultWrapper::success($payParams->getData());

    }

    public function yuePay($param)
    {
        //获取客户信息
        $objMCustomer = new MCustomer($this->enterpriseId, $this->userCenterId);
        $customerData = $objMCustomer->getCustomerInfoByUserCenterId($this->userCenterId);

        if (!$customerData->isSuccess()) {
            return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode());
        }
        $customerData = $customerData->getData();
        $price = $param['pay_price'];// 实际支付

        if ($customerData['memberBalance'] < $price){
            return ResultWrapper::fail('余额不足', 1005);
        }

        $before = $customerData['memberBalance'];
        $after = $customerData['memberBalance'] - $price;


        $Mbalance = new MMemberBalanceDetail($this->enterpriseId, $this->userCenterId);
        $Mbalance->create($customerData['id'], $customerData['userCenterId'], 4, $before, $price, $after,'支付优惠卡订单', '余额支付优惠卡订单');
        $res  = $this->paySuccess($param['order_id']);
        if ($res){
            return ResultWrapper::success('支付成功');
        }else{
            return ResultWrapper::fail('支付失败', 1005);
        }



    }

    /**
     * 支付成功后
     * @return void
     */
    public function paySuccess($order_id)
    {
        $data = $this->obj->get(['order_id' => $order_id]);
        $this->obj->beginTransaction();
        $card = $this->DCardBind->select(['card_id' => $data['card_id']]);
        $res = true;
        if ($card) {
            $cardRes = $this->DCustomerCard->insert(['customer_id' => $data['customer_id'], 'enterprise_id' => $data['enterprise_id'], 'card_id' => $data['card_id']]);
            foreach ($card as $item)
            {
                $user_card = [
                    'customer_card' => $cardRes,
                    'enterprise_id' => $data['enterprise_id'],
                    'customer_id' => $data['customer_id'],
                    'project_id' => $item['project_id'],
                    'number' => $item['number']
                ];
                $this->DCustomerCardNum->insert($user_card);
            }
            $res = $this->obj->update(['paid' => 1], $data['id']);
        }
        if ($res){
            $this->obj->commit();
            return true;
        }else{
            $this->obj->rollBack();
            return false;
        }
    }

}