<?php

namespace app\home\controller;


use think\Lang;

class Sellertransport extends BaseSeller
{
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'home/lang/zh-cn/Sellertransport.lang.php');
        $type = input('param.type');
        if ($type != '' && $type != 'select') {
            $type = 'select';
        }
    }

    /**
     * 售卖区域列表
     *
     */
    public function index()
    {
        $model_transport = Model('transport');
        $list = $model_transport->getTransportList(array('store_id' => session('store_id')), 4);
        $extend = '';
        if (!empty($list) && is_array($list)) {
            $transport = array();
            foreach ($list as $v) {
                if (!array_key_exists($v['id'], $transport)) {
                    $transport[$v['id']] = $v['title'];
                }
            }
            $extend = $model_transport->getExtendList(array('transport_id' => array('in', array_keys($transport))));
            //halt($extend);
            // 整理
            if (!empty($extend)) {
                $tmp_extend = array();
                foreach ($extend as $val) {
                    $tmp_extend[$val['transport_id']]['data'][] = $val;
                    $tmp_extend[$val['transport_id']]['price'] = $val['sprice'];
                }
                $extend = $tmp_extend;
            }
        }
        //dump($list);
        //dump($extend);exit;
        /**
         * 页面输出
         */
        $this->assign('list', $list);
        $this->assign('extend', $extend);
        $this->assign('show_page', $model_transport->page_info->render());
        $this->setSellerCurMenu('sellertransport');
        $this->setSellerCurItem('index');
        return $this->fetch($this->template_dir . 'index');
    }

    /**
     * 新增售卖区域
     *
     */
    public function add()
    {
        $areas = Model('area')->getAreas();
        $this->assign('areas', $areas);
        $this->setSellerCurMenu('sellertransport');
        $this->setSellerCurItem('index');
        return $this->fetch($this->template_dir . 'add');
    }

    public function edit()
    {
        $id = intval($_GET['id']);
        $model_transport = Model('transport');
        $transport = $model_transport->getTransportInfo(array('id' => $id));
        $extend = $model_transport->getExtendInfo(array('transport_id' => $id));
        $this->assign('transport', $transport);
        $this->assign('extend', $extend);

        $areas = Model('area')->getAreas();

        $this->assign('areas', $areas);

        $this->setSellerCurItem('index');
        $this->setSellerCurMenu('sellertransport');
        return $this->fetch($this->template_dir . 'add');
    }

    public function delete()
    {
        $id = intval(input('param.id'));
        $model_transport = Model('transport');
        $transport = $model_transport->getTransportInfo(array('id' => $id));
        if ($transport['store_id'] != session('store_id')) {
            $this->error(lang('transport_op_fail'));
        }
        //查看是否正在被使用
        if ($model_transport->isUsing($id)) {
            $this->error(lang('transport_op_using'));
        }
        if ($model_transport->delTansport(array('id' => $id))) {
            header('location: ' . $_SERVER['HTTP_REFERER']);
            exit;
        }
        else {
            $this->error(lang('transport_op_fail'));
        }
    }

    public function cloned()
    {
        $id = intval($_GET['id']);
        $model_transport = Model('transport');
        $transport = $model_transport->getTransportInfo(array('id' => $id));
        unset($transport['id']);
        $transport['title'] .= lang('transport_clone_name');
        $transport['update_time'] = time();

        try {
            $model_transport->startTrans();
            $insert = $model_transport->addTransport($transport);
            if ($insert) {
                $extend = $model_transport->getExtendList(array('transport_id' => $id));
                foreach ($extend as $k => $v) {
                    foreach ($v as $key => $value) {
                        $extend[$k]['transport_id'] = $insert;
                    }
                    unset($extend[$k]['id']);
                }
                $insert = $model_transport->addExtend($extend);
            }
            if (!$insert) {
                exception(lang('transport_op_fail'));
            }
            $model_transport->commit();
            header('location: ' . $_SERVER['HTTP_REFERER']);
            exit;
        } catch (Exception $e) {
            $model_transport->rollback();
            $this->error($e->getMessage(), $_SERVER['HTTP_REFERER']);
        }
    }

    public function save()
    {

        if (!request()->isPost()) {
            return false;
        }

        $trans_info = array();
        $trans_info['title'] = $_POST['title'];
        $trans_info['send_tpl_id'] = 1;
        $trans_info['store_id'] = session('store_id');
        $trans_info['update_time'] = TIMESTAMP;

        $model_transport = Model('transport');

        if (is_numeric($_POST['transport_id'])) {
            //编辑时，删除所有附加表信息
            $transport_id = intval($_POST['transport_id']);
            $model_transport->transUpdate($trans_info, array('id' => intval($_POST['transport_id'])));
            $model_transport->delExtend($transport_id);
        }
        else {
            //新增
            $transport_id = $model_transport->addTransport($trans_info);
        }

        $trans_list = array();
        $areas = isset($_POST['areas']['kd']) ? $_POST['areas']['kd'] : '';
        $special = isset($_POST['special']['kd']) ? $_POST['special']['kd'] : '';

        //默认运费
        $default = $_POST['default']['kd'];
        $trans_list[]=array(
            'area_id' =>'',
            'area_name' =>'默认运费',
            'sprice' =>$default['postage'],
            'transport_id'  =>$transport_id,
            'transport_title' =>$_POST['title'],
            'snum'   =>$default['start'],
            'xnum'   =>$default['plus'],
            'xprice'  =>$default['postageplus'],
            'is_default' =>'1',
            'top_area_id' =>''
        );

        if (is_array($special)) {
            foreach ($special as $key => $value) {
                $tmp = array();
                if (empty($areas[$key])) {
                    continue;
                }
                $areas[$key] = explode('|||', $areas[$key]);
                $tmp['area_id'] = ',' . $areas[$key][0] . ',';
                $tmp['area_name'] = $areas[$key][1];
                $tmp['sprice'] = $value['postage'];
                $tmp['transport_id'] = $transport_id;
                $tmp['transport_title'] = $_POST['title'];
                $tmp['snum'] = $value['start'];
                $tmp['xnum'] = $value['plus'];
                $tmp['xprice'] =$value['postageplus'];
                $tmp['is_default'] ='0';
                //计算省份ID
                $province = array();
                $tmp1 = explode(',', $areas[$key][0]);
                if (!empty($tmp1) && is_array($tmp1)) {
                    $city = Model('area')->getCityProvince();
                    foreach ($tmp1 as $t) {
                        $pid = isset($city[$t]) ? $city[$t] : array();
                        if (!in_array($pid, $province) && !empty($pid)) {
                            $province[] = $pid;
                        }
                    }
                }
                if (count($province) > 0) {
                    $tmp['top_area_id'] = ',' . implode(',', $province) . ',';
                }
                else {
                    $tmp['top_area_id'] = '';
                }
                $trans_list[] = $tmp;
            }
        }
//halt($trans_list);
        $result = $model_transport->addExtend($trans_list);
        $type = input('param.type');
        if ($result) {
            $this->redirect('sellertransport/index', ['type' => $type]);
        }
        else {
            $this->error(lang('transport_op_fail'));
        }
    }

    /**
     * 货到付款地区设置
     *
     */
    public function offpay_area()
    {
        if (!checkPlatformStore()) {
            $this->error('本功能仅限平台自营店使用');
        }
        $model_parea = Model('offpayarea');
        //v3-b12
        $model_area = Model('area');
        $store_id = session('store_id');

        if (request()->isPost()) {
            if (!preg_match('/^[\d,]+$/', $_POST['county'])) {
                $_POST['county'] = '';
            }
            //内置自营店ID
            $area_info = $model_parea->getAreaInfo(array('store_id' => $store_id));
            $data = array();
            $county = trim($_POST['county'], ',');
            //v3-b12
            $county_array = explode(',', $county);
            $all_array = array();

            if (!empty($_POST['province']) && is_array($_POST['province'])) {
                foreach ($_POST['province'] as $v) {
                    $all_array[$v] = $v;
                }
            }

            if (!empty($_POST['city']) && is_array($_POST['city'])) {
                foreach ($_POST['city'] as $v) {
                    $all_array[$v] = $v;
                }
            }

            if (!empty($_POST['city']) && is_array($_POST['city'])) {
                foreach ($_POST['city'] as $v) {
                    $all_array[$v] = $v;
                }
            }

            foreach ($county_array as $pid) {
                $all_array[$pid] = $pid;
                $temp = $model_area->getChildsByPid($pid);
                if (!empty($temp) && is_array($temp)) {
                    foreach ($temp as $v) {
                        $all_array[$v] = $v;
                    }
                }
            }

            $all_array = array_values($all_array);
            $data['area_id'] = serialize($all_array);
            if (!$area_info) {
                $data['store_id'] = $store_id;
                $result = $model_parea->addArea($data);
            }
            else {
                $result = $model_parea->updateArea(array('store_id' => $store_id), $data);
            }
            if ($result) {
                $this->success('保存成功');
            }
            else {
                $this->error('保存失败');
            }
        }

        //取出支持货到付款的县ID及上级市ID
        $parea_info = $model_parea->getAreaInfo(array('store_id' => $store_id));
        if (!empty($parea_info['area_id'])) {
            $parea_ids = @unserialize($parea_info['area_id']);
        }
        if (empty($parea_ids)) {
            $parea_ids = array();
        }

        $this->assign('areaIds', $parea_ids);

        $model_area = Model('area');
        $areas = $model_area->getAreas();
        $this->assign('areas', $areas);

        //取出支持货到付款县ID的上级市ID
        $city_checked_child_array = array();

        foreach ($parea_ids as $i) {
            if (isset($areas['parent'][$i])) {
                $city_checked_child_array[$areas['parent'][$i]][] = $i;
            }
        }
        //halt($city_checked_child_array);
        $this->assign('city_checked_child_array', $city_checked_child_array);

        //市级下面的县是不是全部支持货到付款，如果全部支持，默认选中
        //如果其中部分县支持货到付款，默认不选中但显示一个支付到付县的数量

        //格式 city_id => 下面支持到付的县ID数量
        $city_count_array = array();

        //格式 city_id => 是否选中true/false
        $city_checked_array = array();

        foreach ($city_checked_child_array as $city_id => $c) {
            $city_count_array[$city_id] = count($areas['children'][$city_id]);

            $c = count($c);
            if ($c > 0 && $c == $city_count_array[$city_id]) {
                $city_checked_array[$city_id] = true;
            }
        }

        $this->assign('city_count_array', $city_count_array);
        $this->assign('city_checked_array', $city_checked_array);

        //计算哪些省需要默认选中(即该省下面的所有县都支持到付，即所有市都是选中状态)
        $province_checked_array = array();
        foreach ($areas['children'][0] as $province_id) {
            $b = true;

            if (is_array($areas['children'][$province_id])) {
                foreach ($areas['children'][$province_id] as $city_id) {
                    if (empty($city_checked_array[$city_id])) {
                        $b = false;
                        break;
                    }
                }
            }
            if ($b) {
                $province_checked_array[$province_id] = true;
            }
        }
        $this->assign('province_checked_array', $province_checked_array);

        $area_array_json = json_encode($model_area->getAreaArrayForJson());
        $this->assign('area_array_json', $area_array_json);

        $this->setSellerCurMenu('sellertransport');
        $this->setSellerCurItem('offpay_area');
        return $this->fetch($this->template_dir . 'offpay_area');
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string $menu_type 导航类型
     * @param string $name 当前导航的name
     *
     * @return
     */
    protected function getSellerItemList()
    {
        $menu_array = array(
            array(
                'name' => 'transport', 'text' => lang('ds_member_path_postage'), 'url' => url('sellertransport/index')
            ),
        );
        $menu_array[] = array(
            'name' => 'offpay_area', 'text' => '配送地区', 'url' => url('sellertransport/offpay_area')
        );

        return $menu_array;
    }
}