<template>
  <el-dialog
    v-dialog-drag
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :title="`${dialogStatus === 'create' ? '新建' : '编辑'}集团`"
    :visible.sync="dialogVisible"
    width="500px"
    append-to-body
    @close="handleCancel"
  >
    <el-form ref="form" :model="formState" :rules="rules" label-width="100px">
      <el-form-item label="集团名称" prop="name">
        <el-input v-model="formState.name" :minlength="1" :maxlength="21" placeholder="请输入集团名称" />
      </el-form-item>
      <el-form-item label="所在省市区" prop="belongRegion">
        <area-cascader :province-id.sync="formState.provinceId" :city-id.sync="formState.cityId" :district-id.sync="formState.districtId" @change="handleSelectArea" />
      </el-form-item>
      <el-form-item label="备注" prop="remark" :rules="{ required: false, min: 0, max: 30, message: '备注不能超过30字', trigger: 'blur' }">
        <el-input
          v-model="formState.remark"
          type="textarea"
          placeholder="请输入内容"
          show-word-limit
          :autosize="{minRows: 2, maxRows: 2}"
          :style="{width: '100%'}"
          :maxlength="30"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addGarden, getGarden, listRepeatGardenName, updateGarden } from '@/api/system/garden'
import AreaCascader from '@/components/Cascader/AreaCascader.vue'

const initForm = {
  name: null,
  remark: null,
  provinceId: null, // 所属区域，
  cityId: null,
  districtId: null,
  belongRegion: null
}
export default {
  components: { AreaCascader },
  data() {
    const nameValidator = (voteRule, value, callback) => {
      const { id } = this.formState
      if (value) {
        listRepeatGardenName(value, id).then((res) => {
          if (res.data && res.data.length > 0) {
            callback(new Error('集团名称已存在'))
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    }
    return {
      dialogStatus: 'create',
      dialogVisible: false,
      loading: false,
      formState: Object.assign({}, initForm),
      rules: {
        name: [
          { required: true, message: '集团名称不能为空', trigger: 'blur' },
          { min: 1, max: 20, message: '集团名称不超过20个字', trigger: ['blur', 'change'] },
          { validator: nameValidator, trigger: 'blur' }
        ],
        belongRegion: [
          { required: true, message: '请选择所在省市区', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    /**
     * 新增
     */
    handleOpen() {
      this.dialogStatus = 'create'
      this.dialogVisible = true
    },
    /**
     * 编辑回显
     * @param row
     */
    handleEdit(row) {
      this.dialogStatus = 'edit'
      this.dialogVisible = true
      getGarden(row.id).then(response => {
        this.formState = response.data
      })
    },
    /**
     * 取消
     */
    handleCancel() {
      this.dialogVisible = false
      this.dialogStatus = 'create'
      this.formState = Object.assign({}, initForm)
      this.$refs.form.resetFields()
    },
    /**
     * 保存
     */
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const fn = this.formState.id ? updateGarden : addGarden
          this.loading = true
          fn(this.formState).then(() => {
            this.$modal.msgSuccess('保存成功')
            this.$emit('ok')
            this.handleCancel()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    handleSelectArea(str) {
      if (str) {
        this.$nextTick(() => {
          this.$refs.form.clearValidate('area')
        })
      }
      this.formState.belongRegion = str
    }
  }
}
</script>
<style scoped lang="scss">

</style>
