<template>
  <div class="page">
    <div class="left">
      <h2>风险单元类型管理</h2>
    </div>
    <div class="right">
      <el-button type="primary" @click="openCreateFile()">
        <el-icon>
          <CirclePlus />
        </el-icon>
        <span>新增</span>
      </el-button>
    </div>
    <div class="tree-box">
      <el-tree :data="dataSource" :props="defaultProps" node-key="id" ref="treeRef" @node-dblclick="handleDblclick"
        :default-expanded-keys="defaultExpandedKeys">
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <div class="files-title">
              <span>{{ data.name }}</span>
            </div>
            <div class="custom-tree-node-right" @click.stop>
              <span class="right-btn operesee" @click="createFile(node, data)">新增下级</span>
              <span class="right-btn operedit" @click="emitItemFile(node, data)">修改</span>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="deleteFile(data.id)">
                <template #reference>
                  <span class="right-btn operdel" size="small">删除</span>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </template>
      </el-tree>
    </div>

    <el-dialog v-model="isShowDialog" :title="isEdit ? '编辑单元类型' : '创建单元类型'">
      <el-form label-width="150px" style="padding-top: 20px;" :model="formData" :rules="rules" ref="ruleFormRef">
        <el-form-item label="风险单元名称" prop="fxdyname">
          <el-input v-model="formData.fxdyname" placeholder="请输入风险单元名称"
            @keyup.enter.prevent.stop="commitFrom(ruleFormRef)" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number :min="0" :max="999999999999" v-model="formData.sort" placeholder="请输入排序序号"
            @keyup.enter.prevent.stop="commitFrom(ruleFormRef)" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>

        <span class="dialog-footer">
          <el-button @click="commitFrom(ruleFormRef)">确定</el-button>
          <el-button @click="isShowDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from "element-plus"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import * as MOSTY from "@/components/MyComponents/index";
import { FileListonload } from "@/api/base";
import { getErrMsg } from "@/utils/tools.js"


/**
 * 档案类型.
 * 值:
 * - '1': 员工诚信档案
 * - '2': 业务工作档案
 * - '3': 设备设施档案
 * - '4': 单元类型
 * @type {import('vue').Ref<string>}
 */
const typeStr = ref('4')
let treeRef = ref(null)
/** 是否是编辑 */
let isEdit = ref(null)
const defaultExpandedKeys = ref([])
/** 是否是 上传文件 */
const isUpdateFile = ref(false)

/** 是否显示弹框（新增/编辑档案） */
let isShowDialog = ref(false)
let formData = ref({
  fxdyname: '',
  sort: '',
  id: null,
  parentId: null
})
let ruleFormRef = ref()
const defaultProps = reactive({
  children: 'children',
  label: 'name',
  value: 'id',
})
const rules = reactive({
  fxdyname: [
    { required: true, message: '风险单元类型名称不能为空', trigger: 'blur' },
  ],
  sort: [
    { required: true, message: '排序不能为空', trigger: 'blur' },
  ],
})
/** 当前点击的row 方便知道是新增的是谁的 */
const currRow = ref({})
/** 树数组 */
const dataSource = ref([])
// 双击事件处理
const handleDblclick = (node) => {
  // 关键3：手动切换节点展开状态
  node.expanded = !node.expanded;
  treeRef.value.store.nodesMap[node.id].expanded = node.expanded;
}
/**
 *
 * @param id 要展开的最后一级节点id
 */
const getExpandedKeys = (id, data, expandArr) => {
  if (!data?.length) return

  const node = data.find(item => item.id === id);
  if (node) {
    return [...expandArr, node.id]
  } else {
    let resultArr = null
    data.forEach(item => {
      if (item.children && item.children.length) {
        const result = getExpandedKeys(id, item.children, [...expandArr, item.id]);
        if (result) resultArr = result
      }
    });
    if (resultArr) return resultArr
  }
}
/** 获取 要展开的keys */
const getRealExpandedKeys = (id, isAdd) => {
  let arr = getExpandedKeys(id, JSON.parse(JSON.stringify(dataSource.value)), [])
  return isAdd ? arr : arr.slice(0, -1)
}

/**
* 提交表单列表
* @param formEl
*/
const commitFrom = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      createAFile()
      // let arr = getExpandedKeys(currRow.value.id, dataSource.value, [])
      // if (isEdit.value) arr.pop()
      // defaultExpandedKeys.value = arr || []
      defaultExpandedKeys.value = getRealExpandedKeys(currRow.value.id, !isEdit.value)
    } else {
      ElMessage.warning(getErrMsg(fields) || '请检查表单!')
    }
  })
}

/**
 *  创建档案
 */
const createAFile = () => {
  const params = {
    name: [formData.value.fxdyname], // 1:员工诚信档案 2:业务工作档案 3:设备设施档案 4:单元类型
    // parentId: formData.value.parentId || null,
    sort: formData.value.sort
  }

  // 新增
  if (!isEdit.value) {
    if (currRow.value.id) params.parentId = currRow.value.id
    postApi(params, "/mosty-jcgl/fxdy/save")
      .then(res => {
        getFilesList()
        ElMessage.success('新增成功')
        isShowDialog.value = false
      })
      .finally(() => {
        isShowDialog.value = false
      })
    // 编辑
  } else {
    params.id = formData.value.id
    postApi(params, "/mosty-jcgl/fxdy/update")
      .then(res => {
        getFilesList()
        ElMessage.success('编辑成功')
        isShowDialog.value = false
      })
      .finally(() => {
        isShowDialog.value = false
      })

  }
}


/**
 *  获取当前列表
 */
const getFilesList = () => {
  getApi({}, '/mosty-jcgl/fxdy/tree').then(async (res) => {
    if (res) {
      dataSource.value = Array.isArray(res) ? res : [];
    }
  });
}


const deleteFile = (id) => {
  postApi({}, `/mosty-jcgl/fxdy/delete?id=${id}`).then(res => {
    ElMessage.success('删除成功')
    getFilesList()
    // 设置展开的节点
    // let arr = getExpandedKeys(id, JSON.parse(JSON.stringify(dataSource.value)), [])
    // arr.pop()
    // defaultExpandedKeys.value = arr || []
    defaultExpandedKeys.value = getRealExpandedKeys(currRow.value.id, !isEdit.value)
  })
}
/**
 * 打开创建档案串钩
 * @param data
 */
const openCreateFile = (row = {}) => {
  isEdit.value = null
  if (ruleFormRef.value) ruleFormRef.value.resetFields()
  formData.value = {
    fxdyname: '',
    sort: '',
  }
  currRow.value = {}
  isShowDialog.value = true; // 显示弹窗
}
/**
 * 新增子项档案
 * @param node
 * @param data
 */
const createFile = (node, data) => {
  isEdit.value = null
  if (ruleFormRef.value) ruleFormRef.value.resetFields()
  currRow.value = data
  formData.value = {
    parentId: data.id,
    fxdyname: '',
    sort: '',
  }
  isShowDialog.value = true; // 显示弹窗
}


/**
 *
 * @param node
 * @param data
 */
const emitItemFile = (node, data) => {
  console.log('data: ', data);
  console.log('node: ', node);

  currRow.value = data
  if (ruleFormRef.value) ruleFormRef.value.resetFields()
  formData.value = {
    id: data.id,
    fxdyname: data.name,
    parentId: data.parentId,
    sort: data.sort,
  }
  isEdit.value = true
  // isUpdateFile.value = false
  isShowDialog.value = true; // 显示弹窗
}



onMounted(() => {
  getFilesList()
});


</script>


<style scoped lang="scss">
.page {
  box-sizing: border-box;
  padding: 0 10px;
  height: 100vh;
  background-color: #fff;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 20px;
}

.left {
  width: 100%;
  background-color: #fff;
  padding: 10px;
  box-sizing: border-box;

  >h2 {
    font-size: 18px;
    line-height: 18px;
    margin: 0;
    color: var(--el-color-primary);
    padding-bottom: 10px;
  }
}

.right {
  border-top: 0.1px solid #a8d1d0;
  background-color: #fff;
  text-align: right;
  box-sizing: border-box;
  padding: 10px;
}

.tree-box {
  height: calc(100vh - 250px);
  overflow-y: auto;
}

:deep(.el-form) {
  display: inline;
}

.files-title {
  display: flex;
  align-items: center;

  img {
    height: 20px;
  }
}

.right-btn {
  background-color: #fff;
  color: #000;
  border-radius: 4px;
  padding: 2px 5px;
  margin-left: 10px;
  background-color: #e7efed;
  border: 1px solid var(--el-color-primary);
}

::v-deep .el-tree-node__content {
  height: 30px;

  &:hover {
    background: var(--el-table-border-color);
  }
}
</style>
