<template>
  <div class="club-edit">
    <el-form ref="submitForm" class="club-edit-form" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="机构名称:" prop="name">
        <el-input v-model="formData.name" placeholder="请输入机构名称" />
      </el-form-item>
      <el-form-item label="所在地区:" prop="address">
        <el-cascader
          ref="cascader"
          v-model="formData.address"
          :class="{ display: cascaderDisplay }"
          clearable
          :props="cascaderProps"
          style="width: 100%"
          :placeholder="cascaderPlaceholder"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="详细地址:" prop="fullAddress">
        <el-input v-model="formData.fullAddress" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="经纬度:" prop="point">
        <el-input v-model="formData.point" placeholder="请输入经纬度 （格式：纬度,经度，可通过右侧地图小按钮获取）">
          <el-button slot="append" icon="el-icon-map-location" @click="dialogMapVisible = true" />
        </el-input>
      </el-form-item>
      <el-form-item label="联系方式:" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入联系方式" />
      </el-form-item>
      <el-form-item label="机构logo:" prop="logoImage">
        <el-input v-show="false" v-model="formData.logoImage" />
        <upload-image
          tip="建议尺寸：242px * 242px"
          :image-list="logoList"
          :before-upload="beforeLogoUpload"
          @success="uploadLogoSuccess"
          @remove="handleLogoRemove"
        />
      </el-form-item>
      <el-form-item label="轮播图:" prop="banner">
        <el-input v-show="false" v-model="formData.banner" />
        <upload-image
          tip="至少上传一张，最多6张；建议尺寸：542px * 542px"
          :image-list="bannerList"
          :before-upload="beforeBannerUpload"
          :limit="6"
          @success="uploadBannerSuccess"
          @remove="handleBannerRemove"
        />
      </el-form-item>
    </el-form>
    <div class="submit-btn">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="warning" @click="$_back()">返回</el-button>
    </div>

    <el-dialog
      class="map-dialog"
      title="坐标拾取（请拖动标记点选取准确位置）"
      :visible.sync="dialogMapVisible"
      width="80%"
    >
      <!-- <location v-if="dialogMapVisible" :init-point="formData.point" @point="handlePointChange" /> -->
      <map-ui v-if="dialogMapVisible" :init-point="formData.point" :address="locationAddress" @change="markerChange" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="dialogMapVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import Location from '@/components/location'
import AMapUI from '@/components/AMapUI'
import UploadImage from '@/components/UploadImage'
import { mapGetters } from 'vuex'
import { saveBrandAuth, getAuthFormData } from '@/api/auth'
import { getAddress } from '@/api/common'
import { isPoint, isNumber } from '@/utils/validate'

export default {
  components: {
    // Location
    [AMapUI.name]: AMapUI,
    UploadImage
  },
  data() {
    var validatePoint = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('经纬度坐标不能为空'))
      } else {
        if (isPoint(value)) {
          this.$refs.ruleForm.validateField('point')
        } else {
          callback('经纬度坐标格式不正确，(例如：114.095294,22.536004)')
        }
        callback()
      }
    }

    var validateMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('联系方式不能为空'))
      } else {
        if (isNumber(value)) {
          this.$refs.ruleForm.validateField('point')
        } else {
          callback('联系方式格式不正确')
        }
        callback()
      }
    }

    return {
      dialogMapVisible: false,
      point: {},
      value: [],
      options: [],

      authId: '',
      disabled: false,

      area: '',
      formData: {
        name: '',
        address: [],
        fullAddress: '',
        point: '',
        mobile: '',
        logoImage: '',
        banner: ''
      },
      rules: {
        name: [{ required: true, message: '机构名称不能为空', trigger: ['blur', 'change'] }],
        address: [{ required: true, message: '地址不能为空', trigger: 'change', type: 'array' }],
        fullAddress: [{ required: true, message: '详细不能为空', trigger: ['blur', 'change'] }],
        point: [{ validator: validatePoint, trigger: ['blur', 'change'] }],
        mobile: [{ validator: validateMobile, trigger: ['blur', 'change'] }],
        logoImage: [{ required: true, message: '请上传机构logo', trigger: 'change' }],
        banner: [{ required: true, message: '请至少上传一张banner图片', trigger: 'change' }]
      },
      // logo图片列表
      logoList: [],
      // banner图片列表
      bannerList: [],
      // 级联选择的地址
      address: ''
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'proxyInfo']),
    // 级联选择器
    cascaderProps() {
      return {
        lazy: true,
        lazyLoad: async(node, resolve) => {
          const { level, value = 0 } = node
          const result = await getAddress({ parentId: value, type: level })
          const nodes = result.data.map(item => ({ value: item.id, label: item.name, leaf: level >= 2 }))
          resolve(nodes)
        }
      }
    },
    cascaderDisplay() {
      return this.formData.address.length > 0
    },
    cascaderPlaceholder() {
      return this.cascaderDisplay ? this.area : '请选择所在区域'
    },
    // 定位使用的地址
    locationAddress() {
      return this.address + this.formData.fullAddress
    }
  },
  created() {
    this.authId = this.$route.query.id
    this.initFormData()
  },
  methods: {
    // 获取地址
    initAddress() {
      return getAddress({
        parentId: 19,
        type: 1
      })
    },

    // 地图标记变化
    markerChange(point) {
      this.formData.point = `${point.lng},${point.lat}`
    },

    // 数据回显
    initFormData() {
      getAuthFormData({ authId: this.authId }).then(res => {
        console.log(res)
        this.formData.name = res.data.authParty

        this.formData.fullAddress = res.data.address
        this.formData.point = res.data.lngAndLat
        this.formData.mobile = res.data.mobile
        this.formData.logoImage = res.data.logo
        this.formData.banner = res.data.bannerList.length || ''

        this.logoList = [{ name: '', url: res.data.logo }]
        this.bannerList = res.data.bannerList.map(item => ({ name: '', url: item }))

        this.formData.address = [res.data.provinceId, res.data.cityId, res.data.townId]
        // this.formData.address = '广东省/深圳市/福田区'
        this.area = res.data.area
      })
    },

    // 表单提交保存
    submit() {
      this.$refs.submitForm.validate(valide => {
        if (!valide) return

        console.log(this.formData)
        const {
          name: authParty,
          address: [provinceId, cityId, townId],
          mobile,
          logoImage: logo,
          point: lngAndLat
        } = this.formData

        const authUserId = this.proxyInfo?.authUserId || this.authUserId

        const data = {
          authId: parseInt(this.authId),
          authParty,
          authUserId,
          createBy: authUserId,
          provinceId,
          cityId,
          townId,
          address: this.formData.fullAddress,
          mobile,
          logo,
          lngAndLat
        }

        data.bannerList = this.bannerList.map(item => item.response ? item.response.data : item.url)

        console.log(data)
        saveBrandAuth(data)
          .then(res => {
            const h = this.$createElement
            this.$notify.success({
              title: `修改授权机构`,
              message: h('i', { style: 'color: #333' }, `已修改授权机构："${this.formData.name}"`),
              duration: 3000
            })
            this.$refs.submitForm.resetFields()
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.push('/auth/list')
          })
          .catch(err => {
            this.$message.danger(err.msg)
          })
      })
    },
    handleChange(e) {
      const node = this.$refs.cascader.getCheckedNodes()
      if (node.length <= 0) return
      this.address = node[0].pathLabels.join()
    },
    // logo上传
    uploadLogoSuccess({ response, file, fileList }) {
      this.logoList = fileList
      this.formData.logoImage = fileList[0].response.data
    },
    handleLogoRemove({ file, fileList }) {
      this.logoList = fileList
      this.formData.logoImage = ''
    },
    beforeLogoUpload(file) {
      const flag = file.size / 1024 < 500
      if (!flag) {
        this.$message.error('上传logo图片大小不能超过 500kb!')
      }
      return flag
    },

    // banner上传
    uploadBannerSuccess({ response, file, fileList }) {
      this.bannerList = fileList
      console.log(this.bannerList)
      this.formData.banner = fileList.length > 0 ? fileList.length : ''
    },
    handleBannerRemove({ file, fileList }) {
      this.bannerList = fileList
      this.formData.banner = fileList.length > 0 ? fileList.length : ''
    },
    beforeBannerUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('上传banner图片大小不能超过 1MB!')
      }
      return flag
    }
  }
}
</script>

<style lang="scss" scoped>
#allmap {
  width: 100%;
  height: 600px;
}

.club-edit {
  margin-bottom: 80px;
}

.club-edit-form {
  width: 600px;
  margin: 0 auto;
  margin-top: 80px;
}
.submit-btn {
  text-align: center;
  .el-button {
    width: 140px;
  }
}
</style>
