<?php

namespace app\controller\manager;

use app\exception\RepositoryException;
use app\model\Account;
use app\model\Account as AccountModel;
use app\model\PayMonthLog;
use app\model\Position;
use app\model\Worksite;
use app\repository\AccountRepository;
use app\service\Math;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\response\Json;
use think\response\Redirect;
use think\response\View;

/**
 * 工资列表 月
 *
 * Class Pay
 * @package app\controller\manager
 */
class Pay extends Base
{
    protected $noNeedLogin = ['getAccountList', 'list'];

    /**
     * 详情
     *
     * @return View
     * @throws RepositoryException
     */
    public function detail(): View
    {
        $id   = input('id/d', 0);
        $item = PayMonthLog::findById($id);

        $orderNum                = 0;
        $orderScoreNum           = 0;
        $totalPrice              = 0;
        $totalScore              = 0;
        $item['total_price']     = Math::fen2Yuan($totalPrice);
        $item['order_num']       = $orderNum;
        $item['order_score_num'] = $orderScoreNum;
        $item['order_newest']    = [];

        $this->data['item'] = $item;

        return $this->view();
    }

    /**
     * 编辑
     *
     * @return Redirect|Json|View
     * @throws Exception
     */
    public function edit()
    {
        $id = input('id/d', 0);
        if (!$info = PayMonthLog::findById($id)) {
            if ($this->request->isPost()) {
                return $this->json(4000, '记录不存在');
            } else {
                return $this->error('记录不存在');
            }
        }

        $all = PayMonthLog::where('account_id', $info['account_id'])->where('time', $info['time'])
            ->fieldRaw('sum(amount) as amount,sum(base_amount) as base_amount,sum(overtime_amount) as overtime_amount')
            ->find();

        $info['amount']          = $all['amount'];
        $info['base_amount']     = $all['base_amount'];
        $info['overtime_amount'] = $all['overtime_amount'];

        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'status' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            try {
                PayMonthLog::where('account_id', $info['account_id'])->where('time', $info['time'])->save(['status' => $item['status']]);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item']    = $info;
        $this->data['account'] = Account::findById($info['account_id']);

        return $this->view();
    }

    /**
     * 单个字段编辑
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function modify(): Json
    {
        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'field' => 'require',
                'value' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!$info = PayMonthLog::findById($item['id'])) {
                return $this->json(4001, '记录不存在');
            }

            $update = [$item['field'] => $item['value']];

            try {
                $info->save($update);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }
        return $this->json(4000, '非法请求');
    }

    /**
     * 列表
     *
     * @return View|Json
     * @throws Exception
     */
    public function index()
    {
        $accountId = input('user_id/d', 0);
        $worksite  = Worksite::list();
        $position  = Position::list();
        if ($this->request->isPost()) {
            $page         = input('page/d', 1);
            $size         = input('size/d', 20);
            $searchParams = input('searchParams');
            $search       = [];
            if ($searchParams) {
                foreach ($searchParams as $key => $param) {
                    if ($param || $param == '0') {
                        switch ($key) {
                            case 'keyword':
                                $search[] = ['a.nickname|a.real_name|a.mobile', 'like', '%'.$param.'%'];
                                break;
                            default:
                                $search[] = ['pml.'.$key, '=', $param];
                        }
                    }
                }
            }

            if ($accountId > 0) {
                $search[] = ['pml.account_id', '=', $accountId];
            }

            try {
                $total = 0;
                $res   = [
                    'total'   => $total,
                    'current' => $page ?: 1,
                    'size'    => $size ?: 20,
                    'info'    => [],
                    'list'    => [],
                ];

                $query = PayMonthLog::alias('pml')
                    ->leftJoin('account a', 'a.id = pml.account_id')
                    ->where($search);
                // 汇总信息
                $info = $query->fieldRaw('sum(pml.amount) as amount, sum(pml.base_amount) as base_amount,
            sum(pml.overtime_amount) as overtime_amount')->find();
                // 已发放工资
                $doneAmount = $query->where('pml.status', 1)->fieldRaw('sum(pml.amount) as amount')->find();

                $res['info'] = [
                    'amount'          => $info['amount'] ?? 0,
                    'base_amount'     => $info['base_amount'] ?? 0,
                    'overtime_amount' => $info['overtime_amount'] ?? 0,
                    'done_amount'     => $doneAmount['amount'] ?? 0,
                    'not_amount'      => Math::sub($info['amount'] ?? 0, $doneAmount['amount'] ?? 0),
                ];

                $query = PayMonthLog::alias('pml')
                    ->leftJoin('account a', 'a.id = pml.account_id')
                    ->leftJoin('worksite w', 'w.id = a.worksite_id')
                    ->leftJoin('position p', 'p.id = a.position')
                    ->where($search)
                    ->group('account_id,time');

                $total        = $query->count();
                $res['total'] = $total;

                if ($total > 0) {
                    $res['list'] = $query->field('pml.id,sum(pml.amount) as amount,sum(pml.base_amount) as base_amount,pml.status,pml.year,pml.month,
                    sum(pml.overtime_amount) as overtime_amount,pml.account_id,pml.time,a.nickname,a.real_name,a.mobile,w.name as worksite_name,
                    p.name as position_text')
                        ->page($page, $size)->order('pml.id', 'desc')->select();
                    $res['list']->each(function ($item) {
                        $item->status_text = $item->status == 1 ? '已发放' : '待发放';
                        $item->time_text   = $item->year.'年'.$item->month.'月';
                    });
                }

                return $this->json(0, 'success', $res);
            } catch (RepositoryException $e) {
                return $this->json(4001, $e->getMessage());
            } catch (Exception $e) {
                return $this->json(5001, '获取工资列表失败'.$e->getMessage());
            }
        }

        $this->data['userId']       = $accountId;
        $this->data['worksiteList'] = $worksite;
        $this->data['positionList'] = $position;
        return $this->view();
    }

    /**
     * 获取客户列表
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException|Exception
     */
    public function getAccountList(): Json
    {
        if ($this->request->isPost()) {
            $keyword = input('keyword/s', '');
            $page    = input('page/d', 1);
            $size    = input('size/d', 10);
            $id      = input('id', '');

            $relationIds = explode(',', $id);//已选记录

            $where = [];
            if (!empty($keyword)) {
                $where[] = ['nickname|real_name|mobile', 'like', '%'.$keyword.'%'];
            }

            $res = AccountModel::findList($where, ['id', 'nickname', 'real_name', 'mobile'], $page, $size);

            if ($res['total'] > 0 && $relationIds) {
                $res['list'] = $res['list']->toArray();
                foreach ($res['list'] as &$item) {
                    $item['name_text'] = sprintf("昵称:%s;真实姓名:%s,手机号:%s", $item['nickname'], $item['real_name'], $item['mobile']);
                    if (count($relationIds) > 0 && in_array($item['id'], $relationIds)) {
                        $item['selected'] = true;
                    }
                }
            }

            return $this->json(0, '操作成功', $res);
        }
        return $this->json(4001, '非法请求');
    }

    /**
     * 每月工资列表 与index的区别是  index按人与月份的汇总 几个工地的工资都进行了汇总
     * list则是按每个工地单独统计
     *
     * @return View|Json
     * @throws Exception
     */
    public function list()
    {
        $accountId = input('user_id/d', 0);
        $time      = input('time/d', 0);
        $worksite  = Worksite::list();
        $position  = Position::list();
        if ($this->request->isPost()) {
            $page         = input('page/d', 1);
            $size         = input('size/d', 20);
            $searchParams = input('searchParams');
            $search       = [];
            if ($searchParams) {
                foreach ($searchParams as $key => $param) {
                    if ($param || $param == '0') {
                        switch ($key) {
                            case 'keyword':
                                $search[] = ['a.nickname|a.real_name|a.mobile', 'like', '%'.$param.'%'];
                                break;
                            default:
                                $search[] = ['pml.'.$key, '=', $param];
                        }
                    }
                }
            }

            if ($accountId > 0) {
                $search[] = ['pml.account_id', '=', $accountId];
            }

            if ($time > 0) {
                $search[] = ['pml.time', '=', $time];
            }

            try {
                $total = 0;
                $res   = [
                    'total'   => $total,
                    'current' => $page ?: 1,
                    'size'    => $size ?: 20,
                    'info'    => [],
                    'list'    => [],
                ];

                $query = PayMonthLog::alias('pml')
                    ->leftJoin('account a', 'a.id = pml.account_id')
                    ->where($search);
                // 汇总信息
                $info = $query->fieldRaw('sum(pml.amount) as amount, sum(pml.base_amount) as base_amount,
            sum(pml.overtime_amount) as overtime_amount')->find();
                // 已发放工资
                $doneAmount = $query->where('pml.status', 1)->fieldRaw('sum(pml.amount) as amount')->find();

                $res['info'] = [
                    'amount'          => $info['amount'] ?? 0,
                    'base_amount'     => $info['base_amount'] ?? 0,
                    'overtime_amount' => $info['overtime_amount'] ?? 0,
                    'done_amount'     => $doneAmount['amount'] ?? 0,
                    'not_amount'      => Math::sub($info['amount'] ?? 0, $doneAmount['amount'] ?? 0),
                ];

                $query = PayMonthLog::alias('pml')
                    ->leftJoin('account a', 'a.id = pml.account_id')
                    ->leftJoin('worksite w', 'w.id = pml.worksite_id')//注意此处需要使用pml表
                    ->leftJoin('position p', 'p.id = a.position')
                    ->where($search);

                $total        = $query->count();
                $res['total'] = $total;

                if ($total > 0) {
                    $res['list'] = $query->field('pml.*,a.nickname,a.real_name,a.mobile,w.name as worksite_name,
                    p.name as position_text')
                        ->page($page, $size)->order('pml.id', 'desc')->select();
                    $res['list']->each(function ($item) {
                        $item->status_text = $item->status == 1 ? '已发放' : '待发放';
                        $item->time_text   = $item->year.'年'.$item->month.'月';
                    });
                }

                return $this->json(0, 'success', $res);
            } catch (RepositoryException $e) {
                return $this->json(4001, $e->getMessage());
            } catch (Exception $e) {
                return $this->json(5001, '获取工资列表2失败'.$e->getMessage());
            }
        }

        $this->data['userId']       = $accountId;
        $this->data['time']         = $time;
        $this->data['worksiteList'] = $worksite;
        $this->data['positionList'] = $position;
        return $this->view();
    }
}