<?php

namespace app\admin\controller\marketing;

use app\admin\service\sys_manage\DeptService;
use app\admin\validate\sys_manage\DeptValidate;
use app\controller\Curd;
use app\model\Device;
use app\model\SysDept;
use app\model\SysUser;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class DeptPremisesController extends Curd
{
    public function __construct()
    {
        $this->model = new SysDept();
        $this->validate = true;
        $this->validateClass = new DeptValidate();
    }

    public function selectList(Request $request)
    {
        $category = $request->get('category','');
        $type = $request->get('type','');

        if ($category == 'dishes'){
            $category = '餐厅';
        }else{
            $category = '营业场所';
        }

        $deptId = '';
        if ($type == 'user'){
            $user = SysUser::where('user_id',JwtToken::getCurrentId())->first();
            if (!empty($user->join_user_dept_id)){
                $restaurant = SysDept::where('dept_id',$user->join_user_dept_id)->where('dept_category','餐厅')->first();
                
                if (empty($restaurant)){
                    $premise = SysDept::where('dept_id',$user->join_user_dept_id)->where('dept_category','营业场所')->first();
                    if (!empty($premise)){
                        $restaurant = SysDept::where('dept_super_id',$premise->dept_id)->where('dept_category','餐厅')->first();
                    }
                }
                if (!empty($restaurant)){
                    $deptId = $restaurant->dept_id;
                }
            }
        }

        $premisses = SysDept::where('dept_category', $category);
        if (!empty($deptId)){
            $premisses = $premisses->where('dept_id',$deptId);
        }
        $premisses = $premisses->select('dept_id as key', 'dept_name as label','dept_address as address','dept_position as position','dept_extend_json')
            ->get()
            ->toArray();

        foreach($premisses as &$item){
            $item['work_time'] = [];
            if($item['dept_extend_json']){
                $extendJson = json_decode($item['dept_extend_json'],true);
                if(isset($extendJson['times'])){
                    $extendJsonTime = explode('~',$extendJson['times']);
                    $item['work_time'] = [
                        date('Y-m-d H:i:s',strtotime(date('Y-m-d ').$extendJsonTime[0])),
                        date('Y-m-d H:i:s',strtotime(date('Y-m-d ').$extendJsonTime[1])),
                    ];
                }
            }
        }

        return json_success('', $premisses);
    }

    /**
     * @Desc 营业场所列表
     * @Author Gorden
     * @Date 2024/3/7 13:17
     *
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $request->get('field', 'dept_addtimes');
        $where['dept_super_id'] = 0;
        $where['dept_category'] = '营业场所';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->dept_extend_json)) {
                $extendJson = json_decode($item->dept_extend_json, true);
                $item->dept_week = $extendJson['week'] ?? [];
                $item->dept_work = [];
                $deptWork = [];
                if (!empty($extendJson['times'])) {
                    $times = explode('~', $extendJson['times']);
                    $deptWork[] = date('Y-m-d H:i:s', strtotime(date('Y-m-d ') . $times[0]));
                    $deptWork[] = date('Y-m-d H:i:s', strtotime(date('Y-m-d ') . $times[1]));
                }

                $item->dept_work = $deptWork;
                if (!empty($extendJson['printer'])) {
                    $devices = Device::whereIn('device_id', $extendJson['printer'])
                        ->select('device_id', 'device_name', 'device_config_json')
                        ->get()
                        ->toArray();
                    $deviceName = [];
                    foreach ($devices as $printer) {
                        if (empty($printer['device_config_json'])) {
                            continue;
                        }
                        $deviceConfigJson = json_decode($printer['device_config_json'], true);
                        $deviceName[] = (isset($deviceConfigJson['dept_name']) ? $deviceConfigJson['dept_name'] . '-' : '') . $printer['device_name'];
                    }
                    $item->printer = implode(', ', $deviceName);
                }
            }
        }

        return $items;
    }

    public function afterInfoQuery($item)
    {
        if (!empty($item->dept_city)) {
            $item->dept_city = explode(',', $item->dept_city);
        }

        return $item;
    }

    /**
     * @Desc 添加营业场所
     * @Author Gorden
     * @Date 2024/3/7 11:48
     *
     * @param Request $request
     * @return Response
     */
    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add_premises')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }
        // 验证编号是否存在
        if (!empty($request->post('dept_code')) && SysDept::checkExist('营业场所', 'dept_code', $request->post('dept_code'))) {
            return json_fail('编号重复，请重新输入');
        }

        Db::beginTransaction();
        try {
            $data = $this->insertInput($request);
            $data['dept_super_id'] = 0;
            $deptId = $this->doInsert($data);
            if (!$deptId) {
                throw new BusinessException('创建营业场所失败');
            }
            // 更新部门path
            $path = '/0/' . $deptId . '/';
            if (!SysDept::where('dept_id', $deptId)->update(['dept_super_path' => $path])) {
                throw new BusinessException('创建营业场所失败');
            }
            Db::commit();
        } catch (BusinessException $customException) {
            Db::rollBack();
            return json_fail($customException->getMessage());
        } catch (\Exception $exception) {
            dump($exception->getMessage());
            Db::rollBack();
            return json_fail('创建营业场所失败');
        }
        return json_success('success');
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());

        $work = $request->post('dept_work', []);
        $dateWeek = $request->post('dept_week', []);
        $printerIds = $request->post('printer_id', []);
        $extendJson = [];
        if (isset($work[0]) && isset($work[1])) {
            $start = date('H:i', strtotime($work[0]));
            $end = date('H:i', strtotime($work[1]));
            $extendJson['times'] = $start . '~' . $end;
        } elseif (!isset($work[0]) && isset($extendJson['times'])) {
            unset($extendJson['times']);
        }

        if ($dateWeek) {
            $newDates = [];
            foreach ($dateWeek as $date) {
                $key = self::$week[$date];
                $newDates[$key] = $date;
            }
            ksort($newDates);

            $currentDate = current($newDates);
            $lastDate = end($newDates);

            $weekStr = '';
            if (self::$week[$lastDate] - self::$week[$currentDate] + 1 > count($newDates)) {
                $weekStr = implode(',', $newDates);
            } else if (self::$week[$lastDate] - self::$week[$currentDate] + 1 == count($newDates)) {
                $weekStr = $currentDate . '至' . $lastDate;
            }

            $extendJson['weeks'] = $weekStr;
            $extendJson['week'] = $dateWeek;
        }
        $extendJson['printer'] = $printerIds;

        $data['dept_extend_json'] = json_encode($extendJson);

        return $data;
    }

    /**
     * @Desc 更新
     * @Author Gorden
     * @Date 2024/3/7 13:14
     *
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('update_premises')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            [$id, $data] = $this->updateInput($request);

            $this->doUpdate($id, $data);
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            return json_fail('数据更新失败');
        }

        return json_success('success');
    }

    /**
     * 更新前置方法
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $work = $request->post('dept_work', []);
        $dateWeek = $request->post('dept_week', []);
        $printerIds = $request->post('printer_id', []);
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        $extendJson = [];
        if (!empty($model->dept_extend_json)) {
            $extendJson = json_decode($model->dept_extend_json, true);
        }
        if (isset($work[0]) && isset($work[1])) {
            $start = date('H:i', strtotime($work[0]));
            $end = date('H:i', strtotime($work[1]));
            $extendJson['times'] = $start . '~' . $end;
        } elseif (!isset($work[0]) && isset($extendJson['times'])) {
            unset($extendJson['times']);
        }

        if ($dateWeek) {
            $newDates = [];
            foreach ($dateWeek as $date) {
                $key = self::$week[$date];
                $newDates[$key] = $date;
            }
            ksort($newDates);

            $currentDate = current($newDates);
            $lastDate = end($newDates);

            $weekStr = '';
            if (self::$week[$lastDate] - self::$week[$currentDate] + 1 > count($newDates)) {
                $weekStr = implode(',', $newDates);
            } else if (self::$week[$lastDate] - self::$week[$currentDate] + 1 == count($newDates)) {
                $weekStr = $currentDate . '至' . $lastDate;
            }

            $extendJson['weeks'] = $weekStr;
            $extendJson['week'] = $dateWeek;
        }
        $extendJson['printer'] = $printerIds;

        $data['dept_extend_json'] = json_encode($extendJson);

        unset($data[$primary_key]);
        return [$id, $data];
    }

    public static $week = [
        '周一' => 1,
        '周二' => 2,
        '周三' => 3,
        '周四' => 4,
        '周五' => 5,
        '周六' => 6,
        '周日' => 7,
    ];
}