<?php

namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\model\Appointment as appointmentModel;
use think\Db;
use time\DateHelper;

class Appointment extends Permissions
{
    private function getModel()
    {
        return new appointmentModel();
    }


    public function publish()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        $this->assign('pid', $pid);

        $post = $this->request->post();
        $post['provider_id'] = $pid;

        if ($this->request->isPost()) {
            //验证
            $validate = new \think\Validate([
                ['provider_id', 'require|number'],
            ]);

            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
        }

        $model = $this->getModel();
        $appointment = $model->where('provider_id', $pid)->find();

        if ($appointment) {
            //修改
            if ($this->request->isPost()) {
                $weeks = $post['weeks']??[];
                $weeks = array_keys($weeks);
                $post['weeks'] = implode(',', $weeks);

                $post['morning_time_periods'] = json_encode($post['morning_time_periods']);
                $post['afternoon_time_periods'] = json_encode($post['afternoon_time_periods']);

                if (false == $appointment->allowField(true)->save($post)) {
                    $this->error('修改失败');
                }
                $this->success('修改成功', 'index', ['pid' => $pid]);
            } else {
                return $this->fetch();
            }

        } else {
            //新增
            if ($this->request->isPost()) {

                $weeks = $post['weeks']??[];
                $weeks = array_keys($weeks);
                $post['weeks'] = implode(',', $weeks);

                $post['morning_time_periods'] = json_encode($post['morning_time_periods']);
                $post['afternoon_time_periods'] = json_encode($post['afternoon_time_periods']);

                if (false == $model->allowField(true)->save($post)) {
                    $this->error('添加失败');
                }
                $this->success('添加成功', 'index', ['pid' => $pid]);
            } else {
                return $this->fetch();
            }
        }
    }

}