<template>
  <zj-page-container direction="row">
    <div style="min-width: 220px; height: 100%">
      <zj-page-container>
        <div class="title">
          <el-button style="margin-right: 5px" size="mini" icon="el-icon-search" @click="getTreeListData"></el-button>
          <el-input size="mini" v-model="filterText" placeholder="请输入内容"></el-input>
        </div>
        <zj-page-fill id="kakaka">
          <el-tree
            :data="treeList"
            :props="defaultProps"
            default-expand-all
            :highlight-current="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
            ref="listTree"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              {{ node.label }}
              <span>
                <el-button v-if="node.level > 1" size="mini" type="text" @click="addbumen(data)">
                  <i class="el-icon-plus"></i>
                </el-button>
                <el-button v-if="node.level > 2" size="mini" type="text" @click="eidbumen(data)">
                  <i class="el-icon-edit"></i>
                </el-button>
                <el-button v-if="node.level > 2" size="mini" type="text" @click="delbumen(data)">
                  <i class="el-icon-delete"></i>
                </el-button>
              </span>
            </span>
          </el-tree>
        </zj-page-fill>
      </zj-page-container>
    </div>
    <template-page
      ref="pageRef"
      :getList="getList"
      :columnParsing="columnParsing"
      :optionsEvensGroup="optionsEvensGroup"
      :tableAttributes="tableAttributes"
      :tableEvents="tableEvents"
      :operationColumnWidth="160"
      :operation="operation()"
      :exportList="exportList"
    >
      <el-dialog title="设置部门" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
        <el-form ref="form" :model="form" label-width="100px" size="mini">
          <el-form-item label="上级部门名称">
            <el-input disabled v-model="form.pname"></el-input>
          </el-form-item>
          <el-form-item label="部门名称">
            <el-input v-model="form.deptName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queding">确定</el-button>
            <el-button @click="handleClose">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog title="添加网点" :visible.sync="dialogVisible2" width="500px" :before-close="handleClose2">
        <el-form ref="form" :model="form2" label-width="120px" size="mini">
          <el-form-item label="部门名称">
            <el-input disabled v-model="form2.deptName"></el-input>
          </el-form-item>
          <el-form-item label="管理网点名称">
            <el-select v-if="form2.id" style="width: 100%" v-model="form2.websitId" filterable placeholder="请选择">
              <el-option
                v-for="(item, index) in keyixuan"
                :key="index"
                :label="`(${item.websitId})${item.websitName}`"
                :value="item.websitId"
              >
              </el-option>
            </el-select>
            <el-select v-else style="width: 100%" multiple v-model="form2.websitIds" filterable placeholder="请选择">
              <el-option
                v-for="(item, index) in keyixuan"
                :key="index"
                :label="`(${item.websitId})${item.websitName}`"
                :value="item.websitId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queding2">确定</el-button>
            <el-button @click="handleClose2">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </template-page>
  </zj-page-container>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import {
  adminDeptList,
  adminDeptListExport,
  adminDeptTree,
  adminDeptAdd,
  adminDeptUpdate,
  adminDeptDel,
  adminDeptAddWebsit,
  adminDeptUpdateWebsit,
  adminDeptDelWebsit,
  adminDeptImport
} from '@/api/departmentManagement.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import { commonTemplateDownload } from '@/api/common.js'
import import_mixin from '@/components/template/import_mixin.js'
export default {
  components: {
    TemplatePage
  },
  mixins: [operation_mixin, import_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {},
      // 表格事件
      tableEvents: {},
      visible: false,
      item: null,
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'deptName'
      },
      filterText: '',
      dialogVisible: false,
      form: {
        pid: '',
        pname: '',
        deptName: ''
      },
      dialogVisible2: false,
      form2: {
        adminDeptId: '',
        deptName: '',
        adminDeptWebsitId: '',
        websitId: '',
        websitName: '',
        websitIds: []
      },
      adminDept: null,
      keyixuan: []
    }
  },
  mounted() {
    this.getTreeListData()
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('import', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(adminDeptImport, moduleName)
                }
              }
            })
          ],
          [
            this.optionsEvensAuth('download', {
              click: () => {
                commonTemplateDownload({ name: '部门网点导入.xlsx' }, `${this.$route.meta.title}`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            })
          ],
          this?.keyixuan?.length
            ? [
                this.optionsEvensAuth('add', {
                  click: () => {
                    if (this.adminDept) {
                      this.form2 = {
                        deptName: this.adminDept.deptName,
                        adminDeptId: this.adminDept.adminDeptId,
                        adminDeptWebsitId: '',
                        websitId: '',
                        websitName: '',
                        websitIds: []
                      }
                      this.dialogVisible2 = true
                    } else {
                      this.$message.warning('请先选择部门')
                    }
                  }
                })
              ]
            : []
        ]
      ]
    }
  },
  watch: {
    filterText(val) {
      this?.$refs?.listTree?.filter?.(val)
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.deptName.indexOf(value) !== -1
    },
    // 请求属性数据
    getTreeListData() {
      adminDeptTree().then(res => {
        this.treeList = res.data
        this.$refs.pageRef.refreshList()
        this.$nextTick(() => {
          const tree = document.getElementById('kakaka').getElementsByClassName('el-tree')
          const elTreeNodeContent = document.getElementById('kakaka').getElementsByClassName('el-tree-node__content')
          if (elTreeNodeContent.length) {
            var maxwidth = 0
            for (var item of elTreeNodeContent) {
              if (maxwidth < item.scrollWidth) {
                maxwidth = item.scrollWidth
              }
            }
          }
          if (tree.length) {
            for (var item of tree) {
              item.style.width = `${maxwidth}px`
            }
          }
        })
      })
    },
    // 树形选中
    handleNodeClick(e) {
      this.adminDept = { ...e }
      adminDeptList({
        pageNum: 1,
        pageSize: -1,
        params: [{ param: 'admin_dept_id', compare: '=', value: this?.adminDept?.pid }]
      }).then(res => {
        this.keyixuan = res.data.records
      })
      this.$refs.pageRef.refreshList()
    },
    // gengxin(val) {
    //   this.form2.websitName = this.keyixuan?.find(item => item.websitId == val)?.websitName
    // },
    // 列表请求函数
    getList(pam, cb) {
      try {
        if (this?.adminDept?.adminDeptId) {
          pam.params.push({ param: 'admin_dept_id', compare: '=', value: this?.adminDept?.adminDeptId })
        }
        cb && cb(pam)
        return adminDeptList(pam)
      } catch (err) {
      } finally {
      }
    },
    // 列表导出函数
    exportList: adminDeptListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    operation() {
      return this.operationBtn({
        del: {
          click: ({ row, index, column }) => {
            adminDeptDelWebsit({
              adminDeptWebsitId: row.adminDeptWebsitId
            }).then(res => {
              this.$refs.pageRef.refreshList()
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            })
          }
        }
      })
    },
    addbumen(data) {
      this.form.pid = data.adminDeptId
      this.form.pname = data.deptName
      this.dialogVisible = true
    },
    eidbumen(data) {
      this.form = { ...data }
      this.dialogVisible = true
    },
    delbumen(data) {
      adminDeptDel({ adminDeptId: data.adminDeptId }).then(res => {
        this.getTreeListData()
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      })
    },
    queding() {
      if (!this.form.deptName) {
        this.$message.warning('名字不能为空')
      }
      ;(this.form.adminDeptId ? adminDeptUpdate : adminDeptAdd)(this.form).then(res => {
        this.getTreeListData()
        this.handleClose()
        this.$message({
          type: 'success',
          message: '设置成功'
        })
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.form = {
        pid: '',
        pname: '',
        deptName: ''
      }
    },
    queding2() {
      if (!this?.form2?.websitIds?.length && !this?.form2?.websitId) {
        this.$message.warning('请选择网点')
      }
      ;(this.form2.id ? adminDeptUpdateWebsit : adminDeptAddWebsit)({
        ...this.form2,
        id: this?.form2?.id,
        adminDeptId: this?.adminDept?.adminDeptId,
        websitIds: this?.form2?.websitIds?.join(','),
        adminDeptWebsitId: this?.form2?.adminDeptWebsitId
      }).then(res => {
        this.$refs.pageRef.refreshList()
        this.handleClose2()
        this.$message({
          type: 'success',
          message: '设置成功'
        })
      })
    },
    handleClose2() {
      this.dialogVisible2 = false
      this.form2 = {
        deptName: '',
        adminDeptId: '',
        adminDeptWebsitId: '',
        websitId: '',
        websitName: '',
        websitIds: []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .zj-page-fill-scroll {
  overflow-x: auto;
}
.title {
  width: 100%;
  padding: 20px 0 10px 20px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  border-bottom: 1px solid #cccccc;
  font-weight: bold;
}

::v-deep .el-tree-node__content {
  display: inline-block; /* 根据内容宽度调整 */
  white-space: nowrap; /* 防止换行 */
}
.custom-tree-node {
  display: inline-block; /* 根据内容宽度调整 */
  white-space: nowrap; /* 防止换行 */
  box-sizing: border-box;
}
</style>
