<?php

namespace app\common\logic;

use app\common\enum\OrderEnum;
use app\common\enum\PayEnum;
use app\common\model\store_finance_flow\StoreFinanceFlow;
use app\common\model\system_store\SystemStore;
use app\common\model\user\User;

class StoreFinanceFlowLogic extends BaseLogic
{

    public $order;
    public $user;
    public $other_arr;
    public $index = 0;
    public $financeSn;
    public $list = [];

    /**
     * 支出财务流水
     * @param $transaction_id
     * @param $number
     * @param $financialType
     * @param $storeId
     * @param $staffId
     * @param $status
     */
    public function out($transaction_id, $number, $financialType, $storeId = 0, $staffId = 0, $status = 1, $pay_type = 7)
    {
        $this->setData($number, $financialType, 0, $storeId, $staffId, $status, $transaction_id, $pay_type);
    }

    /**
     * 收入财务流水
     * @param $transaction_id
     * @param $number
     * @param $financialType
     * @param $storeId
     * @param $staffId
     * @param $status
     */
    public function in($transaction_id, $number, $financialType, $storeId = 0, $staffId = 0, $status = 1, $pay_type = 7)
    {
        $this->setData($number, $financialType, 1, $storeId, $staffId, $status, $transaction_id, $pay_type);
    }

    public function setData($number, $financialType, $pm, $storeId, $staffId, $status, $transaction_id, $pay_type = 7)
    {
        if (empty($this->financeSn)) {
            $this->financeSn = $this->getSn();
        }
        $data = [
            'order_id' => $this->order['id'],
            'transaction_id' => $transaction_id,
            'order_sn' => $this->order['order_id'],
            'user_id' => $this->user['uid'] ?? 0,
            'other_uid' => $this->other_arr['vip_uid'] ?? 0,
            'financial_type' => $financialType,
            'financial_pm' => $pm,
            'number' => $number,
            'pay_type' => $pay_type,
            'status' => 0,
            'store_id' => $storeId !== '' ? $storeId : $this->order['store_id'],
            'staff_id' => $staffId !== '' ? $staffId : $this->order['staff_id'],
            'financial_record_sn' => $this->financeSn . ($this->index++),
            'create_time' => time()
        ];
        switch ($financialType) {
            case OrderEnum::MERCHANT_ORDER_OBTAINS: // 商户
            case OrderEnum::ORDER_MARGIN: // 商户保证金
            case OrderEnum::OTHER_ORDER_OBTAINS: // 损耗'
                $data['type'] = OrderEnum::MERCHANT;
                break;
            case OrderEnum::PLATFORM_ORDER_OBTAINS: // 平台
            case OrderEnum::ORDER_HANDLING_FEES: // 手续费
                $data['type'] = OrderEnum::PLATFORM;
                break;
            case OrderEnum::SUPPLIER_ORDER_OBTAINS: // 供应链
                $data['type'] = OrderEnum::SUPPLIER;
                break;
            default: // 用户
                $data['type'] = OrderEnum::USER;
                break;
        }
        $this->list[] = $data;
    }

    public function save()
    {
        if (count($this->list) > 0) {
            (new StoreFinanceFlow())->insertAll($this->list);
        }
    }

    public function getSn()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        return 'fn' . $msectime . mt_rand(10000, max(intval($msec * 10000) + 10000, 98369));
    }

    public function getStoreOrder($orderId, $storeId = 0, $status = 0)
    {
        return StoreFinanceFlow::where('order_id', $orderId)
            ->where('store_id', $storeId)
            ->where('status', $status)
            ->where('financial_type', OrderEnum::MERCHANT_ORDER_OBTAINS)
            ->find();
    }

    /**
     * 备注
     * @param $id
     * @param $remark
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function remark($id, $remark)
    {
        $model = StoreFinanceFlow::where('id', $id)->where('store_id', request()->adminInfo['store_id'])->find();
        if (empty($model)) {
            throw new \Exception('记录不存在');
        }
        $model->remark = $remark;
        $model->save();
    }

    /**
     * 核销后更新用户余额
     */
    public function updateStatusUser($id, $uid, $money, $order_id)
    {
        StoreFinanceFlow::where('id', $id)->update(['status' => 1]);
        $find = User::where('id', $uid)->find();
        $capitalFlowDao = new CapitalFlowLogic($find);
        $capitalFlowDao->userIncome('system_balance_add', 'order', $order_id, $money);
        $find->inc('now_money', $money)->update();
    }
    /**
     * 核销后更新门店余额
     */
    public function updateStatusStore($order_id, $store_id, $money, $deposit)
    {
        StoreFinanceFlow::where(['order_id' => $order_id, 'financial_type' => 11])->update(['status' => 1]);
        StoreFinanceFlow::where(['order_id' => $order_id, 'financial_type' => 2])->update(['status' => 1]);
        if ($money > 0) {
            SystemStore::where('id', $store_id)->inc('store_money', $money)->update();
        }
        if ($deposit > 0) {
            SystemStore::where('id', $store_id)->inc('paid_deposit', $deposit)->update();
        }
        $find = StoreFinanceFlow::where(['order_id' => $order_id, 'financial_pm' => 1, 'financial_type' => 16, 'status' => 0])->find();
        StoreFinanceFlow::where(['order_id' => $order_id, 'financial_type' => 16])->update(['status' => 1]);
        if ($find) {
            if ($find['number'] > 0) {
                SystemStore::where('id', $store_id)->inc('attrition', $find['number'])->update();
            }
        }
    }

    /**
     * 财务退还金额相关
     * @param $orderSn
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public  function store_finance_back($orderSn)
    {
        $data = StoreFinanceFlow::where('order_sn', $orderSn)
            ->where(['financial_pm' => 1])
            ->select()->toArray();
        foreach ($data as &$value) {
            unset($value['id']);
            $value['financial_record_sn'] = (new StoreFinanceFlowLogic)->getSn();
            $value['financial_pm'] = 0;
            $value['financial_type'] = OrderEnum::PAY_BACK;
            $value['create_time'] = time();
            if ($value['status'] == 1) {
                switch ($value['type']) {
                    case 0:
                        $user = User::where('id', $value['other_uid'])->findOrEmpty();
                        $capitalFlowDao = new CapitalFlowLogic($user);
                        $capitalFlowDao->userExpense('system_now_money_back', 'system_back', $value['order_id'], $value['number']);
                        break;
                    case 1:
                        if ($value['number'] > 0 &&$value['financial_type']==2) {
                            SystemStore::where('id', $value['store_id'])->dec('store_money',$value['number'])->update();
                        }
                        if ($value['number'] > 0 &&$value['financial_type']==11) {
                            SystemStore::where('id', $value['store_id'])->dec('paid_deposit',$value['number'])->update();
                        }
                        if ($value['number'] > 0 &&$value['financial_type']==16) {
                            SystemStore::where('id', $value['store_id'])->dec('attrition',$value['number'])->update();
                        }
                        break;
                }
            }
        }
        (new StoreFinanceFlow)->saveAll($data);
    }
}