<?php

declare(strict_types=1);

namespace app\common\model\account;

use Exception;
use mb\helper\Collection;
use think\facade\Db;
use think\facade\Log;

/**
 * Class department
 * @package app\common\model\account
 */
class Department
{
    /**
     * pid 父级ID
     * title 部门名称
     *
     * @param $departmentInfo
     * @return int|string
     */
    public static function add($departmentInfo)
    {
        $newRow = Collection::keyStyle($departmentInfo, Collection::NAME_STYLE_C);
        $newRow = Collection::elements([
            'pid',
            'title',
            'first'
        ], $newRow);
        $exists = self::fetch(['title' => $newRow['title']]);
        try {
            if (empty($exists)) {
                return Db::table('account_departments')
                    ->insertGetId($newRow);
            } else {
                return error(-21, $newRow['title'] . '已存在');
            }
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return false;
    }


    /**
     * filters.pid
     * filters.title
     * filters.tree 是否返回树状结构
     * @param array $filters
     * @param int $pIndex
     * @param int $pSize
     * @param int $total
     * @return array
     */
    public static function search(array $filters, int $pIndex = 0, int $pSize = 10, &$total = 0)
    {
        $where = [];
        if (isset($filters['pid'])) {
            $where[] = ['pid', '=', $filters['pid']];
        }
        if (!empty($filters['title'])) {
            $where[] = ['title', 'like', "%{$filters['title']}%"];
        }
        try {
            $total = Db::table('account_departments')
                ->where($where)
                ->count();

            $query = Db::table('account_departments')
                ->where($where);
            if (!empty($pIndex)) {
                $query->page($pIndex, $pSize);
            }
            if (!empty($filters['order'])) {
                $query->order($filters['order']);
            }
            $dataSet = $query->select()->toArray();
            if (!empty($dataSet)) {
                $returnSet = array_map(function ($row) {
                    return Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
                }, $dataSet);
                if (!empty($filters['tree'])) {
                    return self::getTree($returnSet);
                }
                return $returnSet;
            }
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return [];
    }

    /**
     * @param $filters
     * @return array
     */
    public static function fetch($filters)
    {
        $where = self::parseFilters($filters);
        try {
            $userInfo = Db::table('account_departments')
                ->where($where)
                ->find();
            if (!empty($userInfo)) {
                return Collection::keyStyle($userInfo, Collection::NAME_STYLE_JAVA);
            }
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return [];
    }

    /**
     * @param $filters
     * @param array $newState
     * @return bool
     */
    public static function update($filters, array $newState)
    {
        $where = self::parseFilters($filters);
        try {
            $offect = Db::table('account_departments')
                ->where($where)
                ->update($newState);
            if ($offect === 1) {
                return true;
            }
            return false;
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return false;
    }


    /**
     * @param $filters
     * @return int
     */
    public static function remove($filters)
    {
        $where = self::parseFilters($filters);
        try {
            return Db::table('account_departments')
                ->where($where)
                ->delete();
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return false;
    }
    /**
     * id
     * pid 父ID
     * title 名称
     * @param $departmentFilters
     * @return array
     */
    public static function parseFilters($departmentFilters)
    {
        $filters = [];
        if (is_array($departmentFilters)) {
            if (isset($departmentFilters['id'])) {
                $filters[] = ['id', '=', $departmentFilters['id']];
            }
            if (isset($departmentFilters['ids'])) {
                $filters[] = ['id', 'in', $departmentFilters['ids']];
            }
            if (!empty($departmentFilters['pid'])) {
                $filters[] = ['pid', '=', $departmentFilters['pid']];
            }
            if (!empty($departmentFilters['title'])) {
                $filters[] = ['title', '=', $departmentFilters['title']];
            }
            if (empty($filters)) {
                throw error(-11, '缺少参数,必须指定id,pid,title');
            }
        } else {
            $filters[] = ['id', '=', intval($departmentFilters)];
        }
        return $filters;
    }

    /**
     * @param $list
     * @param int $pid
     * @return array
     */
    public static function getTree($list, $pid = 0)
    {
        $tree = [];
        if (!empty($list)) {
            $newList = [];
            foreach ($list as $k => $v) {
                $newList[$v['id']] = $v;
                $newList[$v['id']]['value'] = $v['id'];
            }
            foreach ($newList as $value ) {
                if ($pid == $value['pid']) {
                    $tree[] = &$newList[$value['id']];
                } elseif (isset($newList[$value['pid']]))
                {
                    $newList[$value['pid']]['children'][] = &$newList[$value['id']];
                }
            }
        }
        return $tree;
    }
}