<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\api\lists;

use app\common\enum\user\AccountLogEnum;
use app\common\model\user\UserAccountLog;
use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Sum;
use app\common\lists\ListsExtendInterface;
use app\common\lists\ListsSearchInterface;

/**
 * 账户流水列表
 * Class AccountLogLists
 * @package app\shopapi\lists
 */
class AccountLogLists extends BaseApiDataLists implements ListsExtendInterface
{

    /**
     * @notes 搜索条件
     * @return array
     * @author 段誉
     * @date 2023/2/24 14:43
     */
    public function queryWhere()
    {
        // 指定用户
        if (isset($this->params['user_id']) && $this->params['user_id'] > 0) {
            $where[] = ['user_id', '=', $this->params['user_id']];
        } else {
            $where[] = ['user_id', '=', $this->userId];
        }

        // 用户月明细
        if (isset($this->params['type']) && $this->params['type'] == 'um') {
            $where[] = ['change_type', 'in', AccountLogEnum::getUserMoneyChangeType()];
        }

        // 变动类型
        if (!empty($this->params['action'])) {
            $where[] = ['action', '=', $this->params['action']];
        }
        // 变动时间
        if (!empty($this->params['time'])) {
            $date = strtotime($this->params['time']);
            $startTime = $date; // 获取该日期零点的时间戳
            $endTime = $date + 86399; // 获取该日期24小时后的时间戳
            $where[] = ['create_time', 'between', [$startTime, $endTime]];
        }
        return $where;
    }


    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 段誉
     * @date 2023/2/24 14:43
     */
    public function lists(): array
    {
        $field = 'change_type,change_amount,action,create_time,remark';
        $lists = UserAccountLog::field($field)
            ->where($this->queryWhere())
            ->order('id', 'desc')
            ->limit($this->limitOffset, $this->limitLength)
            ->select()
            ->toArray();
        foreach ($lists as &$item) {
            $item['type_desc'] = AccountLogEnum::getChangeTypeDesc($item['change_type']);
            $symbol = $item['action'] == AccountLogEnum::DEC ? '-' : '+';
            $item['change_amount_desc'] = $symbol . $item['change_amount'];
        }
        return $lists;
    }

    public function extend(){
        $deposit=UserAccountLog::where($this->queryWhere())->where('change_type',203)->sum('change_amount');
        $user_money=UserAccountLog::where($this->queryWhere())->where('change_type',202)->sum('change_amount');
        return ['deposit'=>$deposit,'user_money'=>$user_money];

    }

    /**
     * @notes 获取数量
     * @return int
     * @author 段誉
     * @date 2023/2/24 14:44
     */
    public function count(): int
    {
        return UserAccountLog::where($this->queryWhere())->count();
    }

    /**
     * 公司日流水统计
     */
    public function company_lists(): array
    {
        $field = 'change_type,change_amount,action,create_time,remark,user_id';
        $where[] = ['company_id','=', $this->params['company_id']];
        // 变动时间
        if (!empty($this->params['time'])) {
            $date = strtotime($this->params['time']);
            $startTime = $date; // 获取该日期零点的时间戳
            $endTime = $date + 86399; // 获取该日期24小时后的时间戳
            $where[] = ['create_time', 'between', [$startTime, $endTime]];
        }else{
            // $where[] = ['create_time', 'between', [strtotime(date('Y-m-d')), strtotime(date('Y-m-d'))+86366]];
        }

        $lists = UserAccountLog::field($field)
            ->where($where)
            ->with(['userInfo'])
            // ->whereDay('create_time')
            ->order('id', 'desc')
            ->limit($this->limitOffset, $this->limitLength)
            ->select()
            ->toArray();

        foreach ($lists as &$item) {
            $item['type_desc'] = AccountLogEnum::getChangeTypeDesc($item['change_type']);
            $symbol = $item['action'] == AccountLogEnum::DEC ? '-' : '+';
            $item['change_amount_desc'] = $symbol . $item['change_amount'];
        }

        return $lists;
    }

    /**
     * 公司月流水统计
     */
    public function company_year_count()
    {
        $where = [
            'company_id' => $this->params['company_id'],
            'action' => 1,
        ];
        $where2 = [
            'company_id' => $this->params['company_id'],
            'action' => 2,
        ];
        $data = [['month' => date('Y') . '-01'], ['month' => date('Y') . '-02'], ['month' => date('Y') . '-03'], ['month' => date('Y') . '-04'], ['month' => date('Y') . '-05'], ['month' => date('Y') . '-06'], ['month' => date('Y') . '-07'], ['month' => date('Y') . '-08'], ['month' => date('Y') . '-09'], ['month' => date('Y') . '-10'], ['month' => date('Y') . '-11'], ['month' => date('Y') . '-12']];
        $year = date('Y');
        $change_amount_1 = UserAccountLog::whereYear('create_time', $year)
            ->where($where)
            ->field('DATE_FORMAT(FROM_UNIXTIME(create_time), "%Y-%m") as month, SUM(change_amount) as total')
            ->group('month')
            ->order('month')
            ->select();
        $change_amount_2 = UserAccountLog::whereYear('create_time', $year)
            ->where($where2)
            ->field('DATE_FORMAT(FROM_UNIXTIME(create_time), "%Y-%m") as month, SUM(change_amount) as total')
            ->group('month')
            ->order('month')
            ->select();
        foreach ($data as $k => $v) {
            foreach ($change_amount_1 as $key => $val) {
                if ($v['month'] == $val['month']) {
                    $data[$k]['income'] = $val['total'];
                    if (!isset($data[$k]['expenditure'])) {
                        $data[$k]['expenditure'] = 0;
                    }
                    $data[$k]['income'] = $val['total'];
                }
            }
            foreach ($change_amount_2 as $key => $val) {
                if ($v['month'] == $val['month']) {
                    $data[$k]['expenditure'] = $val['total'];
                    if (!isset($data[$k]['income'])) {
                        $data[$k]['income'] = 0;
                    }
                }
            }
            $data[$k]['remark'] = '任务收益';
            if (!isset($data[$k]['income']) || !isset($data[$k]['expenditure'])) {
                unset($data[$k]);
            }
        }
        return array_reverse($data);
    }
}