<template>
  <div class="house-list">
    <tables
      :buttonList="buttonList"
      :data-api="dataApi"
      :delete-api="deleteApi"
      deleteIdKey="id"
      :columns="columns"
      @create="create"
      placeholder="上级区域/区域"
      ref="table"
      @toEdit="toEdit"
    />
    <CModal :show="show==='create'" title="新增地址" :width="420" @submit="createAddress" @close="show=''">
      <createForm :form="form" v-if="show==='create'" />
    </CModal>
    <CModal :show="show==='edit'" title="编辑地址" :width="420" @submit="editAddress" @close="show=''">
      <createForm :form="form" v-if="show==='edit'" isEdit />
    </CModal>
  </div>
</template>

<script>
import tables from 'components/tables'
import { fetchCityList, createCity, deleteRegion, updateRegion } from 'api/region'
import createForm from './components/create'
import CModal from 'components/Modal'
const regionMap = {
  0: '国家',
  1: '省份',
  2: '城市',
  3: '区县',
  4: '街道'
}
export default {
  data() {
    return {
      show: '',
      buttonList: [
        {
          text: '新增',
          handle: 'create'
        }
      ],
      dataApi: fetchCityList,
      deleteApi: deleteRegion,
      columns: [
        {
          type: 'index',
          title: '序号',
          align: 'center',
          width: 80
        },
        {
          title: '上级区域',
          key: 'parent_name',
          align: 'center'
        },
        {
          title: '区域',
          key: 'name',
          align: 'center'
        },
        {
          title: '类型',
          key: 'type',
          align: 'center',
          render: (h, params) => {
            return h('span', regionMap[params.row.type])
          }
        },
        {
          title: '操作',
          slot: 'action',
          tools: ['edit', 'del' ],
          align: 'center'
        }
      ],
      form: {
        type: '',
        parent_id: '0'
      }
    }
  },
  components: {
    tables,
    createForm,
    CModal
  },
  methods: {
    create () {
      this.form = {
        parent_id: '0'
      }
      this.show = 'create'
    },
    toEdit (row) {
      this.show = 'edit'
      this.form = JSON.parse(JSON.stringify(row))
    },
    async createAddress () {
      console.log(this.form)
      await createCity(this.form)
      this.show = ''
      this.$refs['table'].handleTableData()
    },
    async editAddress () {
      await updateRegion(this.form)
      this.show = ''
      this.$refs['table'].handleTableData()
    }
  }
}
</script>

<style lang="less" scoped>
.house-list {
  padding: 20px;
  background: #252828;
}

</style>