<?php

namespace app\controller\manager\account;

use app\controller\manager\Base;
use app\exception\RepositoryException;
use app\model\Account;
use app\model\Account as AccountModel;
use app\model\AccountStar;
use app\model\AccountWorksite;
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 Footmarks
 * @package app\controller\manager
 */
class Index extends Base
{
    protected $noNeedLogin = ['getAccountList', 'star'];

    /**
     * 详情
     *
     * @return View
     * @throws RepositoryException
     */
    public function detail(): View
    {
        $id   = input('id/d', 0);
        $item = AccountRepository::getInstance()->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 = AccountRepository::getInstance()->findById($id)) {
            if ($this->request->isPost()) {
                return $this->json(4000, '用户不存在');
            } else {
                return $this->error('用户不存在');
            }
        }

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

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

            try {
                $info->save($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

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

        return $this->view();
    }

    /**
     * 工人信息编辑
     *
     * @return Redirect|Json|View
     * @throws Exception
     */
    public function worker()
    {
        $id = input('id/d', 0);

        if (!$info = Account::find($id)) {
            if ($this->request->isPost()) {
                return $this->json(4000, '用户不存在');
            } else {
                return $this->error('用户不存在');
            }
        }

        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'real_name|姓名'            => 'require',
                'mobile|电话'               => 'require',
                'position|岗位'             => 'require',
                'pay|基本工资'                => 'require',
                'emergency_contact|紧急联系人' => 'require',
                'emergency_phone|紧急联系人电话' => 'require',
                'bank_card_name|银行卡户名'    => 'require',
                'bank_card_number|银行卡号'   => 'require',
                'bank_name|开户行'           => 'require',
                'card_number|身份证'         => 'require',
            ]);

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

            try {
                $info->save($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item']          = $info;
        $this->data['positionList']  = Position::list();
        $this->data['worksite_name'] = Worksite::where('id', $info['worksite_id'])->value('name');

        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 = AccountModel::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()
    {
        $position   = Position::list();
        $role       = input('role');
        $worksiteId = input('worksite_id/d');
        if ($this->request->isPost()) {
            $page         = input('page/d', 1);
            $size         = input('size/d', 20);
            $searchParams = input('searchParams');
            if (input('role')) {
                $searchParams['role'] = input('role');
            }
            if (input('worksite_id')) {
                $searchParams['worksite_id'] = input('worksite_id');
            }
            $search                      = [];
            if ($searchParams) {
                foreach ($searchParams as $key => $param) {
                    if ($param || $param == '0') {
                        switch ($key) {
                            case 'keyword':
                                $search[] = ['nickname|real_name|mobile|emergency_contact|emergency_phone|bank_card_name|bank_card_number|bank_name|card_number|province|city|area|address_now', 'like', '%'.$param.'%'];
                                break;
                            case 'role':
                                switch ($param) {
                                    case -1://全部
                                        break;
                                    case Account::ROLE_NORMAL:
                                    case Account::ROLE_WORKER:
                                    case Account::ROLE_MANAGER:
                                        $search[] = ['role', '=', $param];
                                        break;
                                    case 3://单独构造的代号 员工 表示工人和负责人
                                        $search[] = ['role', 'in', [Account::ROLE_WORKER, Account::ROLE_MANAGER]];
                                        break;
                                }
                                break;
                            default:
                                $search[] = [$key, 'like', '%'.$param.'%'];
                        }
                    }
                }
            }

            if (empty($searchParams['role'])) {
                $search[] = ['role', 'in', [Account::ROLE_WORKER, Account::ROLE_MANAGER]];
            }

            try {
                $items = Account::findList($search, [], $page, $size, function ($q) {
                    return $q->order('id', 'desc');
                });

                $worksite = Worksite::list();
                $items['list']->each(function ($item) use ($position, $worksite) {
                    $genderText          = Account::genderText()[$item->gender] ?? '保密';
                    $item->role_text     = Account::roleText()[$item->role] ?? '其他';
                    $item->position_text = $position[$item->position] ?? '其他';
                    $item->worksite_name = $worksite[$item->position] ?? '';
                    $item->checking_text = Account::checkingText()[$item->checking] ?? '';

                    $item->gender_text = $genderText;
                });
                return $this->json(0, '操作成功', $items);
            } catch (RepositoryException $e) {
                return $this->json(4001, $e->getMessage());
            } catch (Exception $e) {
                return $this->json(5001, '获取用户列表失败'.$e->getMessage());
            }
        }

        $this->data['worksiteId']   = $worksiteId;
        $this->data['role']         = $role;
        $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, '非法请求');
    }

    /**
     * 负责人评定
     *
     * @return Redirect|Json|View
     * @throws Exception
     */
    public function star()
    {
        $id = input('id/d', 0);

        if (!$info = Account::find($id)) {
            if ($this->request->isPost()) {
                return $this->json(4000, '用户不存在');
            } else {
                return $this->error('用户不存在');
            }
        }

        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'star_time|评定时间' => 'require',
                'star|评级'        => 'require|in:1,2,3,4,5',
            ]);

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

            if ($item['star_time'] > date('Y-m')) {
                return $this->json(4002, '不能超过当前月份');
            }

            try {
                $timeArr = explode('-', $item['star_time']);
                $year    = $timeArr[0];
                $month   = (string) $timeArr[1];
                $ym      = $year.$month;

                if (AccountStar::where('type', AccountStar::TYPE_MANAGER)->where('account_id', $id)->where('ym', $ym)->count() > 0) {
                    return $this->json(4002, '该月已评');
                }

                AccountStar::create([
                    'type'        => AccountStar::TYPE_MANAGER,
                    'star'        => $item['star'],
                    'account_id'  => $id,
                    'year'        => $year,
                    'month'       => $month,
                    'ym'          => $ym,
                    'operated_by' => $this->auth['user_id'],
                    'created_at'  => date('Y-m-d H:i:s'),
                ]);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item']          = $info;
        $worksiteId                  = AccountWorksite::where('account_id', $id)->value('worksite_id');
        $this->data['worksite_name'] = Worksite::where('id', $worksiteId)->value('name');

        return $this->view();
    }
}