<?php
declare (strict_types = 1);

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\admin\traits\Actions;
use think\annotation\route\Group;
use think\annotation\route\Route;
use think\facade\Db;
use app\common\model\MoneyLog as MoneyLogModel;

#[Group("user/money_log")]
class MoneyLog extends Backend
{
    use Actions{
        edit as private _edit;
        multi as private _multi;
        import as private _import;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new MoneyLogModel();
        $this->assign('typeInList',  site_config('addonsd.money_in_type')); //
        $this->assign('typeOutList',  site_config('addonsd.money_out_type'));

        $this->assign('bankList',  site_config('addonsd.bank_account'));
        $this->relationField=['users'];
    }

    //查看 
    #[Route('GET,JSON','index')]
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if($this->request->post('selectpage')){
            return $this->selectpage();
        }
        [$where, $order, $limit, $with] = $this->buildparams();
        $list = $this->model
            ->withJoin($with,'left')
            //如果没有使用operate filter过滤的情况下,推荐使用with关联，可以提高查询效率
            ->where('money_log.status', 1)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
   

    //修改
    #[Route("GET,POST","edit")]
    public function edit(mixed $row=null)
    {
        $ids = $this->request->get('ids');
        if(!$row || is_array($row)){
            $row = $this->model->find($ids);
        }
        if (!$row) {
            $this->error(__('没有找到记录'));
        }
        if(count($this->volidateFields)>0){
            foreach ($this->volidateFields as $field=>$value){
                if($row[$field]!=$value){
                    $this->error(__('没有操作权限'));
                }
            }
        }
        if (false === $this->request->isPost()) {
            $this->assign('parentList', self::getTypeAllByType($row->type));
            $this->assign('row', $row);
            return $this->fetch();
        }
        $params = array_merge($this->request->post("row/a"),$this->postParams);
        if (empty($params)) {
            $this->error(__('提交的参数不能为空'));
        }
        if(!$this->request->checkToken('__token__',['__token__'=>$this->request->post('__token__')])){
            $this->error(__('token错误，请刷新页面重试'));
        }
        foreach ($params as &$value){
            if(is_array($value)){
                $value=implode(',',$value);
            }
            if($value===''){
                $value=null;
            }
        }
        $result = false;
        Db::startTrans();
        try {
            if(isEnglish($params['type_name'])){
                $arr = self::getTypeAllByType((int)$params['type']);
                $params['type_name'] = $arr[$params['type_name']];
            }
            $params['create_month'] = date('Ym', strtotime($params['create_date']));
            $result = $row->save($params);
            if($this->callback){
                $callback=$this->callback;
                $callback($row);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('没有数据被更新'));
        }
        $this->success();
    }

  

    //删除
    #[Route("GET,POST","del")]
    public function del()
    {
        $ids = $this->request->param("ids");
        if (empty($ids)) {
            $this->error(__('参数%s不能为空', ['s'=>'ids']));
        }
        $pk = $this->model->getPk();
        $list = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if(count($this->volidateFields)>0){
                    foreach ($this->volidateFields as $field=>$value){
                        if($item[$field]!=$value){
                            $this->error(__('没有操作权限'));
                        }
                    }
                }
                $item->status=0;
                $count += $item->save();
            }
            if($this->callback){
                $callback=$this->callback;
                $callback($ids);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('没有记录被删除'));
    }

    //更新
    #[Route("GET,POST","multi")]
    public function multi()
    {
        //通过定义callback回调函数来执行更新后的操作
        $this->callback=function ($ids,$field,$value){};
        return $this->_multi();
    }

    //导入
    #[Route("GET,POST","import")]
    public function import()
    {
        //通过定义callback回调函数来处理导入的数据
        $this->callback=function ($inserData){
            return $inserData;
        };
        return $this->_import();
    }

    //获取分类
    private static function getTypeAllByType(int $type)
    {
       return ($type== 1)?site_config('addonsd.money_in_type'):site_config('addonsd.money_out_type');
    }

}
