<?php

namespace app\admin\controller\customer;

use app\admin\validate\customer\IndexValidate;
use app\controller\Curd;
use app\model\Customer;
use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberCert;
use app\model\MemberInfo;
use app\model\SysRole;
use app\model\SysSerial;
use app\model\SysUser;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class IndexController extends Curd
{
    public function __construct()
    {
        $this->model = new Customer();
        $this->validate = true;
        $this->validateClass = new IndexValidate();
    }

    public function selectList(Request $request)
    {
        $keywords = $request->get('keywords');
        if (!$keywords) {
            return json_fail("查询错误");
        }

        $res = Db::table('customer')
            ->select('id','name','mobile')
            ->where(function ($query) use ($keywords) {
                $query->where('name', 'like', '%' . $keywords . '%')
                    ->orWhere("mobile", 'like', '%' . $keywords . '%');
            })->get();
        $data = [];
        foreach ($res as $item) {
            $data[] = [
                'key' => $item->id,
                'value' => $item->name,
            ];
        }

        return json_success('', $data);
    }

    public function select(Request $request): Response
    {
        $userId = JwtToken::getCurrentId();
        $user = SysUser::find($userId);
        if (empty($user->join_user_role_id)) {
            return json_fail("请先关联角色");
        }
        $type = $request->get('type','');
        $role = SysRole::find($user->join_user_role_id);
        $selfAndChildIds = SysRole::where('role_path', 'like', $role->role_path . "%")
            ->where('role_id', '<>', $role->role_id)
            ->pluck('role_id');
        $userIds = SysUser::whereIn('join_user_role_id', $selfAndChildIds)->pluck('user_id')->toArray();
        array_unshift($userIds, $userId);

        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'created_at';
        $where['creator'] = ['in', $userIds];
        if(!empty($type)){
            $where['created_at'] = [
                strtotime(date('Y-m-d').' 00:00:00'),
                strtotime(date('Y-m-d').' 23:59:59')
            ];
        }
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with('user');
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item) {
            $item->city = explode(',', $item->city);
        }

        return $items;
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['creator'] = JwtToken::getCurrentId();
        if (!empty($data['birth'])) {
            $data['birth'] = date('Y-m-d', strtotime($data['birth']));
        }

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        if (!empty($data['birth'])) {
            $data['birth'] = date('Y-m-d', strtotime($data['birth']));
        }
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }

    public function conversion(Request $request)
    {
        $id = $request->post('id');
        $customer = Customer::where('id', $id)->first();
        if (!$customer) {
            return json_fail('客户不存在');
        }
        Db::beginTransaction();

        try {
            $memberId = "ME" . date("ymdHi") . random_string(4, 'up');
            $member = [
                'member_id' => $memberId,
                'member_is_owner' => 'N',
                'member_classify' => 'MEMBER',
                'member_status' => 'ACTIVED',
                'member_mobile' => $customer->mobile ?? '',
                // 'member_from' => 'CUSTOMER',
                'member_addtimes' => time()
            ];
            $member['member_extend_json'] = json_encode(['come_from'=>'CUSTOMER']);
            
            // 归属门店
            $user = SysUser::where('user_id',$customer->creator)->first();
            $belong = [
                'user_id'=>$customer->creator,
                'premises' => $user->join_user_dept_id ?? '',
            ];
            $member['member_extend_json'] = json_encode(['belong'=>$belong]);

            Member::insert($member);

            // cert
            $cert = [
                'join_cert_member_id' => $memberId,
                'member_cert_name' => $customer->name,
                'member_cert_nbr' => $customer->card_id ?? '',
                'member_cert_birth' => $customer->birth ?? '',
                'member_cert_gender' => $customer->gender ?? '',
                'member_cert_province' => $customer->city ?? '',
                'member_cert_addr' => $customer->address ?? ''
            ];

            MemberCert::insert($cert);

            // info
            $info = [
                'join_info_member_id' => $memberId,
                'member_info_nickname' => $customer->name
            ];
            MemberInfo::insert($info);

            $customer->status = '正式用户';
            $customer->save();

            // 账户表
            $accountData = [
                'join_account_member_id' => $memberId,
                'member_account_classify' => 'POINTS',
                'member_account_status' => 'ACTIVED',
                'member_account_category' => 'NORMAL',
                'member_account_nbr' => $memberId . '-POINTS',
                'member_account_name' => '积分账户',
                'member_account_addtimes' => time()
            ];
            // 积分账户
            MemberAccount::insert($accountData);
            $accountData['member_account_classify'] = 'CASH';
            $accountData['member_account_nbr'] = $memberId . '-CASH';
            $accountData['member_account_name'] = '余额账户';
            // 现金/余额账户
            MemberAccount::insert($accountData);


            Db::commit();

            return json_success("转正式用户成功");
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollBack();
            return json_fail('转正式用户失败');
        }
    }
}