<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="请输入机构名称" clearable />
      </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="请输入详细地址" clearable />
      </el-form-item>
      <el-form-item label="经纬度:" prop="point">
        <el-input
          v-model="formData.point"
          placeholder="请输入经纬度 （格式：纬度,经度，可通过右侧地图小按钮获取）"
          clearable
        >
          <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="请输入联系方式" clearable />
      </el-form-item>
      <el-form-item label="手机号:" prop="phoneNumber">
        <el-input v-model="formData.phoneNumber" placeholder="请输入手机号" clearable maxlength="11" />
      </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-item label="机构类型:">
        <el-radio-group v-model="formData.clubType">
          <el-radio :label="1">医美</el-radio>
          <el-radio :label="2">生美</el-radio>
          <el-radio :label="3">项目公司</el-radio>
          <el-radio :label="4">个人</el-radio>
          <el-radio :label="5">其他</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="医美类型:">
        <el-radio-group v-model="formData.medicalType">
          <el-radio :label="1">诊所</el-radio>
          <el-radio :label="2">门诊</el-radio>
          <el-radio :label="3">医院</el-radio>
          <el-radio :label="4">其他</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="医疗许可证:" prop="licenseImage">
        <el-input v-show="false" v-model="formData.licenseImage" />
        <upload-image
          tip="请上传医疗许可证；建议尺寸：542px * 542px"
          :limit="1"
          :image-list="licenseImageList"
          :before-upload="beforeLicenseImageUpload"
          @success="uploadLicenseImageSuccess"
          @remove="handleLicenseImageRemove"
        />
      </el-form-item>

      <el-form-item label="员工人数:" prop="memberCount">
        <el-input v-model.number="formData.memberCount" placeholder="请输入员工人数" clearable />
      </el-form-item>

      <el-form-item label="自定义属性:">
        <el-radio-group v-model="formData.customFlag" size="mini">
          <el-radio :label="0" border>否</el-radio>
          <el-radio :label="1" border>是</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="formData.customFlag === 1">
        <el-form-item label="店铺备注:" prop="remarks">
          <el-input v-model="formData.remarks" placeholder="店铺备注" clearable />
        </el-form-item>
      </template>
    </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, isMobile } 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)) {
          callback()
        } else {
          callback(new Error('经纬度坐标格式不正确，(例如：114.095294,22.536004)'))
        }
      }
    }

    var validateMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('联系方式不能为空'))
      } else {
        if (isMobile(value)) {
          callback()
        } else {
          callback(new Error('联系方式格式不正确'))
        }
      }
    }

    var validatePhoneNumber = (rule, value, callback) => {
      if (!value || isMobile(value)) {
        callback()
      } else {
        callback(new Error('手机号格式不正确'))
      }
    }

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

      authId: '',
      disabled: false,

      area: '',
      formData: {
        name: '',
        address: [],
        fullAddress: '',
        point: '',
        mobile: '',
        phoneNumber: '',
        logoImage: '',
        banner: '',
        customFlag: 0,
        remarks: '',
        memberCount: '',
        clubType: 1,
        medicalType: 1,
        licenseImage: ''
      },
      rules: {
        name: [{ required: true, message: '机构名称不能为空', trigger: ['blur', 'change'] }],
        address: [{ required: true, message: '地址不能为空', trigger: 'change', type: 'array' }],
        fullAddress: [{ required: true, message: '详细不能为空', trigger: ['blur', 'change'] }],
        point: [{ required: true, validator: validatePoint, trigger: ['blur', 'change'] }],
        mobile: [{ required: true, validator: validateMobile, trigger: ['blur', 'change'] }],
        logoImage: [{ required: true, message: '请上传机构logo', trigger: 'change' }],
        banner: [{ required: true, message: '请至少上传一张banner图片', trigger: 'change' }],
        remarks: [{ required: true, message: '店铺备注不能为空', trigger: 'blur' }],
        licenseImage: [{ required: true, message: '请上传医疗许可证', trigger: 'change' }],
        memberCount: [{ required: true, message: '员工人数不能为空', trigger: 'change' }],
        phoneNumber: [{ validator: validatePhoneNumber, trigger: 'change' }]
      },
      // logo图片列表
      logoList: [],
      // banner图片列表
      bannerList: [],
      // 级联选择的地址
      address: '',
      // 医疗许可证图片
      licenseImageList: []
    }
  },
  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.editType = this.$route.query.type || 'add'
    this.authId = this.$route.query.id
    this.initFormData()
  },
  methods: {
    // 自定义属性修改
    custromizeFormChange(data) {
      this.customValue = data.name
    },

    // 获取地址
    initAddress() {
      return getAddress({
        parentId: 19,
        type: 1
      })
    },

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

    // 数据回显
    initFormData() {
      if (!this.authId) return
      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.formData.customFlag = res.data.customFlag
        this.formData.remarks = res.data.remarks

        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
        this.address = 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,
          customFlag,
          remarks
        } = 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,
          remarks,
          customFlag
        }

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

        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('/club/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
    },

    // 医疗许可证图片上传
    uploadLicenseImageSuccess({ response, file, fileList }) {
      this.licenseImageList = fileList
      console.log(this.licenseImageList)
      this.formData.licenseImage = response.data
    },
    handleLicenseImageRemove({ file, fileList }) {
      this.licenseImageList = fileList
      this.formData.licenseImage = ''
    },
    beforeLicenseImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('医疗许可证图片大小不能超过 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;
  }
}

.attributes {
  padding-top: 16px;
}
</style>
