<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 信息栏目
 */
namespace app\allwin\model;
use think\Model;
use category\Tree;

class AllwinInfoCate extends Model{

    protected $pk = 'id';

    //开通好店订单
    public function tpl(){
        return $this->hasOne('AllwinInfoTpl','id','tpl_id');
    }

    //添加或编辑
    public static function edit($param){
        $data['title']     = $param['title'];
        $data['name']      = $param['name'];
        $data['sort']      = $param['sort'];
        $data['picture']   = $param['picture'];
        $data['tpl_id']    = $param['tpl_id'];
        $data['update_time']  = time();
        if(isset($param['id'])){
            return self::update($data,['id'=>(int)$param['id']]);
        }else{
            $data['create_time']       = time();
            $data['member_miniapp_id'] = $param['member_miniapp_id'];
            return self::insert($data);
        }
    } 

   /**
     * 获取当前栏目的模板
     * @param type $parent_id
     * @return type
     */
    public static function cateTpl(int $id){
        $rel = self::where(['id' => $id])->field('tpl_id')->find();
        $data = ['is_shop' => 0,'button_name' => '下单','users' => [],'fields' =>[]];
        if(isset($rel->tpl)){
            $fields = json_decode($rel->tpl->fields,true);
            foreach ($fields as $key => $value) {
                if($value['types'] == 'selector'){
                    $fields[$key]['value'] = '';
                }else{
                    $fields[$key]['value'] = $value['values'];
                }
            } 
            $users = json_decode($rel->tpl->users,true);
            foreach ($users as $key => $value) {
                if($value['types'] == 'selector'){
                    $users[$key]['value'] = '';
                }else{
                    $users[$key]['value'] = $value['values'];
                }
            } 
            $data['fields']      = $fields;
            $data['users']       = $users;
            $data['is_shop']     = $rel->tpl->is_shop;
            $data['button_name'] = $rel->tpl->button_name;
        }
        return $data;
    }
}