<template>
  <a-modal
    centered
    class="edit-network-modal"
    :footer="null"
    :maskClosable="false"
    :title="modalTit"
    v-model="isShow"
    @cancle="isShow=false"
    :width="1000">
    <a-form
      id="network-edit-form"
      :form="form"
      ref="form"
      v-bind="formItemLayout"
      @submit="handleSubmit">
      <a-form-item label="网点名称" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-input
          id="network-edit-name"
          :maxLength="30"
          v-decorator="[
            'formData.name',
            { initialValue: formData.name, getValueFromEvent: $filterEmpty, rules: [{ required: true, message: '请输入网点名称' }] }
          ]"
          placeholder="请输入网点名称(最多30个字符)"
          allowClear />
      </a-form-item>
      <a-form-item label="地址" required :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" style="margin: 0;">
        <a-row :gutter="20">
          <!-- 地址 -->
          <a-col span="8">
            <a-form-item>
              <a-select id="network-edit-provinceCode" @change="getCityList" v-decorator="['formData.provinceCode', { initialValue: formData.provinceCode, rules: [{ required: true, message: '请选择省' }] }]" placeholder="请选择省">
                <a-select-option v-for="item in addrProvinceList" :value="item.id" :key="item.id + 'a'">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col span="8">
            <a-form-item prop="cityCode">
              <a-select id="network-edit-cityCode" v-decorator="['formData.cityCode', { initialValue: formData.cityCode, rules: [{ required: true, message: '请选择市' }] }]" @change="getAreaList" placeholder="请选择市">
                <a-select-option v-for="item in addrCityList" :value="item.id" :key="item.id + 'b'">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col span="8">
            <a-form-item prop="districtCode">
              <a-select id="network-edit-districtCode" v-decorator="['formData.districtCode', { initialValue: formData.districtCode, rules: [{ required: true, message: '请选择区' }] }]" @change="areaCharged" placeholder="请选择区/县">
                <a-select-option v-for="item in addrDistrictList" :value="item.id" :key="item.id + 'c'">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item label="详细地址" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-input
          id="network-edit-address"
          :maxLength="30"
          v-decorator="[
            'formData.address',
            { initialValue: formData.address, getValueFromEvent: $filterEmpty, rules: [{ required: true, message: '请输入详细地址' }] }
          ]"
          placeholder="请输入详细地址(最多30个字符)"
          allowClear />
      </a-form-item>
      <a-row :gutter="30">
        <a-col :span="10">
          <a-form-item label="纬度" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
            <a-input
              id="network-edit-lat"
              v-decorator="[
                'formData.lat',
                { initialValue: formData.lat, rules: [
                  { required: true, message: '请输入纬度' },
                  { pattern: /^[\-\+]?([0-8]?\d{1}\.\d{1,8}|90\.0{1,8})$/, message: '请输入正确的纬度,整数部分为0～90，必须输入1到8位小数' }
                ] }
              ]"
              placeholder="请输入纬度"
              allowClear />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="经度" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
            <a-input
              id="network-edit-lng"
              v-decorator="[
                'formData.lng',
                { initialValue: formData.lng, getValueFromEvent: $filterEmpty, rules: [
                  { required: true, message: '请输入经度' },
                  { pattern: /^[\-\+]?(0?\d{1,2}\.\d{1,8}|1[0-7]?\d{1}\.\d{1,8}|180\.0{1,8})$/, message: '请输入正确的经度,整数部分为0～180，必须输入1到8位小数' }
                ] }
              ]"
              placeholder="请输入经度"
              allowClear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a href="https://lbs.qq.com/tool/getpoint/" target="_blank">
            <a-button type="primary" id="network-edit-search-jwd" class="network-edit-search-jwd" size="small">查询坐标</a-button>
          </a>
        </a-col>
      </a-row>
      <a-form-item label="选择兑换规则" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-select
          id="network-edit-rules"
          allowClear
          v-decorator="[
            'formData.goldExRuleNo',
            { initialValue: formData.goldExRuleNo,
              rules: [{ required: true, message: '请选择兑换规则' }] },
          ]"
          placeholder="请选择兑换规则"
        >
          <a-select-option v-for="(item,index) in goldExRuleNoList" :key="index" :value="item.goldExRuleNo">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="投递时间段" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-select
          id="network-edit-times"
          allowClear
          v-decorator="[
            'formData.deliveryTimeRuleNo',
            { initialValue: formData.deliveryTimeRuleNo,
              rules: [{ required: true, message: '请选择投递时间段' }] },
          ]"
          placeholder="请选择投递时间段"
        >
          <a-select-option v-for="(item,index) in deliveryTimeRuleNoList" :key="index" :value="item.deliveryTimeRuleNo">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="网点标签" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-select
          id="network-edit-labelNoList"
          placeholder="请选择网点标签"
          allowClear
          mode="multiple"
          v-decorator="[
            'formData.labelNoList',
            { initialValue: formData.labelNoList}
          ]"
          :showSearch="true"
          option-filter-prop="children"
          :filter-option="filterOption"
          @select="select"
          @deselect="deselect"
        >
          <a-select-option v-for="item in lableData" :key="item.labelNo" :value="item.labelNo" :disabled="item.disabled">{{ item.labelName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 6 }" style="text-align: center;">
        <a-button type="primary" html-type="submit" id="network-edit-submit" style="margin-right: 15px">保存</a-button>
        <a-button @click="isShow=false" style="margin-left: 15px" id="network-edit-close">取消</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { stationSave, stationFind, getProvince, getCityByPro, getDistrictByCity } from '@/api/station'
import { goldExListQuery } from '@/api/exchangeSetting.js'
import { deliveryTimeListQuery } from '@/api/openTimeSetting.js'
import { lableSeleteList } from '@/api/labelSetting.js'
export default {
  name: 'EditModal',
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    networkId: {
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      formData: {
        name: null, //  网点名称
        provinceCode: undefined, //  省
        provinceName: '',
        cityCode: undefined, // 市
        cityName: '',
        districtCode: undefined, // 区
        districtName: '',
        address: '', //  详细地址
        lat: '', //  纬度
        lng: '', //  经度
        goldExRuleNo: undefined, //  兑换规则
        deliveryTimeRuleNo: undefined, //  投递时间段
        labelNoList: [] // 网点标签编号
      },
      goldExRuleNoList: [], //  兑换规则下拉数据
      deliveryTimeRuleNoList: [], //  投递时间段下拉数据
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      lableData: [], // 标签数据
      newArr: [] // 机构标签数据
    }
  },
  computed: {
    modalTit () {
      return this.networkId ? '编辑' : '新增'
    }
  },
  methods: {
    //  获取详情
    getDetails () {
      stationFind({ id: this.networkId }).then(res => {
        if (res.status == 200) {
          //  省市区
          this.getCityList(res.data.provinceCode)
          this.getAreaList(res.data.cityCode)
          this.form.setFieldsValue({ 'formData.name': res.data.name })
          this.form.setFieldsValue({ 'formData.provinceCode': res.data.provinceCode })
          this.form.setFieldsValue({ 'formData.cityCode': res.data.cityCode })
          this.form.setFieldsValue({ 'formData.districtCode': res.data.districtCode })
          this.form.setFieldsValue({ 'formData.address': res.data.address })
          this.form.setFieldsValue({ 'formData.lat': res.data.lat })
          this.form.setFieldsValue({ 'formData.lng': res.data.lng })
          this.form.setFieldsValue({ 'formData.goldExRuleNo': res.data.goldExRuleNo })
          this.form.setFieldsValue({ 'formData.deliveryTimeRuleNo': res.data.deliveryTimeRuleNo })
          this.form.setFieldsValue({ 'formData.labelNoList': res.data.labelNoList })
          let b = {}
          setTimeout(() => {
            const selectedLable = res.data.labelNoList
            console.log(selectedLable, '-选中数据】')
            for (var i = 0; i < selectedLable.length; i++) {
              console.log(selectedLable.length, this.newArr, 'selectedLable.length')
              b = this.newArr.find(k => k.labelNo == selectedLable[i])
              console.log(selectedLable[i], 'i', b, '-xiangqngshuju')
              if (b) {
                this.lableData.forEach(item => {
                  console.log(item, '----------item------------')
                  if (item.labelType == 'org' && item.labelNo != b.labelNo) {
                    item.disabled = true
                  } else {
                    item.disabled = false
                  }
                })
                return
              }
            }
            // for (var item of selectedLable) {
            //   const itemLabel = item
            //   console.log(item, '-----------------------')
            //   b = this.newArr.find(k => k.labelNo == itemLabel)
            //   console.log(item, 'item', b, '-xiangqngshuju')
            //   if (b) {
            //     this.lableData.forEach(item => {
            //       if (item.labelType == 'org' && item.labelNo != b.labelNo) {
            //         item.disabled = true
            //       } else {
            //         item.disabled = false
            //       }
            //     })
            //   }
            //   break
            // }

            // selectedLable.map(item => {
            //   b = this.newArr.find(k => k.labelNo == item)
            //   if (b) {
            //     this.lableData.forEach(item => {
            //       if (item.labelType == 'org' && item.labelNo != b.labelNo) {
            //         item.disabled = true
            //       } else {
            //         item.disabled = false
            //       }
            //     })
            //   }
            // })
            console.log(b, '-xiangqngshuju ')
            console.log(selectedLable, '-选中数据】')
          }, 1000)
        }
      })
    },
    //  物流信息  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.form.validateFields((err, values) => {
        console.log(values, '------------')
        if (!err) {
          const formData = values.formData
          console.log(formData, '-----参数')
          formData.id = this.networkId || null
          formData.provinceName = _this.addrProvinceList.find(item => item.id == formData.provinceCode).name
          formData.cityName = _this.addrCityList.find(item => item.id == formData.cityCode).name
          formData.districtName = _this.addrDistrictList.find(item => item.id == formData.districtCode).name
          stationSave(formData).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.$emit('success')
                _this.isShow = false
              }, 1000)
            }
          })
        }
      })
    },
    //  投递时间段
    getdeliveryTimeRule () {
      deliveryTimeListQuery({}).then(res => {
        if (res.status == 200) {
          this.deliveryTimeRuleNoList = res.data
        } else {
          this.deliveryTimeRuleNoList = []
        }
      })
    },
    //  兑换规则
    getgoldExRule () {
      goldExListQuery({}).then(res => {
        if (res.status == 200) {
          this.goldExRuleNoList = res.data
        } else {
          this.goldExRuleNoList = []
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取标签数据
    getlableSeleteList () {
      lableSeleteList().then(res => {
        if (res.status == 200) {
          this.lableData = res.data || []
          this.lableData.map(item => {
            if (item.labelType == 'org') {
              this.newArr.push(item)
              console.log(this.newArr, '--------机构类型')
            }
          })
        }
      })
    },
    // 选中标签
    select (value, option) {
      console.log(value, option, 'hfhhhhhhh')
      const a = this.newArr.find(item => item.labelNo == value)
      if (a) {
        this.lableData.forEach(item => {
          if (item.labelType == 'org' && item.labelNo != value) {
            item.disabled = true
          } else {
            item.disabled = false
          }
        })
      }
    },
    // 取消选中标签
    deselect (value, option) {
      const a = this.newArr.find(item => item.labelNo == value)
      if (a) {
        this.lableData.forEach(item => {
          if (item.labelType == 'org') {
            item.disabled = false
          }
        })
      }
    },
    // 获取省列表
    getProvinceList () {
      getProvince().then(res => {
        if (res.status == 200) {
          this.addrProvinceList = res.data || []
        } else {
          this.addrProvinceList = []
        }
      })
    },
    // 获取城市列表
    getCityList (val) {
      this.addrCityList = []
      this.addrDistrictList = []
      this.form.setFieldsValue({ 'formData.cityCode': undefined })
      this.form.setFieldsValue({ 'formData.districtCode': undefined })
      this.form.setFieldsValue({ 'formData.address': '' })
      this.getCityListRequest(val)
    },
    getCityListRequest (val) {
      getCityByPro({
        id: val
      }).then(res => {
        if (res.status == 200) {
          this.addrCityList = res.data || []
        } else {
          this.addrCityList = []
        }
      })
    },
    // 获取区县列表
    getAreaList (val) {
      this.addrDistrictList = []
      this.form.setFieldsValue({ 'formData.districtCode': undefined })
      this.form.setFieldsValue({ 'formData.address': '' })
      this.getAreaListRequest(val)
    },
    getAreaListRequest (val) {
      getDistrictByCity({
        id: val
      }).then(res => {
        if (res.status == 200) {
          this.addrDistrictList = res.data || []
        } else {
          this.addrDistrictList = []
        }
      })
    },
    // 区县变更
    areaCharged (val) {
      this.form.setFieldsValue({ 'formData.address': '' })
    }
  },
  mounted () {
    this.getlableSeleteList() // 网点标签
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
      } else {
        this.getProvinceList()
        this.getdeliveryTimeRule() //  投递时间段
        this.getgoldExRule() //  兑换规则
        this.form.resetFields()
      }
    },
    networkId (newValue, oldValue) {
      if (this.isShow && newValue) {
        this.getDetails()
      }
    }
  }
}
</script>

<style lang="less">
  .edit-network-modal{
    .network-edit-search-jwd{
      margin-top: 8px;
    }
  }
</style>
