<?php
/*
  $Id: modules_shipping_advanced_details_panel.php $
  TomatoCart Open Source Shopping Cart Solutions
  http://www.tomatocart.com

  Copyright (c) 2009 Wuxi Elootec Technology Co., Ltd

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License v2 (1991)
  as published by the Free Software Foundation.
*/

?>

Toc.modules_shipping.ChinaShippingAreaConfigPanel = function(config) {
  config = config || {};

  config.region = 'east';
  config.border = false;
  config.split = true;
  config.style = 'padding: 6px 10px 6px 10px';
  config.minWidth = 420;
  config.maxWidth = 440;
  config.width = 430;
    
  config.url = Toc.CONF.CONN_URL; 
  config.baseParams = {
    module: 'modules_shipping',
    action: 'save_shipping_area'
  };
  
  config.items = this.buildForm(config.code);
  
  config.buttonAlign = 'right';
  config.buttons = [
    {
      text:TocLanguage.btnSave,
      handler: function(){
        this.submitForm(config);
      },
      scope:this
    }, 
    {
      text: TocLanguage.btnClose,
      handler: function() {
        config.parent.ownerCt.close();
      },
      scope:this
    }
  ];
  
  Toc.modules_shipping.ChinaShippingAreaConfigPanel.superclass.constructor.call(this, config);
};

Ext.extend(Toc.modules_shipping.ChinaShippingAreaConfigPanel, Ext.form.FormPanel, {
  buildForm: function(code) {
    var dsCountries = new Ext.data.SimpleStore({
      fields: ['region_id', 'region_name', 'region_type'],
      data: 
        [['1','中国', '0']]
    });
    
    this.cboCountries = new Ext.form.ComboBox({
      fieldLabel: '国家',
      xtype: 'combo', 
      width: 110,
      store: dsCountries, 
      mode: 'local',
      displayField: 'region_name', 
      valueField: 'region_id', 
      triggerAction: 'all', 
      editable: false,
      forceSelection: true,
      value: '1'
    });
    
    var dsProvinces = new Ext.data.Store({
      url:Toc.CONF.CONN_URL,
      baseParams: {
        module: 'modules_shipping',
        action: 'get_china_provinces',
        region_id: '1',
        code: code
      },
      reader: new Ext.data.JsonReader({
        fields: ['region_id', 'region_name', 'region_type'],
        root: Toc.CONF.JSON_READER_ROOT
      }),
      autoLoad: true,
      listeners: {
        load: function() {this.cboProvinces.setValue('0');this.provinceIndex = 0;},
        scope: this
      }
    });
    
    this.cboProvinces = new Ext.form.ComboBox({
      fieldLabel: '省份',
      width: 110,
      xtype: 'combo',
      store: dsProvinces,
      displayField: 'region_name', 
      valueField: 'region_id', 
      triggerAction: 'all', 
      editable: false,
      mode: 'local',
      forceSelection: true,
      listeners: {
        select: this.onProvinceSelect,
        scope: this
      } 
    });
    
    var dsCities = new Ext.data.Store({
      url:Toc.CONF.CONN_URL,
      baseParams: {
        module: 'modules_shipping',
        action: 'get_china_cities'
      },
      reader: new Ext.data.JsonReader({
        fields: ['region_id', 'region_name', 'region_type'],
        root: Toc.CONF.JSON_READER_ROOT
      }),
      autoLoad: false,
      listeners: {
        load: function() {
          this.cboCities.setValue('0');
        },
        scope: this
      }
    });
    
    this.cboCities = new Ext.form.ComboBox({
      fieldLabel: '城市',
      disabled: true,
      width: 110,
      xtype: 'combo',
      store: dsCities,
      displayField: 'region_name', 
      valueField: 'region_id', 
      triggerAction: 'all', 
      editable: false,
      mode: 'local',
      forceSelection: true,      
      listeners: {
        select: this.onCitySelect,
        scope: this
      } 
    });
    
    dsDistricts = new Ext.data.Store({
      url:Toc.CONF.CONN_URL,
      baseParams: {
        module: 'modules_shipping',
        action: 'get_china_districts'
      },
      reader: new Ext.data.JsonReader({
        fields: ['region_id', 'region_name', 'region_type'],
        root: Toc.CONF.JSON_READER_ROOT
      }),
      autoLoad: false,
      listeners: {
        load: function() {
          if (this.cboDistricts.getStore().getCount() == 0) {
            this.cboDistricts.disable();
          } else {
            this.cboDistricts.enable();
            this.cboDistricts.setValue('0');
          }
        },
        scope: this
      }
    });
    
    this.cboDistricts = new Ext.form.ComboBox({
      fieldLabel: '区/县',
      disabled: true,
      width: 110,
      xtype: 'combo',
      store: dsDistricts,
      displayField: 'region_name', 
      valueField: 'region_id', 
      triggerAction: 'all', 
      editable: false,
      mode: 'local',
      forceSelection: true,      
      listeners: {
        select: this.onDistrictSelect,
        scope: this
      } 
    });
    
    this.pnlZonePicker = new Ext.Panel({
      layout: 'form',
      border: false,
      items: [
        this.cboCountries,
        this.cboProvinces,
        this.cboCities,
        this.cboDistricts
      ],
      buttons:[{
        text: TocLanguage.btnAdd,
        iconCls: 'add',
        handler: this.onAddArea,
        scope: this
      }]
    });
    
    this.data = [];
    this.dsZones = new Ext.data.SimpleStore({
      fields: ['region_id', 'region_name', 'region_type'],
      data : this.data
    });

    this.grdZones = new Ext.grid.GridPanel({
      store: this.dsZones,
      height: 140,
      border: true,
      cm: new Ext.grid.ColumnModel([
        {
          header: '所辖地区',
          dataIndex: 'region_name'
        },
        rowActions = new Ext.ux.grid.RowActions({
          actions:[
            {iconCls: 'icon-delete-record', qtip: TocLanguage.tipDelete}
          ]
        })
      ]),
      plugins: rowActions
    });
    rowActions.on('action', this.onRowAction, this);
    
    this.fsZones = new Ext.form.FieldSet({
      title: '地区设置',
      autoHeight: true,
      layout: 'column',
      labelWidth: 80,
      items: [
        {
          columnWidth: .59,
          border: false,
          items:[
            this.pnlZonePicker
          ]
        },
        {
          columnWidth: .40,
          layout: 'form',
          border: false,
          items: [
            this.grdZones
          ]
        }
      ]
    });
    
    this.fsGeneral = new Ext.form.FieldSet({
      title: '参数设置', 
      autoHeight: true,
      labelWidth: 160
    });
    
    return [this.fsGeneral, this.fsZones];
  },
  
  requestForm: function(code, id) {
    this.fsGeneral.removeAll();
    
    Ext.Ajax.request({
      url: Toc.CONF.CONN_URL,
      params: {
        module: 'modules_shipping',
        action: 'get_area_parameters',
        code: code,
        shipping_area_id: id
      },
      callback: function(options, success, response) {
        fields = Ext.decode(response.responseText);
          
        Ext.each(fields, function(field, i) {
          this.fsGeneral.add(
            new Ext.Panel({
              layout: 'form',
              border: false,
              labelWidth: 200,
              items: [
                {xtype: 'textfield', fieldLabel: field.title, name: field.name, value: field.value, allowBlank: false, anchor: '95%'}
              ]
            })
          );
        },this);
            
        this.doLayout();
      },
      scope: this
    });
  },
  
  iniDetail: function(record) {
    if (record == null) {
      this.shippingAreaId = 0;
    } else {
      this.shippingAreaId = record.get('shipping_area_id');
      this.data = [];
      
      var regions = record.get('region_data').split(';');
      for (var i = 0; i < regions.length; i++) {
        var region = regions[i].split('-');
        this.data.push([region[0], region[1], region[2]]);
      }
    }
    
    this.requestForm(this.code, this.shippingAreaId);
    this.dsZones.loadData(this.data);
    
    this.resetAreaComboBox(2);
  },
  
  reset: function() {
    this.requestForm(this.code);
    
    this.data = [];
    this.shippingAreaId = null,
    this.dsZones.loadData(this.data);
    this.resetAreaComboBox(2);
  },
  
  resetAreaComboBox: function(type) {
    switch (type) {
      case 2:
      this.cboCities.clearValue();
      this.cboCities.disable();
      this.cboDistricts.clearValue();
      this.cboDistricts.disable();

      this.provinceIndex = 0;
      this.cityIndex = 0;
      this.districtIndex = 0;
      break;
      case 1:
      this.cboDistricts.clearValue();
      this.cboDistricts.disable();
      
      this.cityIndex = 0;
      this.districtIndex = 0;
      break;
    }
  },

  onProvinceSelect: function(combo, record, index) {
    this.provinceIndex = index;
    
    if (record.get('region_id') > 0) {
      this.resetAreaComboBox(1);
      
      this.cboCities.enable();
      this.cboCities.getStore().baseParams['region_id'] = record.get('region_id');
      this.cboCities.getStore().reload();
    } else {
      this.resetAreaComboBox(2);
    }
  },
  
  onCitySelect: function(combo, record, index) {
    this.cityIndex = index;
    
    if (record.get('region_id') > 0) {
      this.cboDistricts.getStore().baseParams['region_id'] = record.get('region_id');
      this.cboDistricts.getStore().reload();
    } else {
      this.resetAreaComboBox(1);
    }
  },
  
  onDistrictSelect: function(combo, record, index) {
    this.districtIndex = index;
  },

  onAddArea: function() {
    if (this.districtIndex > 0) {
      this.addRegion(this.cboDistricts, this.districtIndex);
    } else {
      if (this.cityIndex > 0) {
        this.addRegion(this.cboCities, this.cityIndex);
      } else {
        if (this.provinceIndex > 0) {
          this.addRegion(this.cboProvinces, this.provinceIndex);
        } else {
          this.addRegion(this.cboCountries, 0);
        }
      }
    }
  },
  
  addRegion: function(combo, index) {
    regionId = combo.getStore().getAt(index).get('region_id');
    regionName = combo.getStore().getAt(index).get('region_name');
    regionType = combo.getStore().getAt(index).get('region_type');
    
    //check region
    for (var i = 0; i < this.data.length; i++) {
      if (this.data[i][0] == regionId) {
        alert('您所选择的区域已在列表中！');
        return;
      } 
    }
    
    this.data.push([regionId, regionName, regionType]);
    this.dsZones.loadData(this.data);
  },
  
  onRowAction: function(grid, record, action, row, col) {
    switch(action) {
      case 'icon-delete-record':
        this.data.splice(row, 1);
        this.dsZones.loadData(this.data);
        break;
    }
  },
  
  submitForm : function(config) {
    if (this.data.length == 0) {
      alert('请至少为改区域选择一个地区！');
    } else {
      var regions = [];
      
      for (var i = 0; i < this.data.length; i++) {
        regions[i] = this.data[i][0] + ',' + this.data[i][2];
      }
      
      this.form.baseParams['code'] = config.code;
      this.form.baseParams['region'] = regions.join(';');
      this.form.baseParams['shipping_area_id'] = this.shippingAreaId;
      
      this.form.submit({
        waitMsg: TocLanguage.formSubmitWaitMsg,
        success: function(form, action) {
          this.owner.app.showNotification( {title: TocLanguage.msgSuccessTitle, html: action.result.feedback} );
          this.parent.fireEvent('saveSuccess');
        },    
        failure: function(form, action) {
          Ext.MessageBox.alert(TocLanguage.msgErrTitle, action.result.feedback);
        },  
        scope: this
      });
    }
  }
});