<template>
  <a-modal
    centered
    class="addShop-modal"
    :footer="null"
    :maskClosable="false"
    :title="modalTit"
    v-model="isShow"
    @cancle="isShow=false"
    :width="1000">
    <a-form id="addShop-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="addShop-name"
          :maxLength="30"
          v-decorator="[
            'formData.name',
            { initialValue: formData.name, getValueFromEvent: $filterEmpty, rules: [{ message: '请输入网点名称' }] }
          ]"
          placeholder="请输入店铺名称(最多30个字符)"
          allowClear />
      </a-form-item>
      <a-form-item label="电话" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-input
          id="addShop-mobile"
          :maxLength="11"
          type="number"
          :disabled="!isEdit && itemId!=''"
          v-decorator="[
            'formData.mobile',
            { initialValue: formData.mobile, getValueFromEvent: $filterEmpty, rules: [{ required: true, message: '请输入电话' },{pattern:/^[1][0-9]{10}$/, message: '请输入正确的骑手电话!'}] }
          ]"
          placeholder="请输入电话"
          allowClear />
      </a-form-item>
      <a-form-item label="所属骑手" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-select
          id="addShop-riderId"
          placeholder="请选择"
          allowClear
          v-decorator="[
            'formData.riderId',
            { initialValue: formData.riderId}
          ]"
          :showSearch="true"
          option-filter-prop="children"
          :filter-option="filterOption">
          <a-select-option v-for="item in lableData" :key="item.userId" :value="item.userId">{{ item.userName+'-' }}{{ item.userMobile }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="地址"
        :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="addShop-provinceCode"
                @change="getCityList"
                v-decorator="['formData.reverseReceiveAddress.provinceCode', { initialValue: formData.reverseReceiveAddress.provinceCode}]"
                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="addShop-cityCode"
                v-decorator="['formData.reverseReceiveAddress.cityCode', { initialValue: formData.reverseReceiveAddress.cityCode}]"
                @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="addShop-districtCode"
                v-decorator="['formData.reverseReceiveAddress.districtCode', { initialValue: formData.reverseReceiveAddress.districtCode}]"
                @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="addShop-receiveAddress"
          :maxLength="30"
          v-decorator="[
            'formData.reverseReceiveAddress.receiveAddress',
            { initialValue: formData.reverseReceiveAddress.receiveAddress, getValueFromEvent: $filterEmpty }
          ]"
          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.reverseReceiveAddress.lat',
                { initialValue: formData.reverseReceiveAddress.lat, rules: [
                  { 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.reverseReceiveAddress.lng',
                { initialValue: formData.reverseReceiveAddress.lng, getValueFromEvent: $filterEmpty, rules: [
                  { 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" style="margin-top: 8px;" size="small">查询坐标</a-button>
          </a>
        </a-col>
      </a-row>
      <a-form-item label="门头照" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <Upload
          class="upload"
          id="storeImage-headerImageList"
          v-decorator="[ 'headerImageList', { initialValue: headerImageList } ]"
          ref="storeImage"
          :fileSize="0.25"
          @change="getStoreImage"
          listType="picture-card"></Upload>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 6 }" style="text-align: center;">
        <a-button type="primary" html-type="submit" id="addShop-submit" style="margin-right: 15px">保存</a-button>
        <a-button @click="isShow=false" style="margin-left: 15px" id="addShop-close">取消</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import {
  getProvince,
  getCityByPro,
  getDistrictByCity
} from '@/api/station'
import {
  savShop,
  riderData,
  shopDetails
} from '@/api/recoveryManage.js'
import {
  Upload
} from '@/components'
export default {
  name: 'AddShop',
  props: {
    visible: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemId: {
      type: [Number, String],
      default: ''
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    visible (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.close()
        this.$emit('close')
      } else {
        console.log(this.isEdit, this.headerImageList, this.formData.reverseReceiveAddress.headerImageList, '===========是否编辑')
        this.pageInit()
      }
    },
    itemId (newValue, oldValue) {
      if (this.isShow && newValue) {
        console.log(this.isShow && newValue)
      } else {
        this.isEdit = false
      }
    }
  },
  components: {
    Upload
  },
  data () {
    return {
      isShow: this.visible, //  是否打开弹框
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          span: 4
        },
        wrapperCol: {
          span: 16
        }
      },
      formData: {
        name: null, //  网点名称
        mobile: '',
        riderId: undefined,
        reverseReceiveAddress: {
          provinceCode: undefined, //  省
          provinceName: '',
          cityCode: undefined, // 市
          cityName: '',
          districtCode: undefined, // 区
          districtName: '',
          receiveAddress: '',
          lat: '',
          lng: ''
        }
      },
      headerImageList: '',
      isEdit: false, // 是否可编辑
      goldExRuleNoList: [], //  兑换规则下拉数据
      deliveryTimeRuleNoList: [], //  投递时间段下拉数据
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      lableData: [] // 骑手数据
    }
  },
  computed: {
    modalTit () {
      return this.itemId ? '编辑' : '新增'
    }
  },
  mounted () {
    this.getRiderData() // 网点标签
  },
  methods: {
    pageInit () {
      this.getProvinceList()
      this.form.resetFields()
      this.getDetails()
    },
    getStoreImage (data) {
      this.headerImageList = data
    },
    close () {
      this.headerImageList = ''
      this.formData.reverseReceiveAddress.headerImageList = []
      if (this.$refs.storeImage) {
        this.$refs.storeImage.setFileList('')
      }
    },
    //  获取详情
    getDetails () {
      shopDetails({
        id: this.itemId
      }).then(res => {
        if (res.status == 200) {
          this.isEdit = res.data.sourceTypeReserve == 'admin'
          //  省市区
          this.getCityList(res.data.reverseReceiveAddress && res.data.reverseReceiveAddress.provinceCode ? res
            .data.reverseReceiveAddress.provinceCode : undefined)
          this.getAreaList(res.data.reverseReceiveAddress && res.data.reverseReceiveAddress.cityCode ? res.data
            .reverseReceiveAddress.cityCode : undefined)
          this.form.setFieldsValue({
            'formData.name': res.data.name
          })
          this.form.setFieldsValue({
            'formData.mobile': res.data.mobile
          })
          this.form.setFieldsValue({
            'formData.riderId': res.data.riderId
          })
          this.form.setFieldsValue({
            'formData.reverseReceiveAddress.provinceCode': res.data.reverseReceiveAddress.provinceCode ? res
              .data.reverseReceiveAddress.provinceCode : undefined
          })
          this.form.setFieldsValue({
            'formData.reverseReceiveAddress.cityCode': res.data.reverseReceiveAddress.cityCode ? res.data.reverseReceiveAddress.cityCode : undefined
          })
          this.form.setFieldsValue({
            'formData.reverseReceiveAddress.districtCode': res.data.reverseReceiveAddress.districtCode ? res.data.reverseReceiveAddress.districtCode : undefined
          })
          this.form.setFieldsValue({
            'formData.reverseReceiveAddress.receiveAddress': res.data.reverseReceiveAddress.receiveAddress ? res.data.reverseReceiveAddress.receiveAddress : ''
          })
          this.form.setFieldsValue({
            'formData.reverseReceiveAddress.lat': res.data.reverseReceiveAddress.lat ? res.data.reverseReceiveAddress.lat : ''
          })
          this.form.setFieldsValue({
            'formData.reverseReceiveAddress.lng': res.data.reverseReceiveAddress.lng ? res.data.reverseReceiveAddress.lng : ''
          })
          this.$refs.storeImage.setFileList(res.data.reverseReceiveAddress.headerImageList ? res.data.reverseReceiveAddress.headerImageList.join() : '')
          // this.form.setFieldsValue({
          //   'formData.reverseReceiveAddress.headerImageList': res.data.reverseReceiveAddress.headerImageList?res.data.reverseReceiveAddress.headerImageList.join(',') :''
          // })
        }
      })
    },
    // 保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.form.validateFields((err, values) => {
        console.log(values, '------------')
        if (!err) {
          const formData = Object.assign(values.formData, {
            'sourceTypeReserve': 'admin'
          })
          console.log(formData, '-----参数')
          formData.id = this.itemId || null
          if (formData.reverseReceiveAddress.provinceCode) {
            formData.reverseReceiveAddress.provinceName = _this.addrProvinceList.find(item => item.id == formData
              .reverseReceiveAddress.provinceCode).name
          }
          if (formData.reverseReceiveAddress.cityCode) {
            formData.reverseReceiveAddress.cityName = _this.addrCityList.find(item => item.id == formData
              .reverseReceiveAddress.cityCode).name
          }
          if (formData.reverseReceiveAddress.districtCode) {
            formData.reverseReceiveAddress.districtName = _this.addrDistrictList.find(item => item.id == formData
              .reverseReceiveAddress.districtCode).name
          }
          if (this.headerImageList) {
            formData.reverseReceiveAddress.headerImageList = this.headerImageList.split(',')
          }
          if ((formData.reverseReceiveAddress.lat == '' && formData.reverseReceiveAddress.lng == '') && (formData
            .riderId == '' || formData.riderId == undefined)) {
            this.$message.error('所属骑手或经纬度至少选择一个')
            return
          }
          savShop(formData).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.$emit('refresh')
                _this.isShow = false
              }, 1000)
            }
          })
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取标签数据
    getRiderData () {
      riderData().then(res => {
        if (res.status == 200) {
          this.lableData = res.data || []
        }
      })
    },
    // 获取省列表
    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': ''
      })
    }
  }

}
</script>

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