<template>
  <div>
    <el-dialog
      v-dialog-drag
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :title="`${dialogStatus === 'create' ? '新增' : '编辑'}幼儿园`"
      :visible.sync="dialogVisible"
      width="900px"
      append-to-body
      @close="handleCancel"
    >
      <el-row :gutter="20">
        <el-form ref="form" class="full-form" :model="formState" :rules="rules" label-width="100px" :disabled="readonly">
          <el-col :span="12">
            <el-form-item label="幼儿园名称" prop="kindergartenName">
              <el-input v-model.trim="formState.kindergartenName" v-emoji :minlength="1" :maxlength="51" placeholder="请输入幼儿园名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="幼儿园类型" prop="kindergartenType">
              <el-select v-model="formState.kindergartenType" filterable placeholder="请选择幼儿园类型" :disabled="isEdit">
                <el-option
                  v-for="dict in options.kindergartenType"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="所属集团"
              prop="gardenId"
              :style="isGroup ? 'display:block' : 'display:none'"
              :rules="[{required: isGroup, message:'所属集团不能为空',trigger:['blur', 'change']}]"
            >
              <el-select v-model="formState.gardenId" filterable placeholder="请选择所属集团" clearable :disabled="isEdit">
                <el-option
                  v-for="group in gardenList"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="是否集团总园"
              prop="isGarden"
              label-width="110px"
              :style="isGroup ? 'display:block;' : 'display:none'"
              :rules="[{required: isGroup ,message:'是否集团总园不能为空',trigger: ['blur', 'change']}]"
            >
              <el-radio-group v-model="formState.isGarden" size="medium">
                <el-radio
                  v-for="(item, index) in isGardenOptions"
                  :key="index"
                  :label="item.value"
                  :disabled="item.disabled"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="幼儿园简称" prop="simpleName">
              <el-input v-model="formState.simpleName" placeholder="请输入幼儿园简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="englishName">
              <el-input v-model="formState.englishName" placeholder="请输入幼儿园英文名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="园长" prop="principal">
              <el-input v-model="formState.principal" placeholder="请输入园长" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="园长电话" prop="principalPhone" :rules="[{ required: false, validator: mobileValidator, trigger: 'blur' }]">
              <el-input
                v-model="formState.principalPhone"
                placeholder="请输入园长电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="formState.legalPerson" placeholder="请输入法人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="belongRegionCode">
              <area-cascader :province-id.sync="formState.provinceId" :city-id.sync="formState.cityId" :district-id.sync="formState.districtId" style="width: 100%" @change="handleSelectArea" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="幼儿园logo" prop="fileId">
              <upload-file
                :limit="1"
                list-type="picture-card"
                :file-list.sync="fileList"
                :accept="DEFINE.FILE.PNG"
                :show-file-list="true"
              />
              <span class="form-tip">支持图片（格式：jpeg、jpg、png、gif），且不超过2MB</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input
                v-model="formState.detailAddress"
                placeholder="请输入详细地址"
                show-word-limit
                :maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" label-width="100px">
            <el-form-item label="幼儿园定位" prop="locationAddress">
              <div class="d-flex">
                <el-button plain type="primary" style="margin-right: 4px" size="small" @click="handleOpenMap">
                  点击定位
                </el-button>
                <span class="form-tip" style="color: #606266">{{ formState.locationAddress }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formState.remark"
                type="textarea"
                placeholder="请输入内容"
                show-word-limit
                :autosize="{minRows: 2, maxRows: 4}"
                :style="{width: '100%'}"
                :maxlength="120"
              />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="!readonly" type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
    <position-map-dialog ref="mapDialog" @ok="handleSetPosition" />
  </div>
</template>

<script>
import { addBranch, editBranch, getBranch } from '@/api/system/branch'
import AreaCascader from '@/components/Cascader/AreaCascader.vue'
import PositionMapDialog from '@/views/system/information/modules/PositionMapDialog.vue'
import { DEFINE } from '@/utils/dict/config'
import { fetchAllGarden } from '@/api/system/garden'
import options from '@/utils/dict/options'
import regex from '@/utils/regex'
import { fetchFileUrl } from '@/utils'
import UploadFile from '@/components/Upload/UploadFile.vue'
import Define from '@/utils/dict/Define'

const initForm = {
  id: null,
  kindergartenName: null,
  kindergartenType: null,
  gardenId: null,
  isGarden: null,
  simpleName: null,
  englishName: null,
  principal: null,
  principalPhone: null,
  legalPerson: null,
  fileId: null,
  provinceId: null, // 所属区域，
  cityId: null,
  belongRegion: null, // 省市区
  districtId: null,
  detailAddress: null,
  locationAddress: null, // 幼儿园定位
  latitudeLongitude: null, // 经纬度
  remark: null
}
export default {
  components: {
    AreaCascader,
    PositionMapDialog,
    UploadFile
  },
  data() {
    const kindergartenNameValidator = (voteRule, value, callback) => {
      if (value && /[\uD800-\uDBFF][\uDC00-\uDFFF]/g.test(value)) {
        callback(new Error('不能输入特殊符号'))
      } else {
        callback()
      }
    }
    return {
      submitLoading: false,
      options,
      DEFINE,
      Define,
      uploadUrl: process.env.VUE_APP_BASE_API + '/file/upload',
      dialogStatus: 'create',
      dialogVisible: false,
      readonly: false,
      isEdit: false,
      gardenList: [],
      formState: Object.assign({}, initForm),
      isGardenOptions: options.yOrN,
      loading: false,
      fileList: [],
      rules: {
        kindergartenName: [
          { required: true, message: '幼儿园名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '幼儿园名称不超多50字', trigger: ['change', 'blur'] }
          // { message: '不能输入特殊符号', trigger: 'blur', validator: kindergartenNameValidator }
        ],
        kindergartenType: { required: true, message: '幼儿园类型不能为空', trigger: 'blur' }
      }
    }
  },
  computed: {
    isGroup() {
      return this.formState.kindergartenType === options.kindergartenTypeMap.kindergartenGroup
    }
  },
  methods: {
    mobileValidator(voteRule, value, callback) {
      if (value && !regex.mobile.test(value)) {
        callback(new Error('手机号格式不正确！'))
      } else {
        callback()
      }
    },
    getGardenList() {
      fetchAllGarden().then(({ data }) => {
        this.gardenList = data && data.length > 0 ? data : []
      })
    },
    handleOpen() {
      this.getGardenList()
      this.dialogVisible = true
      this.dialogStatus = 'create'
      this.isEdit = false
    },
    handleEdit({ id, tenantAccount }, readonly = false) {
      // 已存在账号不能 修改所属集团 幼儿园类型
      this.readonly = readonly
      this.isEdit = !!tenantAccount
      this.dialogStatus = 'edit'
      getBranch(id).then(({ data }) => {
        this.formState = data
        if (data.fileId) {
          fetchFileUrl(data.fileId).then(data => {
            this.fileList = data
          })
        }
        this.dialogVisible = true
      })
    },
    handleCancel() {
      this.dialogVisible = false
      this.fileList = []
      this.fileList = []
      this.$refs.form.clearValidate()
      this.formState = Object.assign({}, initForm)
      this.readonly = false
    },
    handleUploadSuccess({ code, msg, data }, file, fileList) {
      if (code !== 200) {
        this.$modal.msgError(`${msg}`)
      } else {
        data.name = data.fileName
        data.url = data.fileUrl
        this.fileList = [].concat(data)
        this.formState.logoUrl = data.fileUrl
        this.formState.fileId = data.id
      }
    },
    handleOpenMap() {
      const { latitudeLongitude, locationAddress } = this.formState
      const latitudeTmp = latitudeLongitude ? latitudeLongitude.split(',')[0] : ''
      const longitudeTmp = latitudeLongitude ? latitudeLongitude.split(',')[1] : ''
      this.$refs.mapDialog.handleOpen(latitudeTmp, longitudeTmp, locationAddress || null)
    },
    handleSetPosition({ latitudeLongitude, locationAddress }) {
      this.formState.latitudeLongitude = latitudeLongitude
      this.formState.locationAddress = locationAddress
    },
    handleSelectArea(str) {
      this.formState.belongRegion = str
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const isEdit = this.dialogStatus === 'edit'
          this.formState.fileId = this.fileList && this.fileList.length > 0 ? this.fileList[0].fileId : null
          this.formState.logoUrl = this.fileList && this.fileList.length > 0 ? this.fileList[0].fileUrl : null
          const fn = isEdit ? editBranch : addBranch
          this.submitLoading = true
          fn(this.formState).then(() => {
            this.$modal.msgSuccess(`${isEdit ? '编辑' : '新增'}成功`)
            this.$emit('ok')
            this.handleCancel()
          }).finally(() => {
            this.submitLoading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
