<template>
  <div class="main-content market m20">
    <el-input v-model="filterText" placeholder="输入关键字进行过滤" />
    <el-button type="primary" size="small" style="margin-top:10px" @click="addSlice">新增</el-button>
    <el-tree
      v-if="isLoad"
      ref="tree"
      :props="props"
      :load="loadNode"
      lazy
      accordion
      :filter-node-method="filterNode"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span>{{ node.label }}</span>
<!--        <span v-if="node.data.sareaLevel === '4'" style="padding-left: 20px">-->
<!--          <el-button-->
<!--            type="text"-->
<!--            size="mini"-->
<!--            @click.stop="() => append(data)"-->
<!--          >-->
<!--            新增片区-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            type="text"-->
<!--            size="mini"-->
<!--            @click.stop="() => update(node, data)"-->
<!--          >-->
<!--            编辑-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            type="text"-->
<!--            size="mini"-->
<!--            @click.stop="() => remove(node, data)"-->
<!--          >-->
<!--            删除-->
<!--          </el-button>-->
<!--        </span>-->
      </span>
    </el-tree>
    <el-dialog
      :title="dialogType === 'add' ? '新增信息' : '编辑信息'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="30%"
    >
      <el-form ref="form" :key="'form'" v-loading="submitFormLoading" :model="form" label-width="100px" label-position="left" :rules="formRules">
        <el-form-item v-if="dialogType === 'edit'" label="上级目录">
          <el-cascader :props="dicProps" filterable :show-all-levels="false" @change="handleChange" />
        </el-form-item>
        <el-form-item label="上级名称" prop="sparentName">
          {{ form.sparentName }}
        </el-form-item>
        <el-form-item label="名称" prop="sareaName">
          <el-input v-model="form.sareaName" placeholder="名称" />
        </el-form-item>
        <div v-if="form.sparentLevel === '3' || form.sareaLevel === '4'">
          <el-form-item label="监管人员" prop="supervisorId">
            <el-select v-model="form.supervisorId" placeholder="监管人员">
              <el-option v-for="each in userOptions" :key="'supervisorId'+each.primaryKey" :value="each.primaryKey" :label="each.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="片区状态" prop="state">
            <el-radio-group v-model="form.state" size="small">
              <el-radio label="1" border>启用</el-radio>
              <el-radio label="0" border>停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <el-form-item label="说明" prop="smemo">
          <el-input v-model="form.smemo" type="textarea" placeholder="备注" :autosize="{ minRows: 5, maxRows: 10 }" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-loading="submitFormLoading" type="primary" @click="submitSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteAreaDsm,
  getAllBySareaCode,
  getDsmBySparentCode,
  getInfoBySareaCode,
  saveAreaDsm
} from '../../../api/market'
import { getSameDeptUserList } from '@/api/user'
export default {
  data() {
    return {
      isLoad: true,
      dialogVisible: false,
      dialogType: '',
      submitFormLoading: false,
      props: {
        label: 'sareaName',
        key: 'sareaCode',
        children: 'zones'
      },
      updateNode: {},
      filterText: '',
      options: [],
      form: {
        sareaCode: '',
        sareaName: '',
        sparentCode: '',
        sparentName: '',
        sparentLevel: '',
        bend: '',
        bisUnit: '',
        sunitId: '',
        sareaType: '',
        sereaUse: '',
        smainCode: '',
        sisDelete: '',
        sareaLevel: '',
        sentId: '',
        smemo: '',
        // 片区专属参数
        sliceId: '',
        sliceName: '',
        sliceAddr: '',
        supervisorId: '',
        state: '',
        remark: '',
        addRoot: false
      },
      userOptions: [],
      user: JSON.parse(sessionStorage.getItem('user')),
      formRules: {

      },
      dicProps: {
        lazy: true,
        checkStrictly: true,
        label: 'sareaName',
        value: 'sareaCode',
        lazyLoad: async(node, resolve) => {
          if (node.data) {
            resolve(await this.getDsm(node.data.sareaCode, node.data.sareaLevel))
          } else {
            resolve(await this.getDsm(this.user.orgId, null))
          }
        }
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    // 加载片区待选监督人员
    getSameDeptUserList(this.user.unitId).then(res => {
      if (res.code === 0) {
        this.userOptions = res.data || []
      }
    })
  },
  methods: {
    handleChange(value) {
      getInfoBySareaCode({ sareaCode: value[value.length - 1] }).then(res => {
        if (res.code === 0) {
          this.$set(this.form, 'sparentCode', res.data.sareaCode)
          this.$set(this.form, 'sparentName', res.data.sareaName)
          this.$set(this.form, 'sparentLevel', res.data.sareaLevel)
        }
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.sareaName.indexOf(value) !== -1
    },
    getDsm(val, sareaLevel) {
      return getDsmBySparentCode({ sparentCode: val, sareaLevel: sareaLevel }).then(res => {
        if (res.code === 0) {
          return res.data
        } else {
          return []
        }
      })
    },
    async loadNode(node, resolve) {
      console.log(node)
      if (node.level === 0) {
        return resolve(await this.getDsm(this.user.orgId, null))
      } if (node.data.sareaLevel === '5') {
        return resolve([])
      } else {
        const nodes = await this.getDsm(node.data.sareaCode, node.data.sareaLevel)
        node.childNodes = nodes
        return resolve(nodes)
      }
    },
    append(data) {
      this.addRoot = false
      this.dialogVisible = true
      this.dialogType = 'add'
      this.form = {
        sparentName: data.sareaName,
        sparentCode: data.sareaCode,
        sparentLevel: data.sareaLevel
      }
    },
    update(node, data) {
      this.addRoot = false
      this.updateNode = node
      this.dialogVisible = true
      this.dialogType = 'edit'
      getAllBySareaCode({ sareaCode: data.sareaCode }).then(res => {
        this.form = res.data
      })
    },
    remove(node, data) {
      this.addRoot = false
      this.$confirm('删除当前信息会将下属层级一并删除，是否确定继续', '提示').then(res => {
        deleteAreaDsm({ sareaCode: data.sareaCode }).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功')
            this.$refs.tree.remove(node)
          }
        })
      })
    },
    addSlice() {
      this.addRoot = true
      this.dialogVisible = true
      this.dialogType = 'add'
      this.form = {
        sparentName: '',
        sparentCode: '',
        sparentLevel: ''
      }
    },
    submitSave() {
      this.form.type = this.dialogType
      saveAreaDsm(this.form).then(res => {
        if (res.code === 0) {
          this.$message.success('保存成功')
          this.dialogVisible = false
          if (this.dialogType === 'edit') {
            const nodeOne = this.updateNode.parent
            this.$refs.tree.remove(this.updateNode)
            this.$refs.tree.append(this.form, nodeOne)
          } else if (this.dialogType === 'add') {
            if (this.addRoot) {
              this.treeReload()
            } else {
              this.$refs.tree.append(this.form, this.updateNode)
            }
          }
        }
      })
    },
    treeReload() {
      // 通过v-if控制销毁tree组件重载，以实现根节点的重载
      this.isLoad = false
      this.$nextTick(() => {
        this.isLoad = true
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-content{
    >div:not(:first-child){
        margin-top:16px;
    }
    .btn-box{
        text-align:right;
    }
    .main-body{
        // padding:16px 0;
        // border-top: 1px dashed #70AEFF;
        .header{
            .header-label{
                font-size: 20PX;
                font-family: Microsoft YaHei, Microsoft YaHei-Bold;
                font-weight: bold;
                color: #243668;
                line-height: 32px;
            }
        }
    }

}
/deep/.el-input__inner{
  height: 28px;
}
/deep/.label-name{
  text-align: right;
  width: 190px;
  font-size: $table-content-font-size;
}
.search-box{
  background:#fff!important;
  margin-bottom: 40px;
  .search-field{
      display:inline-block;
      width:80%;
      >p{
          margin:0 0 10px 0;
          font-family: Microsoft YaHei, Microsoft YaHei-Bold;
          color: #5e5e7a;
          font-size:16PX;
      }
  }
}
/deep/.search-input-box{
  width: 70%;
}

.content{
  background: #fff;
  /deep/.el-table .warning-row {
    background: #eaf4fe!important;
  }
}
</style>
