<template>
  <el-dialog title="设置区域" width="700px" class="dialog-width" :visible="dialogFormVisibleT" :modal-append-to-body="true"
    append-to-body :close-on-click-modal="false" @close="cancelForm">
    <section>
      <el-tree :data="data" show-checkbox node-key="regionCode" :props="defaultProps" ref="tree" @check="areaOnCheck">
      </el-tree>
    </section>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelForm()">取 消</el-button>
      <el-button type="primary" @click="submitForm()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { arealistApi } from '@/api/distribution';
export default {
  props: ['visible', 'multipleSelection'],
  components: {
  },
  data() {
    return {
      dialogFormVisibleT: this.visible,
      listLoading: false,
      data: [],
      defaultProps: {
        children: 'childrenList',
        label: 'regionName'
      }
    }
  },
  watch: {
    visible() {
      this.dialogFormVisibleT = this.visible
    }
  },

  mounted() {
    this.getList()
  },

  methods: {
    search() {
      this.getList()
    },

    getList() {
      this.listLoading = true;
      arealistApi().then(res => {
        let allRegion = {
          childrenList: [],
          parentCode: 'all',
          regionCode: 'all',
          regionName: '全国'
        };
        this.data = [ allRegion, ...res ];
        this.listLoading = false;

        // 编辑时且只选择一条记录，回显已选择的关联区域
        if (this.multipleSelection.length === 1) {
          let regionCodes = [];
          this.multipleSelection[0].regionList.forEach(item => {
            regionCodes.push(item.regionCode);
          });
          this.$refs.tree.setCheckedKeys(regionCodes);
        }
      }).catch(() => {
        this.listLoading = false;
      });
    },

    areaOnCheck(node) {
      if (node.regionCode === 'all') {
        this.$refs.tree.setCheckedKeys(['all']);
      } else {
        let treelist = this.$refs.tree.getCheckedNodes();
        let regionCodes = [];
        treelist.forEach(item => {
          item.regionCode !== 'all' ? regionCodes.push(item.regionCode) : null;
        });
        this.$refs.tree.setCheckedKeys(regionCodes);
      }
    },

    submitForm() {
      console.log(this.$refs.tree.getCheckedNodes());
      let treelist = this.$refs.tree.getCheckedNodes();
      this.multipleSelection.forEach(item => {
        item.regionList = this.$refs.tree.getCheckedNodes()
      })
      this.$emit('areaMultipleSelection', this.multipleSelection);
      this.cancelForm();
    },

    cancelForm() {
      //取消关闭
      this.$emit("update:visible", false);
      this.$nextTick(() => {
        // this.$refs.ruleForm.resetFields(); //重置输入框提示
      });
    },
  }
}
</script>
<style scoped lang="scss">
.dialog-width {

  //弹出层里内容的高度
  ::v-deep .el-dialog__body {
    max-height: 500px !important;
    overflow: auto;
  }

}
</style>