<template>
  <el-dialog title="地址配置" :visible.sync="visible" width="40%" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="地址" prop="treeAddress">
            <treeselect
              v-model="form.treeAddress"
              :option-key="'value'"
              :multiple="false"
              :normalizer="normalizer"
              :options="deptOptions"
              :show-count="true"
              :flat="true"
              placeholder="请选择地址"
              @select="onTreeSelect"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getAddressRegion, getAddressTree } from '@/api/grid/list/gridlist'

export default {
  props: {
    currentRow: {
      type: Object,
      default: () => ({})
    },
    checkedArr: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    visible(val) {
      val && this.getInitData()
    }
  },
  data() {
    return {
      form: {
        treeAddress: undefined
      },
      deptOptions: [],
      visible: false,
      rules: {
        treeAddress: [{ required: true, message: '地址不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    getInitData() {
      getAddressTree().then((response) => {
        this.deptOptions = [response.data]
      })
    },
    onTreeSelect(node) {
      this.form.treeAddress = node.value
      console.log(node.value)
    },
    normalizer(node) {
      if (node.children === null || node.children === 'null' || (node.children && !node.children.length)) {
        delete node.children
      }
      const nodeResult = {
        id: node.value,
        label: node.node,
        children: node.children,
        level: node.level,
        label: node.label
      }
      if (nodeResult.level !== 5) {
        nodeResult.isDisabled = true
      }
      return nodeResult
    },
    onClose() {
      this.visible = false
      this.resetForm()
      setTimeout(() => {
        this.clearValidate()
      }, 0)
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.doSave()
        }
      })
    },
    async doSave() {
      const res = await getAddressRegion({
        code: this.form.treeAddress
      })
      if (res.code === 200) {
        console.log(res)
        this.onClose()
        this.$emit('updateAddress', {
          ...res.data,
          tableIndex: this.currentRow.tag
        })
      }
    },
    onOpen() {
      this.visible = true
    },
    resetForm() {
      Object.assign(this.form, this.$options.data().form)
    },
    clearValidate() {
      this.$refs.form.clearValidate()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>