<template>
  <div class="regions">
    <p-card title="地理区域">
      <div class="btnlist" slot="extra">
        <p-button type="primary" @click="showModal">新增</p-button>
        <p-button type="primary" style="margin-left: 5px" @click="delBatchDetail">批量删除</p-button>
      </div>
      <a-row class="content" :gutter="8">
        <a-col class="regions-tree" :span="4">
          <p-spin :spinning="spinning">
            <p-tree
              class="tree-a"
              ref="tree"
              :expandedKeys.sync="expandedKeys"
              :selectedKeys.sync="selectedKeys"
              @select="onselect"
              :replaceFields="{ key: 'regionsId', title: 'regionsName' }"
              :tree-data="dataTree"
            >
            </p-tree>
          </p-spin>
        </a-col>

        <a-col :span="20">
          <p-table
            ref="logTable"
            :columns="columns"
            :data-source="data"
            :row-selection="rowSelection"
            row-key="regionsId"
            :loading="loading"
            bordered
          >
            <div slot="action" href="javascript:;" slot-scope="text">
              <a slot="action" style="margin: 0 5px" @click.stop="edit(text)">修改</a><a-divider type="vertical" />
              <a slot="action" style="margin: 0 5px" @click.stop="deleteOne(text)">删除</a>
            </div>
          </p-table>
        </a-col>
      </a-row>
      <div>
        <p-modal
          :title="Title"
          :visible="visible"
          :enlargeable="false"
          :draggable="true"
          :maskClosable="false"
          @cancel="handleCancel"
          :footer="null"
        >
          <div>
            <p-grid-form
              ref="formdetail"
              :items="detailFormItems"
              :span="20"
              :labelCol="{ span: 10 }"
              @submit="
                ($event, form) => {
                  formSubmit($event, form, 'formdetail')
                }
              "
            />
            <div style="text-align: right">
              <p-button type="primary" @click="addForm">保存</p-button>
            </div>
          </div>
        </p-modal>
      </div>
    </p-card>
  </div>
</template>
<script>
import { tableColumnsConfig, detailFormItems } from './js/config'
import { getTree, queryRegion, addDetail, delDetail, editDetail, delBatchDetail, regionInfo } from './api/index'

export default {
  data() {
    return {
      expandedKeys: ['100000'],
      selectedKeys: [],
      data: [],
      columns: tableColumnsConfig,
      dataTree: [
        {
          regionsName: '中国',
          regionsId: '100000',
          isLeaf: false,
          levelId: '0',
          children: [],
        },
      ],
      visible: false,
      detailFormItems: detailFormItems(this),
      Title: '',
      fatherId: '',
      fatherName: '',
      isDisabled: null,
      selectedRows: [],
      loading: false,
      spinning: false,
    }
  },
  watch: {},
  created() {
    this.getTree()
  },
  computed: {
    rowSelection() {
      let _this = this
      return {
        onSelectAll(selected, selectedRows, changeRows) {
          var checked = selected
          var key = changeRows.map((item) => item.id)
        },
        onSelect(record, selected, selectedRows, nativeEvent) {
          var checked = selected
          var key = record.id
          console.log(selectedRows, 'selectedRows')
        },
        onChange(selectedRowKeys, selectedRows) {
          _this.selectedRows = selectedRowKeys
          console.log(selectedRowKeys)
        },
      }
    },
  },
  methods: {
    //初始加载树形列
    getTree() {
      this.spinning = true
      const id = '100000'
      getTree({ regionId: id }).then((res) => {
        if (res.success) {
          const listData = res.data
          this.dataTree[0].children = listData
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    //点击树事件
    onselect(record, selected) {
      if (record.length > 0) {
        this.fatherName = selected.node.title
        this.fatherId = record[0]
        this.loading = true
        queryRegion({ fatherId: this.fatherId }).then((res) => {
          this.loading = false
          if (res.success) {
            this.data = res.data
          }
        })
      }
    },
    //右边table
    getList(test) {
      this.fatherId = test
      this.loading = true
      queryRegion({ fatherId: this.fatherId })
        .then((res) => {
          if (res.success) {
            this.data = res.data
            this.loading = false
          } else {
            this.loading = false
          }
        })
        .catch((err) => {
          this.loading = false
        })
    },
    //打开新增modal
    showModal() {
      if (!this.fatherId) {
        this.$message.success('请选择地区再进行新增')
      } else {
        this.Title = '新增区域'
        this.visible = true
        this.isDisabled = true
        const father = { fatherId: this.fatherId, fatherName: this.fatherName }
        this.$nextTick(() => {
          const { form } = this.$refs.formdetail
          form.resetFields()
          form.setFieldsValue(father)
        })
      }
    },
    //关闭弹框
    handleCancel(e) {
      this.visible = false
      this.$refs.formdetail.form.resetFields()
    },
    //弹框表单保存
    addForm() {
      if (this.isDisabled) {
        const { form } = this.$refs.formdetail
        form.validateFields((error, values) => {
          if (!error) {
            const params = form.getFieldsValue()
            this.loading = true
            addDetail(params).then((res) => {
              if (res.success) {
                this.visible = false
                this.$nextTick(() => {
                  this.$message.success(res.message)
                  this.getList(params.fatherId)
                  this.getTree()
                })
              } else {
                this.$message.success(res.message)
              }
            })
          }
        })
      } else {
        this.$nextTick(() => {
          const { form } = this.$refs.formdetail
          this.loading = true
          form.validateFields((error, params) => {
            if (!error) {
              editDetail(params).then((res) => {
                if (res.success) {
                  this.visible = false
                  this.$nextTick(() => {
                    this.$message.success(res.message)
                    this.getList(params.fatherId)
                    this.getTree()
                  })
                } else {
                  this.loading = false
                  this.$message.success(res.message)
                }
              })
            }
          })
        })
      }
    },
    //修改区域
    edit(text) {
      this.Title = '编辑区域信息'
      this.visible = true
      this.isDisabled = false
      this.$nextTick(() => {
        const { form } = this.$refs.formdetail
        form.setFieldsValue({ fatherName: this.fatherName })
      })
      regionInfo({ regionId: text.regionsId }).then((res) => {
        this.$refs.formdetail.form.setFieldsValue(res.data)
      })
    },
    //删除单条数据
    deleteOne(text) {
      this.$confirm({
        title: '确定是否要删除?',
        content: '',
        onOk: () => {
          this.loading = true
          delDetail({ id: text.regionsId }).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.getList(text.fatherId)
              this.getTree()
            } else {
              this.$message.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
    //批量删除
    delBatchDetail() {
      if (this.selectedRows.length < 1) {
        this.$message.error('请至少选择一条数据！')
        return
      }
      this.$confirm({
        title: '确定是否要删除?',
        content: '',
        onOk: () => {
          this.loading = true
          delBatchDetail({ ids: this.selectedRows })
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.getList(this.fatherId)
                this.getTree()
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(() => console.log('Oops errors!'))
        },
        onCancel() {},
      })
    },
  },
}
</script>
<style lang="less" scoped>
.regions {
  // .content {
  //   position: relative;
  //   height: calc(100vh - 275px);
  //   overflow: auto;
  //   .ant-table-placeholder {
  //     border-bottom: 0;
  //   }
  // }
  .regions-tree {
    position: relative;
    height: 450px;
    overflow: auto;
  }
  .tree-a {
    min-height: 450px;
  }
}
</style>
