<?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)
    {
        $flow = StoreFinanceFlow::where('id', $id)->find();
        StoreFinanceFlow::where('order_id', $order_id)->where('financial_type', $flow['financial_type'])->update(['status' => 1]);
        $find = User::where('id', $uid)->find();
        $capitalFlowDao = new CapitalFlowLogic($find);
        $capitalFlowDao->userIncome('system_balance_add', 'order', $order_id, $money);
        User::where('id', $uid)->inc('now_money', $money)->update();
    }
    /**
     * 核销后更新门店余额
     */
    public function updateStatusStore($order_id, $store_id, $money, $deposit)
    {
        $store = SystemStore::where('id', $store_id)->find();
        $capitalFlowDao = new CapitalFlowLogic($store, 'store');
        if ($deposit > 0 && $store['paid_deposit'] < $store['security_deposit']) {
            StoreFinanceFlow::where(['order_id' => $order_id, 'financial_type' => 11])->update(['status' => 1]);
            $capitalFlowDao->storeIncome('store_paid_deposit_add', 'order', $order_id, $deposit,'','paid_deposit');
            SystemStore::where('id', $store_id)->inc('paid_deposit', $deposit)->update();
        }
        if ($money > 0) {
            StoreFinanceFlow::where(['order_id' => $order_id, 'financial_type' => 2])->update(['status' => 1]);
            $capitalFlowDao->storeIncome('store_money_add', 'order', $order_id, $money,'','store_money');
            SystemStore::where('id', $store_id)->inc('store_money', $money)->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) {
                $capitalFlowDao->storeIncome('store_attrition_add', 'order', $order_id, $find['number'],'','attrition');
                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, $store_id)
    {
        $list = StoreFinanceFlow::where('order_sn', $orderSn)
            ->where(['financial_pm' => 1, 'status' => 1])
            ->select();
        foreach ($list as $k => $value) {
            //用户
            if($value['type']==0){
                if ($value['financial_type'] == 12 && $value['other_uid'] > 0) {
                    $user = User::where('id', $value['other_uid'])->findOrEmpty();
                    $capitalFlowDao = new CapitalFlowLogic($user);
                    $user->now_money = bcsub($user['now_money'], $value['number'], 2);
                    $user->save();
                    $capitalFlowDao->userExpense('user_order_promotion_refund', 'system_back', $value['order_id'], $value['number'], '', $value['pay_type']);
                }
            }elseif($value['type']==1){
                $store = SystemStore::where('id', $store_id)->find();
                $capitalFlowDao = new CapitalFlowLogic($store, 'store');
                if ($value['number'] > 0 && $value['financial_type'] == 2) {
                    $find=SystemStore::where('id', $value['store_id'])->find();
                    $find->store_money=bcsub($find['store_money'], $value['number'],2);
                    $find->save();
                    $capitalFlowDao->storeExpense('store_money_refund', 'order', $value['order_id'],$value['number'],'','store_money');

                }
                if ($value['number'] > 0 && $value['financial_type'] == 16) {
                    $find=SystemStore::where('id', $value['store_id'])->find();
                    $find->attrition=bcsub($find['attrition'], $value['number'],2);
                    $find->save();
                    $capitalFlowDao->storeExpense('store_attrition_refund', 'order', $value['order_id'], $value['number'],'','attrition');

                }
            }
        }
        $find = StoreFinanceFlow::where('order_sn', $orderSn)->where('financial_type', 11)->where('status', 1)->find();
        if ($find && $find['number'] > 0) {
            $find=SystemStore::where('id', $value['store_id'])->find();
            $capitalFlowDao = new CapitalFlowLogic($find, 'store');
            $find->paid_deposit=bcsub($find['paid_deposit'], $value['number'],2);
            $find->save();
            $capitalFlowDao->storeExpense('store_paid_deposit_refund', 'order', $value['order_id'],$value['number'],'','paid_deposit');
        }
        // $data = StoreFinanceFlow::where('order_sn', $orderSn)->select();
        // foreach ($data as $k => &$value) {
        //     $value['status'] = -1;
        //     $value['financial_record_sn'] = (new StoreFinanceFlowLogic)->getSn();
        //     $value['financial_pm'] = 0;
        //     $value['financial_type'] = OrderEnum::PAY_BACK;
        //     $value['create_time'] = time();
        // }
        StoreFinanceFlow::where('order_sn', $orderSn)->update(['status' => -1]);
        // (new StoreFinanceFlow)->saveAll($data);
    }
}