<template><page-meta :root-font-size="fontSize+'px'"></page-meta>
    <seller-base :show="false">
    <view class="div container transport-form seller-transport-form">
        <view class="div common-header-wrap">
            <view :style="'height:'+navHeight+'px'"></view>
            <view class="common-header-holder"></view>
            <view class="common-header-fixed">
            <title-header />
            <uni-nav-bar :title="getTitle" class="common-header" left-icon="back" @clickLeft="goBack">
            </uni-nav-bar>
        </view>
        </view>
        <view class="div main-content">
        <flex-line class="field-line" :show-border="true"><text class="span field-name">区域名称</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_info.transport_title" /></view></flex-line>
        <flex-line :show-border="true"><text class="span line-name">限制配送</text><view class="div" slot="right"><switch @change="switchChange" :checked="!!transport_info.transport_is_limited"></switch></view></flex-line>
        <flex-line :show-border="true">
        <text class="span">运费类型</text>
        <view class="div" slot="right">
			<radio-group @change="radioChange">
			  <label v-for="(item, index) in transport_type_options" :key="index">
				<radio :value="item.value" :checked="transport_info.transport_type==item.value" />
				<text>{{item.label}}</text>
			  </label>
			</radio-group>
        </view>
        </flex-line>
        <view class="div" @click="showPopup('parentVisible')">
            <flex-line :is-link="true" :show-border="true"><text class="span line-name">设置城市运费</text></flex-line>
        </view>

        <view class="div pt-10 pb-10"><view class="div common-btn ds-button-large"  @click="submit">保存</view></view>
        </view>

        <uni-popup background-color="#fff" ref="parentVisible" type="right">
        <view :style="'width:'+screenWidth+'px'" class="div my-popup common-popup-wrapper">
            <view class="div common-header-wrap">
                <view :style="'height:'+navHeight+'px'"></view>
                <view class="common-header-holder"></view>
                <view class="common-header-fixed">
                <title-header />
                <uni-nav-bar title="设置城市运费" class="common-header" left-icon="back" @clickLeft="hidePopup('parentVisible')">
                    <view class="div common-btn btn" slot="right" @click="addTransportExtend">新增</view>
                </uni-nav-bar>
            </view>
            </view>
            <view class="div common-popup-content" v-if="transport_extend">
              <scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" scroll-y="true">
                <view class="div" v-if="!transport_info.transport_is_limited">
                    <view class="div">
                        <flex-line class="label-title" :show-border="true"><text class="span line-name">默认运费</text></flex-line>
                    </view>
                    <view class="block-wrapper">
                    <flex-line class="field-line" :show-border="true"><text class="span field-name">{{transport_info.transport_type=='1'?'首重（kg）':'首件（件）'}}</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_extend[default_transportext_id].transportext_snum" /></view></flex-line>
                    <flex-line class="field-line" :show-border="true"><text class="span field-name">{{transport_info.transport_type=='1'?'首重费用':'首件费用'}}</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_extend[default_transportext_id].transportext_sprice" /></view></flex-line>
                    <flex-line class="field-line" :show-border="true"><text class="span field-name">{{transport_info.transport_type=='1'?'续重（kg）':'续件（件）'}}</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_extend[default_transportext_id].transportext_xnum" /></view></flex-line>
                    <flex-line class="field-line" :show-border="true"><text class="span field-name">{{transport_info.transport_type=='1'?'续重费用':'续件费用'}}</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_extend[default_transportext_id].transportext_xprice" /></view></flex-line>
                    </view>
                </view>
                <view class="div" v-for="(item,key) in transport_extend" :key="key">

                    <view class="div" v-if="item && !item.transportext_is_default">
                      <view class="block-wrapper">
                        <view class="div" @click="showCity(key)">
                            <flex-line :is-link="true" :show-border="true"><text class="span line-name">运送到</text><text class="span" slot="right">{{transport_extend[key].transportext_area_name}}</text></flex-line>
                        </view>
                        
                        <flex-line class="field-line" :show-border="true"><text class="span field-name">{{transport_info.transport_type=='1'?'首重（kg）':'首件（件）'}}</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_extend[key].transportext_snum" /></view></flex-line>
                        <flex-line class="field-line" :show-border="true"><text class="span field-name">{{transport_info.transport_type=='1'?'首重费用':'首件费用'}}</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_extend[key].transportext_sprice" /></view></flex-line>
                        <flex-line class="field-line" :show-border="true"><text class="span field-name">{{transport_info.transport_type=='1'?'续重（kg）':'续件（件）'}}</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_extend[key].transportext_xnum" /></view></flex-line>
                        <flex-line class="field-line" :show-border="true"><text class="span field-name">{{transport_info.transport_type=='1'?'续重费用':'续件费用'}}</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="transport_extend[key].transportext_xprice" /></view></flex-line>
                        <view class="div common-btn ds-button-large" @click="delTransportExtend(key)">删除</view>
                        </view>
                    </view>
                
                </view>
				</scroll-view>
            </view>
        </view>
        </uni-popup>
        <uni-popup background-color="#fff" ref="cityVisible" type="right">
        <view :style="'width:'+screenWidth+'px'" class="div my-popup common-popup-wrapper">
            <view class="div common-header-wrap">
                <view :style="'height:'+navHeight+'px'"></view>
                <view class="common-header-holder"></view>
                <view class="common-header-fixed">
                <title-header />
                <uni-nav-bar title="选择城市" class="common-header" left-icon="back" @clickLeft="hidePopup('cityVisible');getCityName()">
                </uni-nav-bar>
            </view>
            </view>
            <view class="div common-popup-content" v-if="area_list">
              <scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" scroll-y="true">
                <view class="div city-1" v-for="(region,region_name) in area_list.region" :key="region_name">
                    <checkbox-group @change="changeCityStatu(0,region_name,$event)" class="div list-checkbox-wrapper">
                    <view class="div list-checkbox">
                    <checkbox
                            class="checkbox"
                            :id="region_name"
                            value="1"
                            :checked="regionChecked[region_name]"
                    />
                    <label class="label" :class="{'checked':regionChecked[region_name]}" :for="region_name"><text class="span iconfont">&#xe69b;</text></label>

                    </view>
                    <text class="span checkbox-text">{{region_name}}</text>
                    </checkbox-group>
                    <view class="div city-2" v-for="city_id_1 in region" :key="city_id_1">
                        <checkbox-group @change="changeCityStatu(1,city_id_1,$event)" class="div list-checkbox-wrapper">
                        <view class="div list-checkbox">
                        <checkbox
                                class="checkbox"
                                :id="city_id_1+''"
                                :checked="provinceChecked[city_id_1]"
                                :value="city_id_1+''"
                        />
                        <label class="label" :class="{'checked':provinceChecked[city_id_1]}" :for="city_id_1+''"><text class="span iconfont">&#xe69b;</text></label>

                        </view>
                        <text class="span checkbox-text">{{area_list.name[city_id_1]}}</text>
                        </checkbox-group>
                        <view class="div city-3"  v-for="city_id_2 in area_list.children[city_id_1]" :key="city_id_2">
                            <checkbox-group @change="changeCityStatu(2,city_id_2,$event)" class="div list-checkbox-wrapper">
                            <view class="div list-checkbox">
                            <checkbox
                                    class="checkbox"
                                    :id="city_id_2+''"
                                    :checked="cityChecked[city_id_2]"
                                    :value="city_id_2+''"
                            />
                            <label class="label" :class="{'checked':cityChecked[city_id_2]}" :for="city_id_2+''"><text class="span iconfont">&#xe69b;</text></label>

                            </view>
                            <text class="span checkbox-text">{{area_list.name[city_id_2]}}</text>
                            </checkbox-group>
                        </view>
                    </view>

                </view>
                </scroll-view>
            </view>
        </view>
        </uni-popup>

    </view>
</seller-base>
</template>

<script>
import {getFontSize} from '@/util/common'
import TitleHeader from '../../TitleHeader'
import SellerBase from '../SellerBase'

import { getAreaList } from '../../../api/area'
import { editTransport, saveTransport } from '../../../api/sellerTransport'
import flexLine from '../../flexLine'
export default {
  components:{
  TitleHeader,
  SellerBase,
  flexLine,
  },
  props: {
    ifComponent: {
      type: Boolean,
      default: false
    },
    query: {
      type: Object,
      default: function () {
        return { action: 'add', transport_id: 0 }
      }
    }
  },
  computed:{
    fontSize(){
      return getFontSize()
    },
    isAddMode () {
      let mode = this.ifComponent ? this.query.action : this.action
      // add: 添加地址，edit: 编辑地址
      if (mode === 'add') {
        return true
      } else {
        return false
      }
    },
    getTitle () {
      if (this.isAddMode) {
        return '新增售卖区域'
      } else {
        return '修改售卖区域'
      }
    }

  },
  data(){
    return {
        navHeight: 0,
        screenWidth:0,
		action:'',
        transport_type_options: [
            {
                label: '按数量',
                value: '0'
            },
            {
                label: '按重量',
                value: '1'
            }
        ],
      area_list: {},
      transport_info: {
        transport_is_limited: false
      },
      default_transportext_id: 0,
      transport_extend: [{
        transport_id: this.ifComponent ? this.query.transport_id : this.$route.query.transport_id,
        transport_title: '',
        transportext_area_id: '',
        transportext_area_name: '',
        transportext_id: 0,
        transportext_is_default: 1,
        transportext_snum: '',
        transportext_sprice: '',
        transportext_top_area_id: '',
        transportext_xnum: '',
        transportext_xprice: ''
      }],
      regionChecked: {},
      cityChecked: {},
      provinceChecked: {},
      index: 0,
      transport_id: this.ifComponent ? this.query.transport_id : this.$route.query.transport_id
    }
  },
  onLoad: function (option) {
	this.action = option.action
	this.transport_extend.transport_id = this.ifComponent ? this.query.transport_id : option.transport_id
	this.transport_id = this.ifComponent ? this.query.transport_id : option.transport_id

  },
  created(){
    getAreaList().then(res => {
        this.area_list = res.result.area_list
      }).catch(error => {
        uni.showToast({icon:'none',title: error.message})
      })
      this.initTransport()
  },
  watch: {
    query: function (val) {
      this.transport_id = val.transport_id
      this.initTransport()
    }
  },
  mounted(){
    // #ifdef  MP-WEIXIN
    this.navHeight = uni.getMenuButtonBoundingClientRect().height
    // #endif
    this.screenWidth=uni.getSystemInfoSync().screenWidth
  },
  methods: {
      showPopup(id){
        this.$refs[id].open()
      },
      hidePopup(id){
        this.$refs[id].close()
      },
	switchChange(e){
	  this.transport_info.transport_is_limited=e.detail.value
	},
	radioChange(e){
	  this.transport_info.transport_type=e.detail.value
	},
    initTransport () {
      if (!this.isAddMode) {
        editTransport(this.transport_id).then(res => {
          var transport_info = res.result.transport_info
          transport_info.transport_is_limited = !!transport_info.transport_is_limited
          this.transport_info = transport_info
          this.transport_extend = res.result.transport_extend
          for (var i in this.transport_extend) {
            if (this.transport_extend[i].transportext_is_default) {
              this.default_transportext_id = i
            }
          }
        }).catch(function (error) {
          uni.showToast({icon:'none',title: error.message})
        })
      }
    },
    goBack () {
      if (this.ifComponent) {
        this.$emit('closeTransortForm')
      } else {
        uni.navigateBack({delta:1})
      }
    },
    submit () {
      saveTransport(this.transport_info, this.transport_extend).then(res => {
        if (this.ifComponent) {
          this.$emit('saveTransport')
        } else {
          uni.navigateTo({url:'/pages/seller/transport/transportList'})
        }
      }).catch(error => {
        uni.showToast({icon:'none',title: error.message})
      })
    },
    delTransportExtend (key) {
      delete (this.transport_extend[key])
      this.$forceUpdate()
    },
    addTransportExtend () {
      this.transport_extend.push({
        transport_id: this.transport_id,
        transport_title: '',
        transportext_area_id: '',
        transportext_area_name: '',
        transportext_id: 0,
        transportext_is_default: 0,
        transportext_snum: '',
        transportext_sprice: '',
        transportext_top_area_id: '',
        transportext_xnum: '',
        transportext_xprice: ''
      })
    },
    changeCityStatu (layer_id, id, event) {
    var value=event.detail.value
      switch (layer_id) {
        case 0:
          for (var index in this.area_list.region[id]) {
            var city_id_1 = this.area_list.region[id][index]
            if (!value.length) {
              delete this.provinceChecked[city_id_1]
            } else {
              this.provinceChecked[city_id_1] = true
            }
            for (var index2 in this.area_list.children[city_id_1]) {
              var city_id_2 = this.area_list.children[city_id_1][index2]
              if (!value.length) {
                delete this.cityChecked[city_id_2]
              } else {
                this.cityChecked[city_id_2] = true
              }
            }
          }

          break
        case 1:
          if (!value.length) {
            delete this.provinceChecked[id]
            for (var region_name in this.area_list.region) {
              for (var index in this.area_list.region[region_name]) {
                if (this.area_list.region[region_name][index] == id) {
                  delete this.regionChecked[region_name]
                  break
                }
              }
            }
          }else{
            this.provinceChecked[id]=true
          }
          for (var index2 in this.area_list.children[id]) {
            var city_id_2 = this.area_list.children[id][index2]
            if (!value.length) {
              delete this.cityChecked[city_id_2]
            } else {
              this.cityChecked[city_id_2] = true
            }
          }

          if (!Object.keys(this.provinceChecked).length) {
            this.regionChecked = {}
          }
          break
        case 2:
          if (!value.length) {
            delete this.cityChecked[id]
            for (var region_name in this.area_list.region) {
              for (var index in this.area_list.region[region_name]) {
                if (this.area_list.region[region_name][index] == this.area_list.parent[id]) {
                  delete this.regionChecked[region_name]
                  break
                }
              }
            }
          }else{
            this.cityChecked[id]=true
          }
          var flag = false
          for (var index in this.provinceChecked[this.area_list.parent[id]]) {
            if (this.cityChecked[this.provinceChecked[this.area_list.parent[id]][index]]) {
              flag = true
              break
            }
          }
          if (!flag) {
            delete this.provinceChecked[this.area_list.parent[id]]
          }

          if (!Object.keys(this.provinceChecked).length) {
            this.regionChecked = {}
          }
          break
      }
      this.$forceUpdate()
    },
    getCityName () {
      var city_name = []
      for (var i in this.provinceChecked) {
        city_name.push(this.area_list.name[i])
      }
      for (var j in this.cityChecked) {
        if (!this.provinceChecked[this.area_list.parent[j]]) {
          city_name.push(this.area_list.name[j])
        }
      }
      var city_id_1 = Object.keys(this.provinceChecked)
      var city_id_2 = Object.keys(this.cityChecked)
      var _city_id_2 = city_id_2
      var _city_id_1 = city_id_1
      if (city_id_1 && city_id_1.length) {
        _city_id_2 = city_id_2.concat(city_id_1)
      }
      for (var i in city_id_2) {
        if (_city_id_1.indexOf(this.area_list.parent[city_id_2[i]]) == -1) {
          _city_id_1.push(this.area_list.parent[city_id_2[i]])
        }
      }
      this.transport_extend[this.index].transportext_area_name = city_name.join(',')
      this.transport_extend[this.index].transportext_area_id = ',' + _city_id_2.join(',') + ','
      this.transport_extend[this.index].transportext_top_area_id = ',' + city_id_1.join(',') + ','
    },
    showCity (index) {
      this.regionChecked = {}
      this.provinceChecked = {}
      var provinceChecked = {}
      this.cityChecked = {}
      var cityChecked = {}
	  this.showPopup('cityVisible')
      this.index = index
      var str
      str = this.transport_extend[index].transportext_top_area_id
      var city_id_1 = str ? str.substr(1, str.length - 2).split(',') : []
      str = this.transport_extend[index].transportext_area_id
      var city_id_2 = str ? str.substr(1, str.length - 2).split(',') : []

      var provinceLength = {}
      for (var i in city_id_1) {
        provinceChecked[city_id_1[i]] = true
        provinceLength[city_id_1[i]] = this.area_list.children[city_id_1[i]].length
      }
      for (var i in city_id_2) {
        if (!provinceChecked[city_id_2[i]]) {
          cityChecked[city_id_2[i]] = true
          provinceLength[this.area_list.parent[city_id_2[i]]]--
          if (provinceLength[this.area_list.parent[city_id_2[i]]] <= 0) {
            delete provinceLength[this.area_list.parent[city_id_2[i]]]
          }
        }
      }
      for (var i in provinceLength) {
        delete provinceChecked[i]
      }
      for (var i in this.area_list.region) {
        var l = 0
        for (var j in this.area_list.region[i]) {
          if (provinceChecked[this.area_list.region[i][j]]) {
            l++
          }
        }
        if (l == this.area_list.region[i].length) {
          this.regionChecked[i] = true
        }
      }
      this.provinceChecked = provinceChecked
      this.cityChecked = cityChecked
    }
  }
}
</script>
<style lang="scss">
    .seller-transport-form{
        .mint-radiolist {
            display: flex;
            .mint-cell {
                flex: 1;
                .mint-radio-input:checked + .mint-radio-core {
                    background-color: $primaryColor !important;
                    border-color: $primaryColor !important;
                }
                &:after{display: none}
            }
        }
        .mint-cell-value{
            max-width: 80%;
        }
    }
</style>
<style lang="scss" scoped>
  .block-wrapper{padding:0 $pageSpace}
.common-header{
        .btn{background: #000;color: #fff;box-shadow: 0px 2px 4px #d2d2d2;}
    }
.main-content{background: #fff;padding:0 $pageSpace}

    .right-arrow{transform: rotate(-90deg);color:#ddd;font-size:$fontSize;display: inline-block;}
    .input-wrap{position: relative;
        .i{position: absolute;right:0;top:0;line-height: 2.4rem;display: block;width:2rem;text-align: center;font-size:$h1}
    }
    .city-2{padding:0 1rem}
    .city-3{padding:0 1rem}
    .list-checkbox-wrapper{display: flex;border-bottom: 1px solid #eee;padding:.5rem}
    .checkbox-text{flex: 1;font-size:$h2;}
    .list-checkbox {
        width: 1rem;
        height: 1rem;
        flex-basis: 1rem;
        flex-shrink: 0;
        position: relative;
        margin-right:0.25rem;
        .label {
      padding:0;
            position: absolute;
            left:0;
            top: 0;
            width: 1rem;
            height: 1rem;
            display: inline-block;
            border-radius:50%;
            border:1px solid #333;
            box-sizing:border-box;
            .iconfont{display: none;line-height: 1rem;text-align: center;}
      &.checked{
      	border-color:$primaryColor;
      	background-color:$primaryColor;
      	.iconfont{display: block;color:#fff}
      }
		}
		.checkbox {
            position: relative;
            width: 1rem;
            margin: 0;
            opacity: 0;
            background-color: #fff;

        }

    }
    .label-title{padding:0 $pageSpace;background: #eee}

</style>
