<template>
  <div class="app-container">
    <el-row :gutter="16">
      <el-col :span="5">
          <el-input
            v-model="filterText"
            style="width: 100%"
            placeholder="搜索分类名称"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <div class="tree-box">
            <el-tree
              class="tree"
              ref="treeRef"
              node-key="tempId"
              :default-expand-all="true"
              :highlight-current="true"
              :expand-on-click-node="false"
              :data="directoryTree"
              :props="defaultProps"
              :filter-node-method="filterNode"
              :current-node-key="currentNode.tempId"
              @node-click="handleNodeClick"
            >
              <template #default="{ data }">
                <div class="custom-tree-node">
                  <el-space :size="2">
                    <el-icon v-if="!isCollectionDirectory(data)">
        <Folder />
      </el-icon>
      <el-icon v-else :style="isCollectionDirectory(data) ? { color: '#E6A23C' } : {}">
        <FolderRemove />
      </el-icon>
                    <span :style="isCollectionDirectory(data) ? { color: '#E6A23C' } : {}">
        {{ data.contentName || data.dataAstCnName }}
      </span>                  </el-space>
                  <div
                    v-if="!isCollectionDirectory(data)"
                    class="tree-node__action"
                  >
                    <template v-if="isAsset(data)">
                      <el-button
                        v-if="!isCollected(data)"
                        link
                        type="warning"
                        icon="Star"
                        @click="(e) => handleCollect(data, e)"
                      ></el-button>
                      <el-button
                        v-else
                        link
                        type="warning"
                        style="margin-right: -2px"
                        @click="(e) => handleCollectionCancel(data, e)"
                      >
                        <el-icon slot="icon" size="18" color="#E6A23C">
                          <StarFilled />
                        </el-icon>
                      </el-button>
                    </template>
                    <el-dropdown
                      v-if="
                        !isCollection(data) &&
                        (isDirectory(data) || isRoot(data)) &&
                        hasPermiOr([
                          'dataAsset:directory:add',
                          'dataAsset:directory:edit',
                          'dataAsset:directory:remove',
                          'dataAsset:directory:move',
                          'dataAsset:directory:merge',
                        ])
                      "
                      placement="right-start"
                      @command="(command) => handleCommand(command, data)"
                    >
                      <el-button
                        style="margin-left: 4px"
                        link
                        type="primary"
                        icon="Menu"
                      ></el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item
                            v-if="
                              isRoot(data) &&
                              hasPermiOr(['dataAsset:directory:add'])
                            "
                            command="handleAddDialogOpen"
                          >
                            新增分类
                          </el-dropdown-item>
                          <template v-if="isDirectory(data)">
                            <el-dropdown-item
                              v-if="hasPermiOr(['dataAsset:directory:add'])"
                              command="handleAddDialogOpen"
                            >
                              新增分类
                            </el-dropdown-item>
                            <el-dropdown-item
                              v-if="hasPermiOr(['dataAsset:directory:edit'])"
                              command="handleEditDialogOpen"
                            >
                              修改分类
                            </el-dropdown-item>
                            <el-dropdown-item
                              v-if="hasPermiOr(['dataAsset:directory:remove'])"
                              command="handleDelete"
                            >
                              删除分类
                            </el-dropdown-item>
                            <el-dropdown-item
                              v-if="hasPermiOr(['dataAsset:directory:move'])"
                              command="handleMoveDialogOpen"
                            >
                              移动分类
                            </el-dropdown-item>
                            <el-dropdown-item
                              v-if="hasPermiOr(['dataAsset:directory:merge'])"
                              command="handleMergerDialogOpen"
                            >
                              合并分类
                            </el-dropdown-item>
                          </template>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <el-dropdown
                      v-if="
                        !isCollection(data) &&
                        isAsset(data) &&
                        hasPermiOr([
                          'dataAsset:asset:remove',
                          'dataAsset:asst:move',
                        ])
                      "
                      placement="right-start"
                      @command="(command) => handleCommand(command, data)"
                    >
                      <el-button
                        style="margin-left: 4px"
                        link
                        type="primary"
                        icon="Menu"
                      ></el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item
                            v-if="hasPermiOr(['dataAsset:asset:remove'])"
                            command="handleAssetDelete"
                          >
                            删除资产
                          </el-dropdown-item>
                          <el-dropdown-item
                            v-if="hasPermiOr(['dataAsset:asst:move'])"
                            command="handleAssetMoveDialogOpen"
                          >
                            移动资产
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
      </el-col>
      <el-col :span="19">
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="标准编号/名称">
            <el-input v-model="queryParams.stdNum" placeholder="请输入标准编号" />
          </el-form-item>
          <el-form-item label="业务定义">
            <el-input v-model="queryParams.stdMenu" placeholder="请输入业务定义" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
               <!-- 操作按钮 -->
               <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['meta:metaSecurityCol:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleEdit"
              v-hasPermi="['meta:metaSecurityCol:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleRemove"
              v-hasPermi="['meta:metaSecurityCol:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="multiple"
              @click="treeVisible=true"
              v-hasPermi="['meta:metaSecurityCol:remove']"
              >标准分类</el-button
            >
          </el-col>
        </el-row>
                <!-- 表格展示 -->
                <el-table
          v-loading="loading"
          :data="tableData"
          @selection-change="handleSelectionChange"
        >
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="标准编号" prop="stdNum" width="150"></el-table-column>
<el-table-column label="标准英文名" prop="stdCode" width="150"></el-table-column>
<el-table-column label="标准中文名" prop="stdName" width="150"></el-table-column>
<el-table-column label="标准业务定义" prop="stdMenu" width="150"></el-table-column>
<el-table-column label="类型" prop="stdType" width="150">
  <template #default="scope"> 
    <!-- 根据 dataClas 的值来显示不同颜色的标签 -->
    <el-tag v-if="scope.row.stdType =='0'" type="primary">基础数据</el-tag>
    <el-tag v-else type="warning">指标数据</el-tag>
  </template>
</el-table-column><el-table-column label="标准来源" prop="stdSrc" width="150"></el-table-column>
<el-table-column label="数据类别" prop="dataClas" width="150"></el-table-column>
<el-table-column label="代码编号" prop="codeNum" width="150">
  <template #default="scope"> 
              <el-link
                type="primary"
                :underline="true"
                @click="handleCodeClick(scope.row)"
                style="cursor: pointer"
                  >
      {{ scope.row.codeNum }}
    </el-link>
    </template>
</el-table-column>
<el-table-column label="安全等级" prop="securityLevel" width="150"></el-table-column>
<el-table-column label="来源系统" prop="sourceSystem" width="150"></el-table-column>
<el-table-column label="业务认责部门" prop="bussDeptId" width="150"></el-table-column>
<el-table-column label="业务认责部门" prop="bussDeptId" width="150"></el-table-column>
<el-table-column label="业务认责部门" prop="bussDeptId" width="150"></el-table-column>
<el-table-column label="业务认责人员" prop="bussUser" width="150"></el-table-column>
<el-table-column label="技术认责部门" prop="techDeptId" width="150"></el-table-column>
<el-table-column label="技术认责人员" prop="techUser" width="150"></el-table-column>
<!-- <el-table-column label="分类" prop="contentOnum" width="150"></el-table-column> -->
<el-table-column label="更新时间" prop="updateTime" width="180"></el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button
                @click="handleEdit(scope.row)"
                type="text"
                icon="Edit"
              />
              <el-button
                @click="handleRemove(scope.row)"
                type="text"
                icon="Delete"
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </el-col>
    </el-row>
    <FormDialog
      ref="formDialogRef"
      :directoryTree="directoryTree"
      @onSuccess="setDirectoryTree"
    />
    <MoveDialog
      ref="moveDialogRef"
      :directoryTree="directoryTree"
      @onSuccess="setDirectoryTree"
    />
    <MergerDialog
      ref="mergerDialogRef"
      :directoryTree="directoryTree"
      @onSuccess="setDirectoryTree"
    />
    <AssetMoveDialog
      ref="assetMoveDialogRef"
      :directoryTree="directoryTree"
      @onSuccess="setDirectoryTree"
    />
    <AddEditForm
      :data="selectedRow"
      :isEdit="isEdit"
      :dbResourceOldList="dbResourceOldList"
      v-model:visible="dialogVisible"
      @refresh="getList"
    />
    <el-dialog v-model="codeVisible" width="1000px">

    <code-item-common  ref="showCodeDialog" v-if="codeVisible" :codeId="codeId"/>
</el-dialog>
<el-dialog width="600px" append-to-body title="标准分类" v-model="treeVisible">
    <el-form label-width="100px" ref="formRef" >

      <el-form-item label="标准分类">
        <el-tree-select
          check-strictly
          value-key="contentOnum"
          placeholder="请选择标准分类"
          :default-expand-all="true"
          :clearable="true"
          :data="directoryTree"
          @node-click="handleTargetCatalogNodeClick"
          :check-strictly="false"
          :props="{
            value: 'contentOnum',
            label: 'contentName',
            children: 'children',
            disabled: (data) => data.children && data.children.length > 0, // 有子节点就禁用
          }"
          v-model="chooseOnum"
        >
        </el-tree-select>
      </el-form-item>
 </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="treeVisible=false">取消</el-button>
        <el-button type="primary" @click="submitTree"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script setup name="Directory">
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDirectoryTree,
  delDirectory,
  delDirectoryAsset,
  addDirectoryCollection,
  cancelDirectoryCollection,
  
} from '@/api/datastd/directory'
import auth from '@/plugins/auth'
import FormDialog from './components/FormDialog.vue'
import MoveDialog from './components/MoveDialog.vue'
import MergerDialog from './components/MergerDialog.vue'
import AssetMoveDialog from './components/AssetMoveDialog.vue'
import AddEditForm from "./components/AddEditForm.vue";
import {
  listStdMain,
  getStdMain,
  deleteStdMain,
  changeStdMainOum
} from "@/api/datastd/std"; // 更新为新的接口
import useUserStore from '@/store/modules/user'
import { nextTick } from 'vue'
import codeItemCommon from '../stdcode/codeItemCommon.vue'

import { datasourcetree } from "@/api/meta/metatask";
const { proxy } = getCurrentInstance()
const { hasPermiOr } = auth
const userStore = useUserStore()
const codeVisible = ref(false);
const treeVisible = ref(false);
const defaultProps = {
  children: 'children',
  label: 'contentName',
}
const directoryTree = ref([])
const currentNode = ref({})
const handleTargetCatalogNodeClick = (data) => {
  chooseOnumNum.value=data.contentOnum
}

const directoryTableData = ref([])
const queryParams = ref({
  stdNum: '',
  stdMenu: '', 
  contentOnum:null,
  pageNum: 1,
  pageSize: 10,
});
const single = ref(true);
const multiple = ref(true);
const dialogVisible = ref(false);
const selectedRow = ref(null);
const chooseOnum = ref(null);
const chooseOnumNum = ref(null);
const codeId = ref(null);
const isEdit = ref(false);
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const ids = ref([]);
const stdNums = ref([]);
const handlePagination = (pageNum, pageSize) => {
  queryParams.value.pageNum = pageNum;
  queryParams.value.pageSize = pageSize;
  handleQuery();
};
// 点击代码名称，弹出第二个对话框并传递数据
const handleCodeClick = (row) => {
  codeId.value=row.codeId
  codeVisible.value = true;

};
const resetQuery = () => {
  queryParams.value = { stdNum: '', stdMenu: '' ,   pageNum: 1,
  pageSize: 10}
  handleQuery()
}
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const submitTree = async () => {
  const response = await changeStdMainOum({id:ids.value.toString(),sysId:chooseOnumNum.value});
  if (response.success){
    treeVisible.value=false
    getList();
    proxy.$modal.msgSuccess(response.msg);

  }else{
    proxy.$modal.msgWarning(response.msg);

  }

};
const handleSelectionChange = (selection) => {
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
  ids.value = selection.map((item) => item.id);
  stdNums.value = selection.map((item) => item.stdNum);
};
const setDirectoryTree = () => {
  return getDirectoryTree({
    pageSize: 999,
  }).then(({ rows }) => {
    directoryTree.value = addTreeNodeId(rows)
  })
}
setDirectoryTree().then(async () => {
  if (directoryTree.value.length) {
    currentNode.value = directoryTree.value[0]
    directoryTableData.value = directoryTree.value[0].children || []

  }
})
const getList = async () => {
  loading.value = true;
  const response = await listStdMain(queryParams.value);
  tableData.value = response.rows;
  total.value = response.total;
  loading.value = false;
};
const handleRemove = (row) => {
  const idsToDelete = row.id ? [row.id] : ids.value;
  const codesToDelete = row.stdNum ? [row.stdNum] : stdNums.value;
  proxy.$modal
    .confirm(
      '是否确认删除标准编号为"' + codesToDelete.toString() + '"的数据项？'
    )
    .then(function () {
      return deleteStdMain(idsToDelete.toString());
    })
    .then(() => {
      handleQuery();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
const dbResourceOldList = ref([]);

const handleAdd = () => {
  isEdit.value = false;
  selectedRow.value = {
    stdType: "",
    stdNum: "",
    stdCode: "",
    stdName: "",
    stdMenu: "",
    dataType: "",
    stdCode: "",
    bussDeptId: "",
    bussUser: "",
    techDeptId: "",
    techUser: "",
    securityLevel:"",
    sourceSystem:""
  };

  // 清空选中的数据
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  const id = row.id ? row.id : ids.value.toString();
  getStdMain(id).then((response) => {
    selectedRow.value = response.data;
    isEdit.value = true;
    dialogVisible.value = true;
  });
};
/** 增加临时ID作为树节点的唯一键值 */
const addTreeNodeId = (tree) => {
  return tree.map((node) => {
    return {
      ...node,
      tempId: node.astOnum || node.contentOnum,
      children:
        node.children && node.children.length
          ? addTreeNodeId(node.children)
          : [],
    }
  })
}
const filterText = ref(undefined)
const treeRef = ref(null)
watch(filterText, (val) => {
  treeRef.value.filter(val)
})
watch(treeVisible, (val) => {
  if(val){  chooseOnum.value=null}
})
const filterNode = (value, data) => {
  if (!value) {
    return true
  }
  if (data.contentName) {
    return data.contentName.includes(value)
  }
  if (data.dataAstCnName) {
    return data.dataAstCnName.includes(value)
  }
}

// 是否根分类
const isRoot = (data) => {
  return data.contentOnum === 1
}

// 是否我的收藏分类
const isCollectionDirectory = (data) => {
  return data.contentName === '临时'
}

// 是否收藏的分类
const isCollection = (data) => {
  return false
}

// 是否已收藏的
const isCollected = (data) => {
  return data.bookmarkFlag === 1
}


// 是否子分类
const isDirectory = (data) => {
  return data.contentOnum && !isRoot(data) && !data.astOnum
}

// 是否资产
const isAsset = (data) => {
  return data.astOnum
}

const activeName = ref('1')
const handleNodeClick = async (data) => {

  if(data.contentOnum==1){
    queryParams.value.contentOnum=null
  }else{
    queryParams.value.contentOnum=data.contentOnum

  }
  handleQuery();


}

const handleCollect = (data, e) => {
  e.stopPropagation()
  addDirectoryCollection({
    dataAstNo: String(data.dataAstNo),
    userId: String(userStore.id),
  }).then(() => {
    proxy.$modal.msgSuccess('收藏成功')
    setDirectoryTree()
  })
}

const handleCollectionCancel = (data, e) => {
  e.stopPropagation()
  cancelDirectoryCollection(data.relaOnum).then(() => {
    proxy.$modal.msgSuccess('取消成功')
    setDirectoryTree()
  })
}

const formDialogRef = ref(null)
const handleAddDialogOpen = (data) => {
  formDialogRef.value.title = '新增分类'
  formDialogRef.value.openDialog({
    suprContentOnum: data.contentOnum,
  })
}

const handleEditDialogOpen = (data) => {
  formDialogRef.value.title = '修改分类'
  formDialogRef.value.openDialog(data)
}

const handleDelete = (data) => {
  ElMessageBox.confirm(
    `确定删除 ${data.contentName} 分类吗？`,
    '分类删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDirectory(data.contentOnum).then(() => {
      proxy.$modal.msgSuccess('删除成功')
      setDirectoryTree()
    })
  })
}

const moveDialogRef = ref(null)
const handleMoveDialogOpen = (data) => {
  moveDialogRef.value.title = '移动分类'
  moveDialogRef.value.openDialog(data)
}

const mergerDialogRef = ref(null)
const handleMergerDialogOpen = (data) => {
  mergerDialogRef.value.title = '合并分类'
  mergerDialogRef.value.openDialog(data)
}

const handleAssetDelete = (data) => {
  ElMessageBox.confirm(`确定删除 ${data.dataAstCnName} 资产吗？`, '资产删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delDirectoryAsset({
      ...data,
      relaStatus: '0', // 0-删除，1-正常
    }).then(() => {
      proxy.$modal.msgSuccess('删除成功')
      setDirectoryTree()
    })
  })
}

const assetMoveDialogRef = ref(null)
const handleAssetMoveDialogOpen = (data) => {
  assetMoveDialogRef.value.title = '移动资产'
  assetMoveDialogRef.value.openDialog(data)
}

const handleCommand = (command, data) => {
  const strategy = {
    handleAddDialogOpen: handleAddDialogOpen,
    handleEditDialogOpen: handleEditDialogOpen,
    handleDelete: handleDelete,
    handleMoveDialogOpen: handleMoveDialogOpen,
    handleMergerDialogOpen: handleMergerDialogOpen,
    handleAssetDelete: handleAssetDelete,
    handleAssetMoveDialogOpen: handleAssetMoveDialogOpen,
  }
  strategy[command](data)
}

onMounted(() => {
  datasourcetree().then((response) => {
    dbResourceOldList.value = response.rows;

  });
  getList();
});

</script>

<style lang="scss" scoped>
.tree-box {
  overflow: auto;
}
.tree {
  margin-top: 10px;
  min-width: 260px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .tree-node__action {
    padding: 0 8px;
    display: flex;
    justify-content: flex-end;
  }
}

:deep(
    .el-descriptions__body
      .el-descriptions__table.is-bordered
      .el-descriptions__cell
  ) {
  width: 80px !important;
}

.faq {
  white-space: pre-wrap;
}



iframe {
  border: none;
}
</style>
