<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" class="">
      <el-form-item label="父级分类" prop="parentids">
        <el-cascader
          v-model="parentids"
          :options="provinceCityDatas"
          :props="props"
          @change="handleItemChange"
          ref="myCascader"
          :placeholder="updateForm.technologyName"
          class="form_select form_cascader"
          clearable
          change-on-select
          style="width: 100%"
          :disabled="addEditJudgment"
        />
      </el-form-item>
      <el-form-item label="行政编号" prop="code">
        <el-input v-model="ruleForm.code" placeholder="请输入行政编号"/>
      </el-form-item>
      <el-form-item label="地区" prop="areaname">
        <el-input v-model="ruleForm.areaname" placeholder="请输入地区"/>
      </el-form-item>
      <el-form-item label="排列序号" prop="sort">
        <el-input v-model.number="ruleForm.sort" placeholder="请输入排列序号"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="ruleForm.remark" type="textarea" autosize placeholder="请输入备注"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProviceCity, getProviceCityById} from "@/api/commonAPI";
import { getAreaTree, addAreaTree, editAreaTree, getAreaTreeDetail } from '@/api/systemSetup/roleSetting/areaManagement'
export default{
  name: 'AddOrEdit',
  props: {
    rowid: {
      type: Number,
      default: 0
    },
    layerid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      parentids: [],
      ruleForm: {
        parentid: '', // 父节点id
        id: '', // 当前节点id
        code: '', //行政编号
        areaname: '', //地区
        sort: '', // 序号
        remark: '', //备注
      },
      rules: {
        code: [{ 
          required: true, 
          message: '行政编号不能为空' 
        }],
        areaname: [{ 
          required: true, 
          message: '地区不能为空' 
        }],
        sort: [{ 
          required: true, 
          message: '排列序号不能为空' 
        },{ 
          type: 'number', 
          message: '排列序号必须为数字' 
        }],
      },
      updateForm: {
        technologyName: '请选择父级分类'
      },
      typeDropDatas: [], // 下拉分类
      provinceCityDatas: [],
      // 自定义菜单下拉数据的key值
      props: {
        value: 'id',
        label: 'text',
        children: "children",
        code: "code",
      },
      addEditJudgment: false
    }
  },
  created() {
    this.getProCity()
    this.getTypeDrop().then(() => {
      if (this.rowid) {
        this.addEditJudgment = true
        this.ruleForm.id = this.rowid
        this.getTypeDetails(this.rowid)
      }
    })
  },
  methods: {
    // 获取分类下拉
    getTypeDrop() {
      return new Promise(resolve => {
        getAreaTree().then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.typeDropDatas = response.data
          }
        })
        resolve()
      })
    },
    // 获取菜单详情
    getTypeDetails(rid) {
      getAreaTreeDetail(rid).then(response => {
        if (response.state.toLowerCase() === 'success') {
          const res = response.data.model
          this.ruleForm.code = res.F_Code // 行政编号
          this.ruleForm.areaname = res.F_AreaName // 地区
          this.ruleForm.sort = res.F_Sort // 排序
          this.ruleForm.remark = res.F_Remark // 备注
          this.ruleForm.parentid = res.F_ParentId // 父节点id
          let levelNameLength = response.data.levelname.length
          let levelName = response.data.levelname.splice(levelNameLength - 2, 1)
          this.updateForm.technologyName = levelName.join('/')
          // const len = response.data.levelid.length
          // const levelid = response.data.levelid
          // levelid.splice(len - 1, 1)
          // this.parentids = levelid
        }
      })
    },
    getProCity() {
      getProviceCityById(this.addressParams)
        .then(res => {
          this.provinceCityDatas = this.handleData(res.data);
        })
        .catch(err => {});
    },
    handleItemChange(val) {
      this.provinceCityText=this.$refs['myCascader'].currentLabels
      let pid = val ? val[val.length - 1] : 1; //id值
      this.level = val.length + 1; //判断第几级
      this.provinceCityDatas = this.handleData(
        this.provinceCityDatas,
        pid,
        this.level
      );
    },
    handleData(data, val, level) {
      for (let i = 0; i < data.length; i++) {
        if (!data[i].children) {
          this.$set(data[i], "children", []);
        }
        if (data[i].id === val) {
          getProviceCityById({ pid: val })
            .then(res => {
              if (res.data.length) {
                data[i].children = res.data;
                if(this.level!==4){
                  data[i].children.forEach(ele => {
                    this.$set(ele, "children", []);
                  });
                }
              } else {
                data[i].children = undefined;
              }
            })
            .catch(err => {});
        } else {
          if (data[i].children.length) {
            this.handleData(data[i].children, val,level);
          }
        }
      }
      return data;
    },
    

    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          if (!this.rowid) {
            // 添加
            if (this.parentids.length == 0) {
              this.ruleForm.parentid = 1  
            } else if (this.parentids.length > 0) {
              this.ruleForm.parentid = this.parentids[this.parentids.length - 1]
            }
            addAreaTree(this.ruleForm).then(response => {
              this.loading = false
              if (response.state.toLowerCase() === 'success') {
                this.$parent.$layer.close(this.layerid)
                this.$parent.requestNewData() // 重新加载父级数据
                this.$message.success('恭喜你，添加成功!')
              }
            }).catch(() => {
              this.loading = false
            })
            return
          }
          // 编辑
          editAreaTree(this.ruleForm).then(response => {
            this.loading = false
            if (response.state.toLowerCase() === 'success') {
              this.$parent.$layer.close(this.layerid)
              this.$parent.requestNewData() // 重新加载父级数据
              this.$parent.clearTreeclickId() //清空数据
              this.$message.success('恭喜你，编辑成功!')
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.$message.error('请输入有效的必填项信息!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form_select {
  width: 100%
}
.form_cascader input::placeholder{
  color: red;
}
</style>

