<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="dbResoursName"
            placeholder="请输入代码分类"
            clearable
            prefix-icon="search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="dbResourceOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <!-- <i :class="getIconClass(data)"></i> -->
                <span>{{ data.name }}</span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="标准代码编号" prop="codeNum">
            <el-input v-model="queryParams.codeNum" placeholder="请输入标准代码编号" clearable style="width: 220px" />
          </el-form-item>
          <el-form-item label="标准代码值" prop="codeName">
            <el-input v-model="queryParams.codeName" placeholder="请输入标准代码值" clearable style="width: 220px" />
          </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-row>

        <!-- 表格展示 -->
        <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />

          <el-table-column label="代码归属" align="center" prop="sysName" />
          <el-table-column label="标准代码编号" align="center" prop="codeNum" />
          <el-table-column label="标准代码名称" align="center" prop="codeName" >
            <template #default="scope"> 
              <el-link
                type="primary"
                :underline="true"
                @click="handleCodeClick(scope.row)"
                style="cursor: pointer"
                  >
      {{ scope.row.codeName }}
    </el-link>
    </template>
            </el-table-column>
          <el-table-column label="代码状态" align="center" prop="codeStatus">
            <template #default="scope">
              <dict-tag
                :options="std_code_appr"
                :value="scope.row.codeStatus"
              />
            </template>
          </el-table-column>
          <el-table-column label="引用情况" align="center"  >
          <template #default="scope">
            <el-link
                type="primary"
                :underline="true"
                @click="handleCodeClick(scope.row)"
                style="cursor: pointer"
                  >
            查看
    </el-link>
            </template>
          </el-table-column>
          <el-table-column label="代码关系" align="center" >
          <template #default="scope">
            <el-link
                type="primary"
                :underline="true"
                @click="handleCodeClick(scope.row)"
                style="cursor: pointer"
                  >
      查看关系
    </el-link>
            </template>
          </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>

    <!-- 添加或编辑标准代码对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="form" ref="formRef" label-width="120px" :rules="formRules">
        <el-form-item label="标准代码类型" prop="codeType">
          <el-select
                v-model="form.codeType"
                placeholder="请选择标准代码类型"
                maxlength="30"
                @change="changeCodeType"
              >
                <el-option
                  v-for="dict in std_code_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
        </el-form-item>

        <el-form-item label="归属系统" prop="sysId" v-show="showSys">
          <el-select
                v-model="form.sysId"
                placeholder="请选择归属系统"
                maxlength="30"
                @change="dataChange"
              >
                <el-option
                  v-for="dict in dbResourceOldList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
</el-form-item>
        <el-form-item label="标准代码编号" prop="codeNum">
          <el-input v-model="form.codeNum" placeholder="请输入标准代码编号" />
        </el-form-item>
        <el-form-item label="标准代码值" prop="codeName">
          <el-input v-model="form.codeName" placeholder="请输入标准代码值" />
        </el-form-item>

   </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
     <!-- 第二个对话框 - 用于查看标准代码详情 -->
     <el-dialog :title="dialogTitle2" v-model="dialogVisible2" width="1000px">
      <!-- 引入第二个页面组件 -->
      <code-item :rowData="selectedRow"/>
      <template #footer>
        <el-button @click="handleCancel2">取消</el-button>
        <el-button type="primary" @click="handleSave2">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from 'vue';
import { listStdCode, addStdCode, getStdCode, updateStdCode, deleteStdCode } from "@/api/datastd/stdcode"; // 更新为新的接口
import { datasourcetree } from "@/api/meta/metatask";
import { ElLink } from 'element-plus';
import CodeItem from './codeItem.vue'; // 引入第二个页面组件


const { proxy } = getCurrentInstance();
const { std_code_status,std_code_appr } = proxy.useDict("std_code_status","std_code_appr");

const queryParams = ref({
  codeNum: '',
  codeName: '',
  codeType: '',
  sysName: '',
  sysId: '',
  pageNum: 1,
  pageSize: 10
});
const single = ref(true);
const showSys = ref(false);
const multiple = ref(true);
const dbResoursName = ref(undefined);
const defaultProps = {
  children: "children",
  label: "name"
};
// 用于第二个对话框
const dialogVisible2 = ref(false);
const dialogTitle2 = ref('标准代码');
const selectedRow = ref(null); // 传递给 codeItem 组件的数据
const formData = ref({}); // 用于传递表单数据给 codeItem
const handlePagination = (pageNum, pageSize) => {
  queryParams.value.pageNum = pageNum;
  queryParams.value.pageSize = pageSize;
  handleQuery();
};
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};
const handleNodeClick = (data) => {
  if(data==9999){
    queryParams.value.sysId =undefined;

  }else{
    queryParams.value.sysId = data.id;

  }
 
  handleQuery();
};

const dbResourceOptions = ref(undefined);
const form = ref({
  id: '',
  codeNum: '',
  codeName: '',
  codeType: 'company',
  codeStatus: '',
  sysName: '',
  sysId: undefined
});
const ids = ref([]);
const codeNums = ref([]);

// 获取数据列表
const getList = async () => {
  loading.value = true;
  const response = await listStdCode(queryParams.value);
  tableData.value = response.rows;
  total.value = response.total;
  loading.value = false;
};
// 点击代码名称，弹出第二个对话框并传递数据
const handleCodeClick = (row) => {
  selectedRow.value = row; // 保存选中的行数据
  formData.value = { ...row }; // 复制选中的行数据
  dialogVisible2.value = true; // 打开第二个对话框
};

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  codeNums.value = selection.map(item => item.codeNum);
  single.value = ids.value.length !== 1;
  multiple.value = !ids.value.length > 0;
}
function changeCodeType(data){
 if(data != "company"){
 showSys.value=true
 form.value.sysName=""
 form.value.sysId=undefined
 } else {
  showSys.value=false
  form.value.sysName="公司级"
  form.value.sysId=10000

 }

}
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
function dataChange(data) {

// 从 dbResourceOldList 中查找对应的 name
const selectedItem = dbResourceOldList.value.find(item => item.id === data);
if (selectedItem) {
// 如果找到对应的项，将 name 赋值给 form.value.dbRName
form.value.sysName = selectedItem.name;
} else {
// 如果未找到，清空 form.value.dbRName
form.value.sysName = '';
}
}
const resetQuery = () => {
  queryParams.value = {
    codeNum: '',
    codeName: '',
    codeType: '',
    sysName: '',
    sysId: '',
    pageNum: 1,
    pageSize: 10
  };
  getList();
};

const handleAdd = () => {
  dialogTitle.value = "新增标准代码";
  form.value = {
    id: '',
    codeNum: '',
    codeName: '',
    codeType: '',
    codeStatus: '',
    sysName: '',
    sysId: '',
  };
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogTitle.value = "编辑标准代码";
  getStdCode(row.id).then(response => {
    form.value = response.data;
    if(form.value.codeType=="sys")
  {
    showSys.value=true
  } else{
    showSys.value=false

  }
    dialogVisible.value = true;
  });
};

const handleRemove = (row) => {
  const idsToDelete = row.id ? [row.id] : ids.value;
  const codesToDelete = row.codeNum ? [row.codeNum] : codeNums.value;
  proxy.$modal.confirm('是否确认删除ID为"' + codesToDelete.toString() + '"的数据项？').then(function () {
    return deleteStdCode(idsToDelete.toString());
  }).then(() => {
    handleQuery();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

const handleSave = () => {
  if (!form.value.codeNum || !form.value.codeName) {
    ElMessage.warning("请填写必填项");
    return;
  }

  const saveAction = form.value.id ? updateStdCode : addStdCode;
  saveAction(form.value).then(() => {
    dialogVisible.value = false;
    handleQuery();
  });
};

const handleCancel = () => {
  dialogVisible.value = false;
};
const dbResourceOldList = ref([]);
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRules = reactive({
  codeNum: [{ required: true, message: "请输入标准代码编号", trigger: "blur" }],
  codeName: [{ required: true, message: "请输入标准代码值", trigger: "blur" }]
});
onMounted(() => {
  datasourcetree().then(response => {

    dbResourceOldList.value = response.rows;
    const childrenList = dbResourceOldList.value.map(element => ({ ...element, parentId: "99999" }));
    dbResourceOptions.value = [
    {
      id: 10000, // 新的节点 ID，可以根据需要调整
      name: "公司级代码", 
      parentId: 0, 
      children: [] // 这里可以根据需要填充子节点
    },
    { 
      id: 99999, 
      name: "系统级代码", 
      parentId: 0, 
      children: childrenList 
    },

  ];  });
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.head-container {
  margin-bottom: 0px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
}

.custom-tree-node i {
  margin-right: 8px;
}
</style>
