<?php

namespace app\adminapi\controller\v1\company;

use app\adminapi\controller\AuthController;
use crmeb\services\{UtilService as Util};
use app\models\section\SectionModel;
use app\models\company\CompanyModel;
use app\models\company\ExampleModel;
use app\models\company\DesignerModel;
use think\Request;

class Company extends AuthController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $where = Util::getMore([
            ['title', ''],
            ['sid', ''],
            ['page', 1],
            ['limit', 10]
        ], $this->request);
        $list = CompanyModel::systemPage($where);
        return $this->success($list);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = Util::postMore([
            ['id', 0],
            ['sid', ''],
            ['title', ''],
            ['logo', ''],
            ['intro', ''],
            ['contact', ''],
            ['phone', ''],
            ['project', ''],
            ['slider_image', ''],
            ['sort', 0],
            ['status', 1],
            ['example', []],
            ['designer', []],
        ]);
        if (!$data['title']) return $this->fail('缺少参数');
        $example = $data['example'];
        $designer = $data['designer'];
        unset($data['example'], $data['designer']);
        if ($data['id']) {
            $id = $data['id'];
            unset($data['id']);
            $res = CompanyModel::edit($data, $id, 'id');
            ExampleModel::saveExample($example, $id);
            DesignerModel::saveDesigner($designer, $id);
            return $this->success('修改成功!', ['id' => $id]);
        } else {
            $data['add_time'] = time();
            $res = CompanyModel::create($data);
            foreach($example as $key => $value){
                $example[$key]['cid'] = (int)($res['id']);
            }
            foreach($designer as $key => $value){
                $designer[$key]['cid'] = (int)($res['id']);
            }
            ExampleModel::saveExample($example, $res['id']);
            DesignerModel::saveDesigner($designer, $res['id']);
            return $this->success('添加成功!', ['id' => $res->id]);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        if ($id) {
            $info = ArticleModel::where('n.id', $id)->alias('n')->field('n.*,c.content')->join('ArticleContent c', 'c.nid=n.id', 'left')->find();
            if (!$info) return $this->fail('数据不存在!');
            $info['cid'] = intval($info['cid']);
        }
        $info = CompanyModel::getOne($id);
        return $this->success(compact('info'));
    }

}