<template>
  <el-dialog
    :title="title"
    :append-to-body="true"
    :modal-append-to-body="falseValue"
    :close-on-click-modal="falseValue"
    :visible.sync="showDialog"
    :modal="falseValue"
    custom-class="dialog-style list-dialog"
    width="1000px"
    @close="dialogClose"
    v-el-drag-dialog
    v-el-dialog-center
  >
    <div id="containt">
      <div class="detail-wrap">
        <el-form ref="editForm" :model="formData">
          <div class="d-header clearfix">
            <div class="fl">
              <i class="el-icon-info"/>
              {{ title }}
            </div>
            <div class="fr">
              <el-button type="primary" class="button-sty" icon="el-icon-check" @click="saveData">{{ $t1('保存') }}
              </el-button>
            </div>
          </div>
          <baseTabs>
            <baseTabPane :label="$t1('基本信息')">
              <template #default>
                <table class="table-detail">
                  <tbody>
                  <tr>
                    <th>
                      <em class="f-red">*</em>
                      {{ $t1('属性名') }}
                    </th>
                    <td>
                      <el-radio-group v-model="formData.type">
                        <el-radio label="attribute01">{{ $t1('偏远地区') }}</el-radio>
                      </el-radio-group>
                    </td>
                  </tr>
                  <tr>
                    <th>
                      <em class="f-red">*</em>
                      {{ $t1('属性值') }}
                    </th>
                    <td>
                      <template v-if="formData.type=='attribute01'">
                        <el-form-item prop="attribute01" :rules="[{ required: true, trigger: 'blur' }]">
                          <el-radio-group v-model="formData.attribute01">
                            <el-radio :label="1">{{ $t1('是') }}</el-radio>
                            <el-radio :label="0">{{ $t1('否') }}</el-radio>
                          </el-radio-group>
                        </el-form-item>
                      </template>
                    </td>
                  </tr>
                  </tbody>
                </table>
              </template>
            </baseTabPane>
            <baseTabPane :label="$t1('地区信息')" v-if="modifyModel==1">
              <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"
                >
                  <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>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'formDataInfo',
  components: {},
  props: {
    modifyModel: {
      type: Number,
      default: () => 1//1 新增 2 修改
    },
    checkRows: {
      type: Array,
      default: () => []//1 新增 2 修改
    }
  },
  created() {
    this.title = this.modifyModel == 1 ? this.$t1('批量新增地区属性') : this.$t1('批量修改地区属性');
  },
  mounted() {

  },
  data() {
    return {
      showDialog: true,
      falseValue: false,
      dataId: '',
      hBtn: true,
      formData: {type: "attribute01", attribute01: null},
      vxeOption: {},
      companyInfoOption: {},
      formDataRoleOption: {},
      showContent: true,

      defaultProps: {
        label: 'name', //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: 'leaf'
      },
      expandAll: false,
      defaultExpandedNodes: [],
      defaultCheckedKeys: [],
      maxGrade: 1,
      title: ""
    };
  },
  methods: {
    saveData() {
      let modifyModel = this.modifyModel;
      let checkedDatas = [];
      if (modifyModel == 1) {
        checkedDatas = this.getCheckedDatas();
        if (!checkedDatas.length) {
          this.$message({
            message: this.$t1('请选择地区'),
            type: 'error',
            duration: 2000
          });
          return
        }
      } else {
        checkedDatas = this.$baseLodash.cloneDeep(this.checkRows);
      }
      this.$refs.editForm.$baseValidate(valid => {
        if (valid) {
          this.$baseConfirm(this.$t1('您确定要保存吗？')).then(() => {
            var url = USER_PREFIX + '/area_attribute/save';

            let requests = [];
            let field = this.formData.type;
            let value = this.formData[field];

            checkedDatas.forEach(item => {
              let reqData;
              if (modifyModel == 1) {
                reqData = {
                  name: item.name,
                  fullName: item.fullName,
                  areaId: item.id
                }
              } else {
                reqData = reqData = {
                  name: item.name,
                  fullName: item.fullName,
                  areaId: item.areaId
                };
              }
              reqData[field] = value;
              reqData.attributeName = field;
              requests.push(this.$http({
                url: url,
                method: `post`,
                data: reqData,
                isLoading: true,
                success: res => {

                }
              }));
            })
            if (requests.length) {
              Promise.all(requests)
                .then(responses => {
                  // 所有请求都成功了
                  // 处理你的数据
                  /*responses.forEach(response => {
                    console.log(response.data);
                  });*/
                  this.$message({
                    message: 'success',
                    type: 'success',
                    duration: 2000,
                    onClose: t => {

                    }
                  });
                  this.confirm();
                })
                .catch(error => {
                  // 至少一个请求失败了
                  console.error('An error occurred:', error);
                });
            }
          });
        }
      });
    },
    dialogClose() {
      this.showDialog = false
      this.$emit('update:visiable', false);
    },
    confirm() {
      this.dialogClose();
      this.$emit('confirm');
    },
    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;
    },
    loadNode(node, resolve) {
      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;
      }
      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 && data.checked) {
              this.defaultCheckedKeys.push(item.id);//展开第二级节点
            }

          });
          resolve(rows)
        }
      });

    },
    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();
    }
  }
};
</script>
