<template>
  <el-container class="fullheight" style="border: 1px solid #eee">
    <el-aside width="200px" style="border-right: 1px solid #eee">
      <div class="tree-header flex">
        <el-input placeholder="请输入" v-model="filterText" clearable>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <div
          :class="
            isIeExplorer
              ? 'tree-button-group is-ie-explorer flex'
              : 'tree-button-group flex'
          "
        >
          <i
            :class="{'icon-zhankai': !isExpand, 'icon-shouqi': isExpand}"
            :title="isExpand ? '收起' : '展开'"
            @click="handleExpandCollapse"
          />
          <i
            class="icon-sync"
            :class="{'icon-spin': loading}"
            title="刷新"
            @click="refresh"
          />
        </div>
      </div>
      <el-tree
        :default-expand-all="defaultExpandAll"
        :data="treeData"
        :props="props"
        :load="loadNode"
        :filter-node-method="filterNode"
        :default-checked-keys="defaultCheckedKeys"
        node-key="id"
        @node-click="handleNodeClick"
        lazy
        ref="tree"
        highlight-current
        style="background: #fafafa"
      >
        <span class="custom-tree-node" slot-scope="{node}">
          <div>
            <i class="el-icon-s-order icon"></i>
            <span style="padding-left: 4px">{{ node.label }}</span>
          </div>
        </span></el-tree
      >
    </el-aside>
    <!-- <el-container v-if="!editMenuFormVisible">
      <div class="form-empty">请选择一个菜单进行操作</div>
    </el-container> -->
    <el-container style="margin-left: 10px">
      <at-table
        @load="loadData"
        :data="data"
        :page-result="pageResult"
        ref="AtTable"
        :dialogTitle="dialogTitle"
        :dialogVisible="dialogVisible"
        @select-all="handleSelect"
        @select="handleSelect"
        @handleDialogCancel="handleDialogCancel"
        @handleDialogClose="handleDialogClose"
        @handleDialogSubmit="handleDialogSubmit"
        @row-dblclick="handleRowDBClick"
      >
        <template v-slot:searchInput>
          <el-form
            ref="searchForm"
            :model="searchForm"
            label-width="80px"
            class="search-top"
            @submit.native.prevent
          >
            <!-- <project-info-selector
              v-model="searchForm.projectId"
              style="width: 100%"
            ></project-info-selector> -->
            <el-input
              v-model="searchForm.name"
              clearable
              placeholder="请输入名称"
              @keyup.enter.native="findinfo"
            ></el-input>
            <el-button
              size="small"
              @click="findinfo"
              type="primary"
              class="el-icon-search search-btn"
              >查询</el-button
            >
            <el-button
              size="small"
              @click="handleReset"
              type="primary"
              plain
              class="el-icon-refresh"
              >重置</el-button
            >
          </el-form>
        </template>
        <template v-slot:operationBtn>
          <el-button
            size="small"
            type="primary"
            @click="handleAdd"
            icon="el-icon-plus"
            >添加</el-button
          >
          <ht-delete-button
            :url="deleteUrl"
            :requestMethod="'POST'"
            :htTable="$refs.AtTable"
            @after-delete="afterDelete"
            >删除</ht-delete-button
          >
        </template>
        <template>
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column type="index" label="序号" width="55" align="center">
          </el-table-column>
          <el-table-column prop="code" label="编码" align="center">
          </el-table-column>
          <el-table-column prop="name" label="名称" align="center">
          </el-table-column>
          <el-table-column prop="pcode" label="父级编码" align="center">
          </el-table-column>
          <el-table-column prop="pname" label="父级名称" align="center">
          </el-table-column>
          <ht-table-column
            prop="finishStatus"
            label="状态"
            :show-overflow-tooltip="true"
            :filters="getDictData('mlgl-jdzt')"
          >
            <template v-slot="{row}">
              {{ getDictName('mlgl-jdzt', row.finishStatus) }}
            </template>
          </ht-table-column>
          <ht-table-column
            prop="groupType"
            label="类型"
            :show-overflow-tooltip="true"
            :filters="getDictData('mlgl-fzlx')"
          >
            <template v-slot="{row}">
              {{ getDictName('mlgl-fzlx', row.groupType) }}
            </template>
          </ht-table-column>
        </template>
        <template v-slot:dialogContent>
          <el-form
            ref="form"
            v-form
            data-vv-scope="form"
            :model="form"
            :rules="rules"
            label-width="110px"
            v-if="dialogVisible"
            v-loading.fullscreen="loading"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="名称" prop="name">
                  <el-input
                    v-model="form.name"
                    placeholder="请输入名称"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="编码" prop="code">
                  <el-input
                    v-model="form.code"
                    v-pinyin="form.name"
                    placeholder="请输入编码"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="状态" prop="finishStatus">
                  <dict-select
                    dictCode="mlgl-jdzt"
                    :hasDefaultOption="true"
                    clearable
                    v-model="form.finishStatus"
                    style="width: 100%"
                    @select="(val, obj) => handleDict(val, obj, 'mlgl-jdzt')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="分组类型" prop="groupType">
                  <dict-select
                    dictCode="mlgl-fzlx"
                    :hasDefaultOption="true"
                    clearable
                    v-model="form.groupType"
                    style="width: 100%"
                    @select="(val, obj) => handleDict(val, obj, 'mlgl-fzlx')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="父级名称" prop="pname">
                  <el-select v-model="form.pname" placeholder="请选择父级名称">
                    <el-option
                      v-for="item in options"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="父级编码" prop="pcode">
                  <el-input
                    v-model="form.pcode"
                    v-pinyin="form.pname"
                    placeholder="请输入父级编码"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="前置路由地址" prop="target">
                  <el-input
                    v-model="form.target"
                    placeholder="请输入前置节点路由地址"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="后置节点" prop="ptarget">
                  <el-input
                    v-model="form.ptarget"
                    placeholder="请输入后置节点"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="后置路由地址" prop="targetUrl">
                  <el-input
                    v-model="form.targetUrl"
                    placeholder="请输入后置节点路由地址"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="超时提醒时限" prop="timeoutPeriod">
                  <el-input
                    type="number"
                    v-model="form.ptimeoutPeriod"
                    placeholder="请输入超时提醒时限"
                    clearable
                  >
                    <i slot="suffix">天</i>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="超时提醒间隔"
                  prop="timeoutReminderInterval"
                >
                  <el-input
                    type="number"
                    v-model="form.timeoutReminderInterval"
                    placeholder="请输入超时提醒间隔"
                    clearable
                  >
                    <i slot="suffix">分钟</i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="超时提醒方式" prop="timeoutReminderType">
                  <dict-select
                    dictCode="mlgl-cstxfs"
                    :hasDefaultOption="true"
                    clearable
                    v-model="form.timeoutReminderType"
                    style="width: 100%"
                    @select="(val, obj) => handleDict(val, obj, 'mlgl-cstxfs')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="超时提醒任务状态" prop="timeoutTaskStatus">
                  <!-- <el-input
                    v-model="form.timeoutTaskStatus"
                    placeholder="请输入超时提醒任务状态"
                    clearable
                  ></el-input> -->
                  <el-switch
                    v-model="form.timeoutTaskStatus"
                    :active-value="1"
                    :inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  >
                  </el-switch>
                  {{ form.timeoutTaskStatus == 1 ? '开' : '关' }}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </at-table>
    </el-container>
  </el-container>
</template>

<script>
import projectArr from '@/assets/data.json'
export default {
  data() {
    return {
      filterText: '',
      isIeExplorer: false,
      defaultExpandAll: true,
      isExpand: false,
      loading: false,
      treeData: [],
      props: {
        label: 'name',
        code: 'code',
        id: 'id',
        children: 'children',
        pcode: 'pcode',
        isLeaf: 'leaf', // 指定节点是否为叶子节点，仅在指定了 lazy 属性的情况下生效
      },
      editMenuFormVisible: false,
      searchForm: {
        name: '',
      }, //顶部搜索参数
      data: [], //表格数据
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      form: {
        name: '',
        code: '',
        pname: '',
        pcode: '',
      },
      dialogVisible: false,
      dialogTitle: '添加',
      indexArr: [],
      node: '',
      resolve: '',
      treeData: [],
      nodeKey: false,
      pCode: 'root',
      loading: false,
      arrPcode: [{name: '目录管理', code: 'root'}],
      options: [],
      defaultCheckedKeys: [],
      rules: {
        name: {
          required: true,
          message: '请输入名称',
          trigger: 'blur',
        },
        code: {
          required: true,
          message: '请输入编码',
          trigger: 'blur',
        },
        finishStatus: {
          required: true,
          message: '请选择状态',
          trigger: 'blur',
        },
        groupType: {
          required: true,
          message: '请选择分组类型',
          trigger: 'blur',
        },
        pname: {
          required: true,
          message: '请选择父级名称',
          trigger: 'blur',
        },
        pcode: {
          required: true,
          message: '请输入父级编码',
          trigger: 'blur',
        },
        target: {
          required: true,
          message: '请输入前置路由地址',
          trigger: 'blur',
        },
        ptarget: {
          required: true,
          message: '请输入后置节点',
          trigger: 'blur',
        },
        targetUrl: {
          required: true,
          message: '请输入后置节点路由地址',
          trigger: 'blur',
        },
      },
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    defaultCheckedKeys(val) {
      this.$refs.tree.setCheckedKeys(val)
    },
  },
  mounted() {
    if (!!window.ActiveXObject || 'ActiveXObject' in window) {
      this.isIeExplorer = true
    }
  },
  computed: {
    deleteUrl: function () {
      return (
        window.context.yhxt +
        '/biz/projectManagement/directoryManagement/v1/delete'
      )
    },
  },
  created() {
    this.getOptions()
  },
  methods: {
    handleReset() {
      this.searchForm.name = ''
      this.$refs['searchForm'].resetFields()
      this.$refs.AtTable.load()
    },
    getOptions() {
      let param = {
        pageBean: {
          page: -1,
          pageSize: 10,
          showTotal: true,
        },
        querys: [
          {
            property: 'bdm.PCODE_',
            value: this.pCode,
          },
        ],
      }
      this.$http
        .post(
          '${cqxy}/biz/projectManagement/directoryManagement/v1/queryChildNodeByPage',
          param
        )
        .then((resp) => {
          let response = resp.data.value
          this.options = response.rows
        })
    },
    filterNode(value, data) {
      if (!value) return true
      return data[this.props.label].indexOf(value) !== -1
    },
    // 树状菜单的全部展开和收起
    handleExpandCollapse() {
      let elTree = this.$refs.tree
      for (var i = 0; i < elTree.store._getAllNodes().length; i++) {
        elTree.store._getAllNodes()[i].expanded = this.isExpand
      }
      this.isExpand = !this.isExpand
    },
    refresh() {
      this.loading = true
      this.$emit('refresh', () => {
        this.loading = false
        this.isExpand = this.defaultExpandAll
      })
      setTimeout(() => {
        this.loading = false
        this.isExpand = this.defaultExpandAll
      }, 5000)
    },
    loadNode(node, resolve) {
      //暂存
      if (node.level === 0) {
        this.node = node
        this.resolve = resolve
        return resolve(this.arrPcode)
      } else {
        //获取子节点
        this.getPcode(node.data.code, resolve)
      }
    },
    getPcode(data, resolve) {
      let formData = new FormData()
      formData.append('pCode', data)
      this.$http
        .post(
          '${cqxy}/biz/projectManagement/directoryManagement/v1/getByParentId',
          formData
        )
        .then((res) => {
          let data = []
          res.data.value.forEach((item) => {
            if (item.hasChildre == '1') {
              data.push({
                name: item.name,
                code: item.code,
                pname: item.pname,
                id: item.id,
              })
            } else {
              data.push({
                name: item.name,
                code: item.code,
                pname: item.pname,
                id: item.id,
                leaf: true, //没有子节点时为true
              })
            }
          })
          resolve(data)
        })
    },
    //点击节点
    handleNodeClick(data) {
      this.nodeKey = false
      this.editMenuFormVisible = true
      this.pCode = data.code
      if (this.pCode == 'root') {
        this.$refs.AtTable.load()
        // return false
      }
      if (this.$refs.AtTable) {
        if (data.leaf) {
          this.$message.info('没有下一级目录了')
        } else {
          this.$refs.AtTable.load()
        }
      }
    },
    handleAdd() {
      this.dialogTitle = '添加'
      this.form = {
        name: '',
        code: '',
        pname: this.options[0].code, //父级名称
        pcode: '',
        finishStatus: 1, //状态
        groupType: 1, //分组类型
        timeoutReminderType: 1, //超时提醒方式
        timeoutTaskStatus: 1, //超时提醒任务状态
      }
      this.dialogVisible = true
    },
    handleRowDBClick(data) {
      this.form = data
      this.dialogTitle = '修改'
      this.dialogVisible = true
    },
    //字典回调
    handleDict(val, obj, str) {
      if (str === 'mlgl-jdzt') {
      } else if (str === 'mlgl-fzlx') {
      }
    },
    afterDelete() {
      this.nodeKey = true
      this.node.childNodes = []
      this.loadNode(this.node, this.resolve)
    },
    handleSelect(selection) {
      this.indexArr = selection
    },
    handleDialogCancel() {
      this.dialogVisible = false
    },
    handleDialogClose() {
      this.dialogVisible = false
    },
    handleDialogSubmit() {
      this.form.pcode = this.pCode
      if (this.data.length !== 0) {
        this.form.pname = this.data[0].pname
      }
      if (!this.form.pname) {
        this.form.pname = 'root'
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$http
            .post(
              '${cqxy}/biz/projectManagement/directoryManagement/v1/save',
              this.form
            )
            .then((res) => {
              if (res.data.state) {
                this.$refs.form.resetFields()
                this.$message.success(res.data.message)
                this.dialogVisible = false
                this.$refs.AtTable.load()
                this.node.childNodes = []
                this.loadNode(this.node, this.resolve)
              } else {
                this.$message.error(res.data.message)
              }
              this.loading = false
            })
        }
      })
    },
    loadData(param, cb) {
      let pcode = [
        {
          property: 'bdm.PCODE_',
          value: this.pCode,
        },
      ]
      if (param.querys && param.querys.length) {
        param.querys.push(...pcode)
      } else {
        param.querys = pcode
      }
      let obj = this.searchObj
      for (let i in obj) {
        if (obj[i] && obj[i] !== undefined) {
          param.querys.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: obj[i],
          })
        }
      }
      this.$http
        .post(
          '${cqxy}/biz/projectManagement/directoryManagement/v1/queryChildNodeByPage',
          param
        )
        .then(
          (resp) => {
            let response = resp.data.value
            this.data = response.rows
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            }
          },
          (error) => {
            reject(error)
          }
        )
        .finally(() => {
          if (cb) {
            cb()
          }
        })
    },
    findinfo() {
      let query = []
      query.push({
        property: 'bdm.PCODE_',
        value: this.pCode,
      })
      let search = {
        // project_id_: this.searchForm.projectId,
        name_: this.searchForm.name,
      }
      this.searchObj = search
      for (let i in search) {
        if (search[i]) {
          query.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: search[i],
          })
        }
      }
      let data = {
        pageBean: {
          page: 1,
          pageSize: 20,
          showTotal: true,
        },
        querys: query,
      }
      this.$http
        .post(
          '${cqxy}/biz/projectManagement/directoryManagement/v1/queryChildNodeByPage',
          data
        )
        .then((resp) => {
          let response = resp.data.value
          this.data = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total,
          }
        })
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/common.scss';
.form-empty {
  position: absolute;
  text-align: center;
  width: 300px;
  font-size: 20px;
  top: 200px;
  left: 50%;
  margin-left: -150px;
  color: rgba(0, 0, 0, 0.5);
}
div.tree-header {
  min-height: 30px;
  /deep/ .el-input--small .el-input__inner {
    border: none;
  }
}
div.tree-header >>> .el-input__inner {
  border-width: 0;
  padding-right: 0;
}
div.tree-button-group i {
  cursor: pointer;
  display: inline;
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}
div.tree-button-group i:hover {
  color: lightcoral;
}
.tree-button-group {
  margin-left: 10px;
}
.is-ie-explorer {
  margin-right: 25px;
}
.flex {
  display: flex;
}
</style>
