<template>
  <div class="detail-wrap">
    <el-form ref="editForm" :model="formData">
      <div class="d-header clearfix">
        <div class="fl">
          <i class="el-icon-info"/>
          {{ $t1('设置地区属性（请勾选需要设置的‘{attributeName}’）', {attributeName}) }}
        </div>
        <div class="fr">
          <el-button type="primary" plain class="button-sty" @click="$baseReload()" icon="el-icon-refresh-right">
            {{ $t1('重置') }}
          </el-button>
          <el-button type="primary" class="button-sty" icon="el-icon-check" @click="saveData">{{ $t1('保存') }}
          </el-button>
        </div>
      </div>
      <baseTabs :showNav="false">
        <baseTabPane :label="$t1('地区信息')">
          <template #default>
            <el-tree
              :props="defaultProps"
              :load="loadNode"
              node-key="id"
              ref="tree"
              highlight-current
              lazy
              :expand-on-click-node="false"
              class="tree-checkbox t-check2"
              icon-class="el-icon-arrow-down"
              show-checkbox
              :check-on-click-node="true"
              @check-change="handleCheckChange"
              :check-strictly="true"
              :default-checked-keys="defaultCheckedKeys"
              :default-expanded-keys="defaultExpandedNodes"
            >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ node.label }}</span>
                    <span v-if="node.level==1" @click.stop>
                      ( <el-checkbox v-model="data.checked" :indeterminate="data.indeterminate" @change="(val)=>{
                        changeCheckAll(node,val)
                      }">{{ $t1('下级全选') }}</el-checkbox> )
                    </span>
                  </span>
            </el-tree>
          </template>
        </baseTabPane>
      </baseTabs>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'areaAttributeEdit',
  props: {
    attributeCode: {
      type: String,
      default: () => null
    },
    attributeName: {
      type: String,
      default: () => null
    }
  },
  created() {

  },
  mounted() {

  },
  watch: {},
  data() {
    return {
      attributeValue: false,
      formData: {attributeCode: null, areaIds: []},
      showContent: true,
      defaultProps: {
        label: 'name', //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: 'leaf'
      },
      expandAll: false,
      defaultExpandedNodes: [],
      defaultCheckedKeys: [],
      maxGrade: 1,
      title: ""
    };
  },
  methods: {
    saveData() {
      let checkedDatas = this.getCheckedDatas();
      if (!checkedDatas.length) {
        this.$message({
          message: this.$t1('请选择地区'),
          type: 'error',
          duration: 2000
        });
        return
      }
      this.$baseConfirm(this.$t1('您确定要保存吗？')).then(() => {
        var url = USER_PREFIX + '/area_attribute/saveValue';
        let areaIds = checkedDatas.map(item => item.id);
        this.$http({
          url: url,
          method: `post`,
          data: {
            attributeValue: "1",
            attributeCode: this.attributeCode,
            areaIds: areaIds
          },
          isLoading: true,
          success: res => {
            this.$message({
              message: res.content,
              type: 'success',
              duration: 500,
              onClose: t => {
                this.$baseReload();
              }
            });
          }
        })
      });
    },
    dialogClose() {
      this.showDialog = false
      this.$emit('update:visiable', false);
    },
    handleNodeClick(data, node, v) {

    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
      let node = this.$refs.tree.getNode(data.id + '');
      if (node.level == 1 && !node.childNodes.length) {
        node.expand();
      }
      if (node.level == 2) {
        let parentNode = node.parent;
        let parentData = parentNode.data;
        let pNodes = parentNode.childNodes;
        let pNodeSize = pNodes.length;
        let checkedKeys = this.$refs.tree.getCheckedKeys();
        let pCheckNodes = pNodes.filter(pNode => {
          return checkedKeys.includes(pNode.data.id)
        });
        let pCheckNodeSize = pCheckNodes.length;
        if (pCheckNodeSize) {
          if (pCheckNodeSize < pNodeSize) {
            parentData.checked = false;
            parentData.indeterminate = true;
          } else {
            parentData.checked = true;
            parentData.indeterminate = false;
          }
        } else {
          parentData.checked = false;
          parentData.indeterminate = false;
        }
      }
    },
    getCheckedDatas() {
      let checkDatas = this.$refs.tree.getCheckedNodes(false, true);
      return checkDatas;
    },
    async loadNode(node, resolve) {
      if (node.level == 0) {
        await this.initAttributeValueList();
      }
      this.getTreeData(node, resolve)
    },
    getTreeData(node, resolve) {
      let data = node.data;
      // this.defaultExpandedNodes = [];
      let id = data && data.id ? data.id : null;
      let url = USER_PREFIX + '/area/getChildren';
      let maxGrade = this.maxGrade;
      let currentGrade = 0;
      if (data && data.id) {
        currentGrade = data.grade + 1;
      }
      let defaultCheckedKeys = this.defaultCheckedKeys;
      this.$http({
        url: url,
        method: 'post',
        data: {
          id: id
        },
        success: res => {
          let rows = res.objx || [];
          rows.forEach(item => {
            item.grade = currentGrade;
            item.leaf = currentGrade >= maxGrade;
            item.checked = false;
            item.indeterminate = false;
            if (!id) {
              this.defaultExpandedNodes.push(item.id);
            }
          });
          resolve(rows)
          let rowSize = rows.length;
          if (id && data && rowSize) {
            let checkRows = rows.filter(row => {
              return defaultCheckedKeys.includes(row.id);
            });
            let checkRowSize = checkRows.length;
            if (checkRowSize) {
              if (rowSize == checkRowSize) {
                data.checked = true;
              } else {
                data.indeterminate = true;
              }
            }
          }
        }
      });

    },
    changeCheckAll(node, val) {
      let childNodes = node.childNodes
      let $tree = this.$refs.tree;
      if (childNodes.length) {
        childNodes.forEach(childNode => {
          this.$refs.tree.setChecked(childNode.data, val)
        })
      }
      node.expand();
    },
    initAttributeValueList() {
      return this.$http({
        url: USER_PREFIX + '/area_attribute/getValueList',
        method: `post`,
        data: {
          stringOne: this.attributeCode
        },
        isLoading: true,
        success: res => {
          let rows = res.objx || [];
          this.defaultCheckedKeys = rows.map(row => row.areaId);
        }
      });
    }
  }
}
;
</script>
