<!-- @format -->

<template>
  <div class="main">
    <div class="left">
      <div class="top">
        <a-form style="width: 100%; margin: 0 auto">
          <div class="ns-form-title"><div class="title">排放分类</div></div>
          <div style="padding: 0 16px !important; width: 100%">
            <a-row>
              <a-col :span="24" style="margin-bottom: 16px">
                <a-input-search
                  v-model:value="selectTreeDataValue"
                  placeholder="请输入关键词"
                  allowClear
                  @search="onSearchTreeData" />
              </a-col>
            </a-row>
          </div>
        </a-form>
        <a-tree
          v-if="gData && gData.length > 0"
          class="draggable-tree"
          style="padding: 0 16px !important"
          draggable
          show-line
          checkable
          block-node
          :tree-data="gData"
          :checkedKeys="checkedTreeNodeKeys"
          :selectedKeys="selectedKeys"
          @dragenter="onDragEnter"
          @drop="onDrop"
          @check="checkTreeNode"
          @select="onSelect"
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          @expand="onExpand">
          <template #title="data">
            <div class="treeRow">
              <div>
                <span
                  v-if="
                    data.emissionName &&
                    selectTreeDataValue &&
                    data.emissionName.indexOf(selectTreeDataValue) > -1
                  ">
                  {{
                    data.emissionName.substring(0, data.emissionName.indexOf(selectTreeDataValue))
                  }}
                  <span style="color: #f50">{{ selectTreeDataValue }}</span>
                  {{
                    data.emissionName.substring(
                      data.emissionName.indexOf(selectTreeDataValue) + selectTreeDataValue.length,
                    )
                  }}
                </span>
                <span v-else>{{ data.emissionName }}</span>
              </div>
              <a-dropdown>
                <ns-icon name="actionMore" size="14" class="actionMore" />
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="editTreeNodeData(data)">编辑</a-menu-item>
                    <a-menu-item @click="addTreeNodeData">新增子节点</a-menu-item>
                    <a-menu-item
                      v-if="!data.isFirst && data.emissionName !== '未分类'"
                      @click="moveNode(data, 'up')"
                      >上移</a-menu-item
                    >
                    <a-menu-item
                      v-if="!data.isEnd && data.emissionName !== '未分类'"
                      @click="moveNode(data, 'down')"
                      >下移</a-menu-item
                    >
                    <a-menu-item @click="deleteTreeNode(data)">删除</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
          </template>
        </a-tree>
        <div class="addTreeNode">
          <a-button type="primary" style="width: 100%" @click="addTreeNodeData">新增</a-button>
        </div>
      </div>
    </div>
    <div class="right">
      <ns-view-list-table v-bind="tableConfig" :model="data" ref="mainRef" :scroll="{ x: 2000 }">
        <template #bodyCell="{ record, column }">
          <template v-if="column.dataIndex === 'emissionGas'">
            {{ record.emissionGas.label }}
          </template>
        </template>
      </ns-view-list-table>
    </div>
    <!-- 新增树节点 -->
    <ns-modal :visible="treeNodeAdd" :title="operationTree" @ok="handleOk" @cancel="handleCancel">
      <ns-input v-model:value="addTreeNode" class="input" placeholder="请输入排放类型" />
    </ns-modal>
    <!-- 新增数据库数据 -->
    <a-drawer
      :width="500"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      destroyOnClose
      @close="onClose">
      <ns-form
        ref="formRef"
        :schemas="formSchema"
        :model="formData"
        class="form"
        :wrapperCol="{ span: 20 }"
        formLayout="vertical" />
      <template #footer>
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onEdit">确定</a-button>
      </template>
    </a-drawer>
    <!-- 单位管理 -->
    <a-drawer
      :width="500"
      :visible="unitManagement"
      v-if="unitManagement"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      destroyOnClose
      @close="closeUnitManag">
      <div class="ns-form-title titleUnit">
        <div class="title">单位管理</div>
        <a-button type="primary" @click="addGroup">新增分组</a-button>
        <a-button type="primary" @click="addUnit">新增单位</a-button>
      </div>
      <!-- <div class="addButton">
      </div> -->
      <div class="treePart">
        <div
          style="
            width: 100%;
            height: 7%;
            display: flex;
            justify-content: center;
            align-items: center;
          ">
          <a-select
            ref="select"
            :value="unitTreeParams.id"
            allowClear
            style="width: 96%"
            placeholder="选择分组"
            @change="handleChange">
            <a-select-option v-for="(item, index) in groupData" :key="index" :value="item.id">
              {{ item.cnValue }}
            </a-select-option>
          </a-select>
        </div>
        <a-tree
          :expanded-keys="unitExpandedKeys"
          :selectedKeys="unitSelectedKeys"
          :tree-data="unitTreeData"
          v-if="unitTreeData && unitTreeData.length > 0"
          class="draggable-tree"
          block-node>
          <template #title="data">
            <div class="treeRow">
              <div>
                <span>{{ data.cnValue }}</span>
              </div>
              <div class="actionMore">
                <EditOutlined v-if="!data.parentId" @click="editGroup(data)" />
                <EditOutlined v-else @click="editUnit(data)" />
                <MinusCircleOutlined style="margin-left: 6px" @click="delUnit(data)" />
                <PlusCircleOutlined
                  v-if="!data.parentId"
                  style="margin-left: 6px"
                  @click="addUnit(data)" />
              </div>
            </div>
          </template>
        </a-tree>
      </div>
      <template #footer>
        <a-button style="margin-right: 8px" @click="closeUnitManag">取消</a-button>
      </template>
    </a-drawer>
    <!-- 新增分组管理 -->
    <ns-modal
      :visible="addGroupManage"
      :title="addGroupTitle"
      @ok="unitOrGroupOk"
      @cancel="groupCancel">
      <a-form ref="unitFormRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="分组名称" name="cnValue" :required="true">
          <a-input v-model:value="formState.cnValue" placeholder="请输入分组名称" />
        </a-form-item>
      </a-form>
    </ns-modal>
    <!-- 新增单位 -->
    <ns-modal
      :visible="addUnitManage"
      :title="addUnitTitle"
      @ok="unitOrGroupOk"
      @cancel="unitCancel">
      <a-form ref="unitFormRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="单位名称" name="cnValue" :required="true">
          <a-input v-model:value="formState.cnValue" placeholder="请输入单位名称" />
        </a-form-item>
        <a-form-item label="选择分组" name="parentId" :required="true">
          <a-select
            v-model:value="formState.parentId"
            placeholder="请选择所属分组"
            :disabled="canSelect">
            <a-select-option v-for="(item, index) in groupData" :key="index" :value="item.id">
              {{ item.cnValue }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </ns-modal>
  </div>
</template>
<script lang="ts" setup>
  import {
    ExclamationCircleOutlined,
    EditOutlined,
    PlusCircleOutlined,
    MinusCircleOutlined,
  } from '@ant-design/icons-vue';
  import { Modal } from 'ant-design-vue';
  import { computed, createVNode, reactive, ref, watchEffect, watch, toRaw } from 'vue';
  import { http } from '/nerv-lib/util/http';
  import { NsMessage } from '/nerv-lib/component';
  import { formConfig } from './config';
  import { carbonEmissionFactorLibrary } from '/@/api/carbonEmissionFactorLibrary';
  import type {
    AntTreeNodeDragEnterEvent,
    AntTreeNodeDropEvent,
    TreeProps,
  } from 'ant-design-vue/es/tree';
  import { log } from 'node:console';
  import { or } from '@vueuse/core';

  defineOptions({ name: 'OrderListIndex' });
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;
  const dynamicDisabled = computed(() => {
    return formRef.value?.validateResult && userAuthList.value?.length;
  });
  const fetch = (api, params = { orgId }, config) => {
    return http.post(api, params, config);
  };
  const selectTreeDataValue = ref<string>('');
  const mainRef = ref();
  const data = reactive({});
  let formData = ref({
    orgId: orgId.value,
  });
  const formRef = ref();
  const visible = ref(false);
  const unitManagement = ref(false);
  const searchValue = ref<string>('');
  const searchValue2 = ref<string>('');
  const disabled = ref(false);
  const treeNodeAdd = ref<boolean>(false);
  const operationTree = ref<string>('新增');
  // const showOperation = ref(false);

  const opMap: any = ref({
    type: 'add',
    fuc: () => {},
    record: {},
  });
  watchEffect(() => {
    disabled.value = opMap.value.type === 'edit';
  });
  const show = ref(true);
  const formSchema = formConfig(show);
  const casData = ref([]);
  const treeData = ref([]);
  const userAuthList = ref([]);

  // 树结构
  const x = 3;
  const y = 2;
  const z = 1;
  const genData: TreeProps['treeData'] = [];
  const checkedTreeNodeKeys = ref<string[]>();

  const generateData = (_level: number, _preKey?: string, _tns?: TreeProps['treeData']) => {
    const preKey = _preKey || '0';
    const tns = _tns || genData;

    const children = [];
    for (let i = 0; i < x; i++) {
      const key = `${preKey}-${i}`;
      tns.push({ title: key, key });
      if (i < y) {
        children.push(key);
      }
    }
    if (_level < 0) {
      return tns;
    }
    const level = _level - 1;
    children.forEach((key, index) => {
      tns[index].children = [];
      return generateData(level, key, tns[index].children);
    });
  };
  generateData(z);
  type TreeDataItem = TreeProps['treeData'][number];
  const gData = ref<TreeProps['treeData']>(genData);
  const onDragEnter = (info: AntTreeNodeDragEnterEvent) => {
    console.log(info);
    // expandedKeys 需要展开时
    // expandedKeys.value = info.expandedKeys;
  };

  const onDrop = (info: AntTreeNodeDropEvent) => {
    console.log(info);
    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;
    const dropPos = info.node.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
    const loop = (data: TreeProps['treeData'], key: string | number, callback: any) => {
      data.forEach((item, index) => {
        if (item.key === key) {
          return callback(item, index, data);
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
      });
    };
    const data = [...gData.value];

    // Find dragObject
    let dragObj: TreeDataItem;
    loop(data, dragKey, (item: TreeDataItem, index: number, arr: TreeProps['treeData']) => {
      arr.splice(index, 1);
      dragObj = item;
    });
    if (!info.dropToGap) {
      // Drop on the content
      loop(data, dropKey, (item: TreeDataItem) => {
        item.children = item.children || [];
        /// where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    } else if (
      (info.node.children || []).length > 0 && // Has children
      info.node.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, (item: TreeDataItem) => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    } else {
      let ar: TreeProps['treeData'] = [];
      let i = 0;
      loop(data, dropKey, (_item: TreeDataItem, index: number, arr: TreeProps['treeData']) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }
    gData.value = data;
  };
  const dataList: TreeProps['treeData'] = [];
  const generateList = (data: TreeProps['treeData']) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const key = node.key;
      dataList.push({ key, title: key });
      if (node.children) {
        generateList(node.children);
      }
    }
  };
  generateList(genData);

  const getParentKey = (
    key: string | number,
    tree: TreeProps['treeData'],
  ): string | number | undefined => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };
  const expandedKeys = ref<(string | number)[]>([]);
  const autoExpandParent = ref<boolean>(true);

  const onExpand = (keys: string[]) => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
  };
  watch(selectTreeDataValue, (value) => {
    const expanded = dataList
      .map((item: TreeProps['treeData'][number]) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, gData.value);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    expandedKeys.value = expanded;
    selectTreeDataValue.value = value;
    autoExpandParent.value = true;
  });
  // 筛选树结构中的数据
  const onSearchTreeData = (selectTreeDataValue: string) => {
    console.log('use value', selectTreeDataValue);
    console.log('or use this.value', value.value);
  };
  // 点击数据点的复选框
  const checkedIds = ref([]);
  const emissionList = ref([]);
  const checkTreeNode = (checkedKeys, info) => {
    checkedTreeNodeKeys.value = checkedKeys;
    checkedIds.value = [];
    info.checkedNodes.forEach((item) => {
      checkedIds.value.push(item.id);
    });
    sessionStorage.setItem('checkedTreeNode', checkedIds.value);
    emissionList.value = checkedIds.value;
    mainRef.value?.nsTableRef.reload();
  };
  // 点击新增树节点
  const addTreeNodeData = () => {
    operationTree.value = '新增';
    treeNodeAdd.value = true;
    editTreeNode.value.type = 'create';
  };
  // 编辑树节点
  const editTreeNodeData = (data) => {
    operationTree.value = '编辑';
    treeNodeAdd.value = true;
    editTreeNode.value.type = 'update';
    addTreeNode.value = data.emissionName;
  };
  const moveNode = (data, type: opType) => {
    const flag = type === 'up';
    http.post(carbonEmissionFactorLibrary.move, { ...data, isUp: flag }).then(() => {
      getOrgTree();
      NsMessage.success('操作成功');
    });
  };
  // 删除树节点
  const deleteTreeNode = (data) => {
    Modal.confirm({
      title: '警告',
      icon: createVNode(ExclamationCircleOutlined),
      content: '确定要删除么？',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        http
          .post(carbonEmissionFactorLibrary.delTreeNode, { orgId: orgId.value, id: data.id })
          .then(() => {
            getOrgTree();
            NsMessage.success('操作成功');
          });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  // 新增/编辑树节点点击确定
  const addTreeNode = ref();
  const handleOk = (e: MouseEvent) => {
    editTreeNode.value.emissionName = addTreeNode.value;
    editTreeNode.value.orgId = orgId.value;
    http.post(carbonEmissionFactorLibrary.creat, editTreeNode.value).then(() => {
      getOrgTree();
      NsMessage.success('操作成功');
      addTreeNode.value = '';
      treeNodeAdd.value = false;
    });
  };
  const handleCancel = () => {
    addTreeNode.value = '';
    treeNodeAdd.value = false;
  };
  // 获取排放分类树
  const getOrgTree = () => {
    fetch(carbonEmissionFactorLibrary.getCarbonFactorTree, { orgId: orgId.value }).then((res) => {
      gData.value = res.data;
      // 找到匹配的节点数据
      // const selectedNodes = [];
      // checkedTreeNodeKeys.value.forEach(key => {
      //   const [parentId, childId] = key.split('-').map(Number);
      //   if (parentId >= 0 && childId >= 0 && gData.value[parentId]?.children?.[childId]) {
      //     selectedNodes.push(gData.value[parentId]);
      //   }
      // });
      // 获取默认选中节点的所有id
      // getDefaultIds(selectedNodes)
    });
  };
  const defaultIds = ref([]);
  const getDefaultIds = (selectedNodes) => {
    selectedNodes.forEach((items) => {
      defaultIds.value.push(items.id);
      if (items.children) {
        getDefaultIds(items.children);
      }
    });
    emissionList.value = defaultIds.value.join(',');
    checkedIds.value = defaultIds.value;
    sessionStorage.setItem('checkedTreeNode', checkedIds.value);
  };
  getOrgTree();
  // 被选中的树节点
  const editTreeNode = ref({});
  const onSelect = (selectedKeys: string[], info: any) => {
    if (info.selected) {
      // showOperation.value = true;
      editTreeNode.value = {
        id: info.selectedNodes[0].id,
        level: info.selectedNodes[0].level,
        dataNumber: info.selectedNodes[0].dataNumber,
        sortNumber: info.selectedNodes[0].sortNumber,
        parentEmissionId: info.selectedNodes[0].parentEmissionId,
      };
    } else {
      editTreeNode.value = {};
    }
  };

  const onSearch = () => {
    console.log(searchValue.value);
    getOrgTree({ orgName: searchValue.value, orgId });
  };

  const tableFetch = (params) => {
    console.log(params, 'sdfasfasdfasdfasdf');

    tableConfig.value.params = {
      ...mainRef.value.params,
      ...params,
    };

    setTimeout(() => {
      mainRef.value?.nsTableRef.reload();
    }, 100);
  };

  const handleSelect = (selectedKeys: any, info: any) => {
    fetch(carbonEmissionFactorLibrary.queryDeptTree, { orgId: info.node?.orgInfo.orgId }).then(
      (res) => {
        treeData2.value = res.data;
      },
    );
    tableFetch({ orgId: info.node?.orgInfo.orgId });
  };

  const onClose = () => {
    visible.value = false;
    formData.value = {
      orgId: orgId.value,
    };
    userAuthList.value.splice(0);
  };
  const closeUnitManag = () => {
    unitTreeParams.value = {
      grp: 'MEASUREMENT_UNIT',
    };
    unitManagement.value = false;
  };
  const onEdit = () => {
    formRef.value?.triggerSubmit().then(() => {
      console.log(formData.value, 'formData.value');
      // if (!userAuthList.value.length) {
      //   NsMessage.error('请添加用户权限');
      //   return;
      // }

      opMap.value.fuc && opMap.value.fuc({ ...formData.value });
    });
  };
  const doWnload = (url: any) => {
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.href = encodeURI(url);
    //设置下载的文件名
    // a.download = fileName.value;
    //触发a标签的点击事件，进行下载
    a.click();
  };
  const tableConfig = ref({
    title: '数据库',
    api: carbonEmissionFactorLibrary.getTableList,
    params: {
      orgId,
      emissionList,
    },
    headerActions: [
      {
        label: '新增',
        name: 'userAdd',
        type: 'primary',
        handle: () => {
          opMap.value.type = 'add';
          setTimeout(() => {
            formData.value = {
              carbonEmissionPrefix: 't',
              numberOfReferences: '',
              orgId: orgId.value,
            };
            userAuthList.value.splice(0);
          });
          opMap.value.fuc = (formData: any) => {
            formData.emissionType = formData.emissionType[formData.emissionType.length - 1];
            return http.post(carbonEmissionFactorLibrary.creatOrUpdate, formData).then(() => {
              mainRef.value?.nsTableRef.reload();
              visible.value = false;
              NsMessage.success('操作成功');
            });
          };
          show.value = false;
          visible.value = true;
        },
      },
      {
        label: '导入',
        type: 'primary',
        name: 'carbonEmissionFactorLibraryImport',
        extra: {
          api: carbonEmissionFactorLibrary.import, // 导入接口名
          params: {
            orgId,
          },
          title: '排放源', // 弹窗title
          templateName: 'emissionSource', // 所使用的文件名称
          indexName: '设备id', // 匹配类型字段
          message: [
            { label: '1、若必填项未填写，则不能进行导入操作' },
            { label: `2、当重复时，则更新数据。` },
            { label: '3、数据将从模版的第五行进行导入。' },
            { label: '4、文件导入勿超过5MB。' },
          ],
        },
      },
      {
        label: '导出',
        type: 'primary',
        handle: () => {
          // console.log( mainRef.value.nsTableRef.tableState.selectedRowKeys)
          const exportQuery = {
            orgId: orgId.value,
            pageNum: 1,
            pageSize: 999,
            ids: mainRef.value.nsTableRef.tableState.selectedRowKeys,
          };
          const config = {
            responseType: 'blob',
          };
          fetch(carbonEmissionFactorLibrary.export, exportQuery, config)
            .then((res) => {
              // 创建一个 URL 对象，指向图片数据的 blob
              const url = window.URL.createObjectURL(new Blob([res]));
              // 创建一个 <a> 标签，用于触发下载
              const link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', 'carbonFactor.xlsx'); // 设置下载的文件名
              document.body.appendChild(link);
              link.click();

              // 清理 URL 对象
              window.URL.revokeObjectURL(url);
              mainRef.value.nsTableRef.tableState.selectedRowKeys = [];
            })
            .catch((error) => {
              console.error('下载失败：', error);
            });
        },
      },
      {
        label: '批量删除',
        type: 'primary',
        name: 'userBatchDel',
        dynamicDisabled: (data: any) => {
          return data.list.length === 0;
        },
        confirm: true,
        isReload: true,
        isClearCheck: true,
        api: carbonEmissionFactorLibrary.del,
        dynamicParams: { ids: 'id[]' },
      },
      {
        label: '单位管理',
        type: 'primary',
        name: 'userAdd',
        handle: () => {
          (unitManagement.value = true),
            fetch(carbonEmissionFactorLibrary.findOutermost, { grp: 'MEASUREMENT_UNIT' }).then(
              (res) => {
                groupData.value = res.data;
              },
            );
          getUnitTree();
        },
      },
    ],
    columns: [
      {
        title: 'id',
        customRender: (text: any) => {
          return text.index + 1;
        },
      },
      {
        title: '排放源',
        dataIndex: 'emissionSources',
      },
      {
        title: '排放类型',
        dataIndex: 'emissionTypeColumn',
      },
      {
        title: '排放气体',
        dataIndex: 'emissionGas',
      },
      {
        title: '排放环节',
        dataIndex: 'emissionProcess',
      },
      {
        title: '排放因子',
        dataIndex: 'emissionFactors',
      },
      {
        title: '排放因子单位',
        dataIndex: 'emissionFactorUnits',
      },
      {
        title: '数据来源',
        dataIndex: 'dataSources',
      },
      {
        title: '数据库',
        dataIndex: 'carbonDatabase',
      },
      {
        title: '参考文献',
        dataIndex: 'bibliography',
        ellipsis: true,
      },
      {
        title: '引用数量',
        dataIndex: 'numberOfReferences',
      },
    ],
    columnActions: {
      title: '操作',
      actions: [
        {
          label: '编辑',
          name: 'userEdit',
          handle: (record: any) => {
            userAuthList.value.splice(0);
            setTimeout(() => {
              const measurementUnit = ref([]);
              http
                .post(carbonEmissionFactorLibrary.getCarbonFactorTree, { orgId: orgId.value })
                .then((res) => {
                  measurementUnit.value = res.data;
                  http.post(carbonEmissionFactorLibrary.findById, { id: record.id }).then((res) => {
                    if (res.data.emissionType) {
                      let selectDevice = ref([Number(res.data.emissionType)]);
                      findParentIds(
                        measurementUnit.value,
                        res.data.emissionType,
                        selectDevice.value,
                      );
                      res.data.emissionType = selectDevice;
                    }
                    formData.value = res.data;
                  });
                });
            }, 10);
            opMap.value.type = 'edit';
            opMap.value.fuc = (formData: any) => {
              formData.emissionType = formData.emissionType[formData.emissionType.length - 1];
              if (formData.emissionGas.value) {
                formData.emissionGas = formData.emissionGas.value;
              }
              return http.post(carbonEmissionFactorLibrary.creatOrUpdate, formData).then(() => {
                mainRef.value?.nsTableRef.reload();
                visible.value = false;
                NsMessage.success('操作成功');
              });
            };
            show.value = true;
            visible.value = true;
          },
        },
        {
          label: '删除',
          name: 'userDelete',
          dynamicParams: { ids: 'id[]' },
          confirm: true,
          isReload: true,
          api: carbonEmissionFactorLibrary.del,
        },
      ],
    },

    formConfig: {
      schemas: [
        {
          field: 'emissionSources',
          label: '排放源',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入排放源',
            maxLength: 30,
          },
        },
        {
          field: 'emissionProcess',
          label: '排放环节',
          component: 'NsInput',
          componentProps: {
            // allowClear: true,
            placeholder: '请选择排放环节',
            maxLength: 30,
            // options: [
            //   {
            //     label: '消费环节',
            //     value: 0,
            //   }
            // ],
          },
        },
        {
          field: 'emissionGas',
          label: '排放气体',
          component: 'NsSelectApi',
          componentProps: {
            placeholder: '请选择排放气体',
            api: carbonEmissionFactorLibrary.gasAndDatabase,
            resultField: 'data',
            params: {
              orgId: orgId.value,
              emissionList,
              type: 'gas',
            },
            immediate: true,
            labelField: 'label',
            valueField: 'value',
          },
        },
        {
          field: 'carbonDatabase',
          label: '数据库名称',
          component: 'NsSelectApi',
          componentProps: {
            allowClear: true,
            placeholder: '请选择数据库名称',
            api: carbonEmissionFactorLibrary.gasAndDatabase,
            resultField: 'data',
            params: {
              orgId: orgId.value,
              emissionList,
              type: 'database',
            },
            immediate: true,
            labelField: 'label',
            valueField: 'value',
          },
        },
        {
          field: 'bibliography',
          label: '文献关键字',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入文献关键字',
            maxLength: 30,
          },
        },
      ],
      params: {},
    },
    // pagination: { defaultPageSize: 10 },
    rowKey: 'id',
  });
  function findParentIds(tree: any, targetId: number, result: any) {
    for (let item of tree) {
      if (item.children && item.children.length > 0) {
        if (item.children.some((child: any) => child.id === Number(targetId))) {
          result.unshift(item.id); // 将当前节点的id添加到结果数组的最前面
          findParentIds(tree, item.id, result); // 递归查找父级节点的id
          break; // 找到后可以退出循环
        } else {
          for (let childsItem of item.children) {
            if (childsItem.children && childsItem.children.length > 0) {
              if (childsItem.children.some((child: any) => child.id === Number(targetId))) {
                result.unshift(childsItem.id); // 将当前节点的id添加到结果数组的最前面
                findParentIds(tree, childsItem.id, result); // 递归查找父级节点的id
                break; // 找到后可以退出循环
              }
            }
          }
        }
      }
    }
  }

  // 单位管理
  const unitExpandedKeys = ref<string[]>();
  const unitSelectedKeys = ref<string[]>([]);
  const unitTreeParams = ref({
    grp: 'MEASUREMENT_UNIT',
  });
  const groupData = ref([]);
  const unitTreeData = ref<TreeProps['treeData']>(genData);
  const handleChange = (value: string) => {
    unitTreeParams.value.id = value;
    getUnitTree();
  };
  const getUnitTree = () => {
    fetch(carbonEmissionFactorLibrary.dictionaryUnitManagement, unitTreeParams.value).then(
      (res) => {
        unitTreeData.value = res.data;
      },
    );
  };
  // 新增单位管理
  const labelCol = { span: 5 };
  const wrapperCol = { span: 19 };
  const unitFormRef = ref();
  const addGroupManage = ref(false);
  const addUnitManage = ref(false);
  const canSelect = ref(false);
  const formState = ref({
    grp: 'MEASUREMENT_UNIT',
    grpDesc: '计量单位',
  });
  const addGroupTitle = ref<string>('新增分组');
  const addUnitTitle = ref<string>('新增单位');
  const addGroup = () => {
    addGroupTitle.value = '新增分组';
    addGroupManage.value = true;
  };
  const editGroup = (data) => {
    addGroupTitle.value = '编辑分组';
    addGroupManage.value = true;
    formState.value.id = data.id;
    formState.value.cnValue = data.cnValue;
  };
  const groupCancel = () => {
    addGroupManage.value = false;
    unitFormRef.value.resetFields();
    formState.value = {
      grp: 'MEASUREMENT_UNIT',
      grpDesc: '计量单位',
    };
  };
  const addUnit = (data) => {
    if (data.id) {
      canSelect.value = true;
      formState.value.parentId = data.id;
    } else {
      canSelect.value = false;
    }
    fetch(carbonEmissionFactorLibrary.findOutermost, { grp: 'MEASUREMENT_UNIT' }).then((res) => {
      groupData.value = res.data;
    });
    addUnitTitle.value = '新增单位';
    addUnitManage.value = true;
  };
  const editUnit = (data) => {
    addUnitTitle.value = '编辑单位';
    addUnitManage.value = true;
    canSelect.value = true;
    formState.value.parentId = data.parentId;
    formState.value.id = data.id;
    formState.value.cnValue = data.cnValue;
  };
  const unitCancel = () => {
    addUnitManage.value = false;
    unitFormRef.value.resetFields();
    formState.value = {
      grp: 'MEASUREMENT_UNIT',
      grpDesc: '计量单位',
    };
  };
  const unitOrGroupOk = () => {
    unitFormRef.value
      .validate()
      .then(() => {
        console.log('values', formState, toRaw(formState));
        if (formState.value.id) {
          fetch(carbonEmissionFactorLibrary.updateDictionary, formState.value).then((res) => {
            unitTreeData.value = res.data;
            if (formState.value.parentId) {
              addUnitManage.value = false;
            } else {
              addGroupManage.value = false;
            }
            unitFormRef.value.resetFields();
            formState.value = {
              grp: 'MEASUREMENT_UNIT',
              grpDesc: '计量单位',
            };
            getUnitTree();
          });
        } else {
          fetch(carbonEmissionFactorLibrary.createDictionary, formState.value).then((res) => {
            unitTreeData.value = res.data;
            if (formState.value.parentId) {
              addUnitManage.value = false;
            } else {
              addGroupManage.value = false;
            }
            unitFormRef.value.resetFields();
            formState.value = {
              grp: 'MEASUREMENT_UNIT',
              grpDesc: '计量单位',
            };
            getUnitTree();
          });
        }
      })
      .catch((error) => {
        console.log('error', error);
      });
  };
  // 删除单位管理的树节点
  const delUnit = (data) => {
    formState.value.id = data.id;
    Modal.confirm({
      title: '警告',
      content: '确定要删除吗?',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        fetch(carbonEmissionFactorLibrary.delDictionary, formState.value).then((res) => {
          message.success('操作成功！');
          formState.value = {
            grp: 'MEASUREMENT_UNIT',
            grpDesc: '计量单位',
          };
          getUnitTree();
        });
      },
      onCancel() {
        formState.value = {
          grp: 'MEASUREMENT_UNIT',
          grpDesc: '计量单位',
        };
        console.log('Cancel');
      },
    });
  };
</script>
<style lang="less" scoped>
  .main {
    background-color: @ns-content-bg;
    display: flex;
  }
  .left {
    width: 300px;
    // max-height: calc(100vh - 96px);
    margin-right: @ns-gap;
    min-width: fit-content;
    > div {
      border-radius: @ns-border-radius;
      background-color: @white;
      // box-shadow: @ns-content-box-shadow;
      flex: 1;
    }
    display: flex;
    flex-direction: column;
    .top {
      position: relative;
      .addTreeNode {
        width: 100%;
        padding: 16px;
        position: absolute;
        bottom: 0;
      }
    }
  }
  .right {
    flex: 1;
    min-width: 0;
  }
  .top {
    overflow: auto;
    // height: 50%;
    // border-bottom: 5px solid rgb(229, 235, 240);
    // overflow-y: auto;
  }
  .ns-form-title {
    font-weight: bold;
    user-select: text;
    padding: 16px;
    margin-bottom: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9e9e9;
  }
  .titleUnit {
    font-weight: bold;
    user-select: text;
    padding: unset;
    margin-bottom: unset;
    padding-bottom: unset;
    border-bottom: unset;
    width: 70%;
    height: 5vh;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-left: 10%;
  }
  .title {
    text-align: left;
    height: 32px;
    line-height: 32px;
    font-weight: bold;
    user-select: text;
    position: relative;
    padding-left: 9px;
  }
  .title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    height: 13px;
    width: 3px;
    border-radius: 1px;
    background-color: #2778ff;
  }
  .treeRow {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .addButton {
    width: 70%;
    height: 5vh;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }
  .treePart {
    width: 70%;
    height: 100%;
    display: flex;
    border: 1px solid #bfbfbf;
    margin-left: 10%;
    flex-direction: column;
    border-radius: 12px;
  }
  .actionMore {
    display: none;
  }
  :deep(.ant-tree-node-content-wrapper) {
    &:hover {
      .actionMore {
        display: block;
      }
    }
  }
  :deep(
      .ant-form-item-label
        > label.ant-form-item-required:not(.ant-form-item-required-mark-optional)::before
    ) {
    display: none !important;
  }
  :deep(.ant-form-item-label) {
    z-index: 20;
    text-align: right;
    width: 27%;
  }
</style>
 
