<?php
namespace app\admin\controller;
use think\facade\View;
use think\facade\Lang;
use think\facade\Db;
/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Flearegion extends AdminControl
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'admin/lang/'.config('lang.default_lang').'/region.lang.php');
        Lang::load(base_path() . 'admin/lang/'.config('lang.default_lang').'/flea.lang.php');
    }
    /**
     * 地区列表
     *
     * @param
     * @return
     */
    public function flea_region() {
        /**
         * 实例化模型
         */
        $fleaarea_model = model('fleaarea');
        /**
         * 增加 修改 地区信息
         */
        if (request()->isPost()) {
            /**
             * 是否生成缓存的标识
             */
            $new_cache = true;
            /**
             * 新增地区
             */
            $new_area_name_array = input('post.new_area_name/a');#获取数组
            if (is_array($new_area_name_array) && !empty($new_area_name_array)) {
                foreach ($new_area_name_array as $k => $v) {
                    if (!empty($v)) {
                        $insert_array = array();
                        $insert_array['fleaarea_name'] = $v;
                        $insert_array['fleaarea_parent_id'] = input('post.fleaarea_parent_id');
                        $insert_array['fleaarea_sort'] = intval($new_area_name_array[$k]);
                        $insert_array['fleaarea_deep'] = input('post.child_area_deep');
                        $fleaarea_model->addFleaarea($insert_array);
                        $new_cache = true;
                    }
                }
            }
            /**
             * 修改地区
             */
            $area_name_array = input('post.area_name/a');#获取数组
            if (is_array($area_name_array) && !empty($area_name_array)) {
                foreach ($area_name_array as $k => $v) {
                    if (!empty($v)) {
                        $insert_array = array();
                        $insert_array['fleaarea_name'] = $v;
                        $insert_array['fleaarea_sort'] = intval($area_name_array[$k]);
                        $fleaarea_model->editFleaarea(array('fleaarea_id'=>$k),$insert_array);
                        $new_cache = true;
                    }
                }
            }
            /**
             * 删除地区
             */
            $hidden_del_id = input('post.hidden_del_id');
            if (!empty($hidden_del_id)) {
                $hidden_del_id = trim($hidden_del_id, '|');
                $del_id = explode('|', $hidden_del_id);
                $fleaarea_model->delFleaarea($del_id, input('post.child_area_deep'));
                $new_cache = true;
            }

            /**
             * 更新缓存
             */
            if ($new_cache === true) {
                \fleacache::getCache('flea_area', array('deep' => input('post.child_area_deep'), 'new' => '1'));
            }

            $this->success(lang('region_index_modify_succ'));
        } else {
            /**
             * 导航地区内容
             */
            /**
             * 一级
             */
            $province_list = \fleacache::getCache('flea_area', array('deep' => '1'));
            $child_area_deep = 1;
            /**
             * 二级
             */
            $city_list = array();
            $district_list = array();
            if (input('param.province')) {
                $cache_data = \fleacache::getCache('flea_area', array('deep' => '2'));
                if (is_array($cache_data)) {

                    foreach ($cache_data as $k => $v) {
                        if ($v['fleaarea_parent_id'] == intval(input('param.province'))) {
                            $city_list[] = $v;
                        }
                    }
                }
                unset($cache_data);
                $child_area_deep = 2;
                /**
                 * 三级
                 */
                if (input('param.city')) {
                    $cache_data = \fleacache::getCache('flea_area', array('deep' => '3'));
                    if (is_array($cache_data)) {

                        foreach ($cache_data as $k => $v) {
                            if ($v['fleaarea_parent_id'] == intval(input('param.city'))) {
                                $district_list[] = $v;
                            }
                        }
                    }
                    unset($cache_data);
                    $child_area_deep = 3;
                    /**
                     * 四级
                     */
                    if (input('param.district')) {
                        $child_area_deep = 4;
                    }
                }
            }
            /**
             * 地区列表
             */
            $condition = array();
            $fleaarea_parent_id = input('param.fleaarea_parent_id') ? input('param.fleaarea_parent_id') : '0';
            $condition[] = array('fleaarea_parent_id','=',$fleaarea_parent_id);
            $area_list = $fleaarea_model->getFleaareaList($condition);
            View::assign('province', input('param.province') ? input('param.province') : '');
            View::assign('city', input('param.city'));
            View::assign('district', input('param.district'));

            View::assign('province_list', $province_list);
            View::assign('city_list', $city_list);
            View::assign('district_list', $district_list);
            View::assign('fleaarea_parent_id', input('param.fleaarea_parent_id') ? input('param.fleaarea_parent_id') : '0');
            View::assign('area_list', $area_list);
            View::assign('child_area_deep', $child_area_deep);
            $this->setAdminCurItem('index');
            return View::fetch('index');
        }
    }


    /**
     * 导入默认地区
     *
     * @param
     * @return
     */
    public function flea_import_default_area() {
        $file = PUBLIC_PATH.'/examples/flea_area.sql';
        if (!is_file($file)){
            ds_json_encode(10001, lang('region_import_csv_null'));
        }

        $handle = @fopen($file, "r");
        $tmp_sql = '';
        if ($handle) {

            Db::query("TRUNCATE TABLE `".config('database.connections.mysql.prefix')."fleaarea`");
            while (!feof($handle)) {

                $buffer = fgets($handle);
                if (trim($buffer) != ''){
                    $tmp_sql .= $buffer;
                    if (substr(rtrim($buffer),-1) == ';'){
                        if (preg_match('/^(INSERT)\s+(INTO)\s+/i', ltrim($tmp_sql)) && substr(rtrim($buffer),-2) == ');'){
                            //标准的SQL语句，将被执行
                        }else{
                            //不能组成标准的SQL语句，继续向下一行取内容，直到组成合法的SQL为止
                            continue;
                        }
                        if (!empty($tmp_sql)){
                            if (strtoupper(CHARSET) == 'GBK'){
                                $tmp_sql = iconv('UTF-8',strtoupper(CHARSET),$tmp_sql);
                            }
                            $tmp_sql = str_replace("`#__fleaarea`","`".config('database.connections.mysql.prefix')."fleaarea`",$tmp_sql);
                            Db::query($tmp_sql);
                            $tmp_sql = '';
                        }
                    }
                }
            }
            @fclose($handle);
            /**
             * 重新生成缓存
             */
            for ($i=1;$i<=4;$i++){
                $tmp = 'flea_area_parent_id_'.$i;
                if (isset($$tmp) && intval($$tmp) >= 0){
                    \fleacache::getCache('flea_area',array('deep'=>intval($i),'new'=>'1'));
                }
            }
            ds_json_encode(10000, lang('region_import_succ'));
        }else {
            ds_json_encode(10001, lang('region_import_csv_null'));
        }
    }
    
    
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index', 'text' => lang('ds_manage'), 'url' => (string)url('Flearegion/flea_region')
            ),
            array(
                'name' => 'import', 'text' => lang('flea_region_import'), 'url' => "javascript:dsLayerConfirm('".(string)url('Flearegion/flea_import_default_area')."','".lang('import_confirm')."')"
            ),
        );
        return $menu_array;
    }
}