<template>
  <!-- 分组编辑按钮 -->
  <editDrawer ref="editDrawerRef" :params="defaultParams" @sure="handleOk" />
  <editCalDrawer ref="editDrawerCalRef" :params="defaultParams" @sure="handleOk" />
  <editGroup ref="editGroupRef" :params="defaultParams" @sure="handleOk" />
  <editFormula ref="editFormulaRef" :params="defaultParams" @sure="handleOk" />

  <NsModalFrom ref="modalFormRef" v-bind="nsModalFormConfig" />
  <div class="groupContainer">
    <div class="tree">
      <ns-tree-api ref="treeRef" v-bind="tConfig" @select="handleSelect">
        <template #title="data">
          <div class="treeRow">
            <div>
              <ns-icon
                :name="
                  data?.id === 'all'
                    ? 'common'
                    : data.pointType === 'GROUPING_NODE'
                    ? 'fenzujiedian'
                    : 'jisuanjiedian'
                " />
              <span style="padding-left: 8px">{{ data.pointName }}</span>
            </div>
            <a-dropdown>
              <ns-icon name="actionMore" size="14" class="actionMore" />
              <template #overlay>
                <a-menu>
                  <template v-for="(item, index) in filterAction(actionList, data)" :key="index">
                    <a-menu-item @click="item.func(data)">
                      <span>{{ item.title }}</span>
                    </a-menu-item>
                  </template>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
        </template>
      </ns-tree-api>
    </div>
    <ns-view-list-table v-show="defaultType" class="table" v-bind="config" ref="tableRef" />
    <ns-view-list-table v-show="!defaultType" class="table" v-bind="configCal" ref="tableCalRef" />
  </div>
</template>
<script lang="ts" setup>
  import { createVNode, nextTick, onMounted, ref } from 'vue';
  import { tableConfig, treeConfig, tableConfigCal, formSchema } from './config';
  import { useParams } from '/nerv-lib/use';
  import editDrawer from './edit.vue';
  import editCalDrawer from './editCal.vue';
  import editGroup from './editGroup.vue';
  import editFormula from './editFormula.vue';
  import { NsMessage, NsModal } from '/nerv-lib/component';
  import NsModalFrom from '/@/components/ns-modal-form.vue';
  import { group } from '/@/api/deviceManage';
  import { http } from '/nerv-lib/util/http';

  type opType = 'up' | 'down';
  const { getParams } = useParams();
  const modalFormRef = ref();
  const tableRef = ref();
  const tableCalRef = ref();
  const editDrawerRef = ref();
  const editDrawerCalRef = ref();
  const editGroupRef = ref();
  const editFormulaRef = ref();
  const treeRef = ref();
  const defaultType = ref(true);
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  const defaultParams = ref({
    orgId: result,
    energyType: 'ELECTRICITY_USAGE',
    id: '',
    hxDeviceGroupId: '',
  });

  const config = tableConfig(editDrawerRef, editGroupRef, editFormulaRef, defaultParams);
  const configCal = tableConfigCal(editDrawerCalRef, editGroupRef, editFormulaRef, defaultParams);
  const tConfig = treeConfig(result);
  const nsModalFormConfig = ref({
    api: group.creatOrUpdate,
    data: {},
    title: '新增',
    schemas: formSchema,
    extraModalConfig: {
      bodyStyle: { paddingBottom: 0 },
    },
    success: () => {
      treeRef.value?.treeReload();
    },
  });
  nextTick(() => {
    console.log(modalFormRef.value, 'modal');
  });

  const addNodeSon = (data) => {
    console.log(data);

    nsModalFormConfig.value.title = '新增';
    nsModalFormConfig.value.data = {
      isCreate: true,
      orgId: result,
      energyType: data.formModel?.energyType,
    };
    if (data.id !== 'all') {
      nsModalFormConfig.value.data.pid = data.id;
      nsModalFormConfig.value.data.isCreatSon = true;
    }
    modalFormRef.value?.toggle();
  };
  const editNode = (data) => {
    nsModalFormConfig.value.title = '编辑';
    setTimeout(() => {
      nsModalFormConfig.value.data = data;
    }, 1);
    modalFormRef.value?.toggle();
  };
  const moveNode = (data, type: opType) => {
    const flag = type === 'up';
    http.post(group.move, { ...data, isUp: flag }).then(() => {
      treeRef.value?.treeReload();
      NsMessage.success('操作成功');
    });
  };

  const deleteNode = (record) => {
    NsModal.confirm({
      centered: true,
      title: '提示',
      content: '确定删除吗?',
      onOk: () => {
        http.post(group.del, { id: record.id }).then(() => {
          treeRef.value?.treeReload();
          treeRef.value?.clearSelectedKeys();
          NsMessage.success('操作成功');
        });
      },
    });
  };
  const filterAction = (actions, data) => {
    let list: string | any[] = ['addNodeSon', 'editNode', 'deleteNode'];
    //判断逻辑先后不可颠倒
    // 最后一个以及中间的不会包含isFirst，即支持上移
    if (!data?.isFirst) {
      list.push('moveUp');
    }
    // 第一个以及中间的不会包含isEnd，即支持下移
    if (!data?.isEnd) {
      list.push('moveDown');
    }
    // 只有一条即不支持上移也不支持下移
    if (data.isOnlyOne) {
      list = ['addNodeSon', 'editNode', 'deleteNode'];
    }
    // 全部根节点
    if (data.id === 'all') {
      list = ['addNodeSon'];
    }
    return actions.filter(({ key }) => list.includes(key));
  };
  const actionList = [
    { title: '新增子节点', key: 'addNodeSon', func: (data) => addNodeSon(data) },
    { title: '编辑', key: 'editNode', func: (data) => editNode(data) },
    { title: '上移', key: 'moveUp', func: (data) => moveNode(data, 'up') },
    { title: '下移', key: 'moveDown', func: (data) => moveNode(data, 'down') },
    { title: '删除', key: 'deleteNode', func: (data) => deleteNode(data) },
  ];
  const handleSelect = (key, record) => {
    //清除选中行数据
    tableRef.value?.nsTableRef.clearCheck();
    tableCalRef.value?.nsTableRef.clearCheck();
    const {
      node: { pointType, id, energyType },
    } = record;
    defaultParams.value.energyType = energyType;
    defaultParams.value.id = id;
    defaultParams.value.hxDeviceGroupId = id;
    defaultType.value = pointType === 'GROUPING_NODE';
    defaultType.value
      ? tableRef.value?.nsTableRef.reload()
      : tableCalRef.value?.nsTableRef.reload();
  };

  const handleOk = () => {
    defaultType.value
      ? tableRef.value?.nsTableRef.reload()
      : tableCalRef.value?.nsTableRef.reload();
  };
</script>
<style lang="less" scoped>
  .groupContainer {
    height: 100%;
    // overflow-y: auto;
    background-color: @ns-content-bg;
    display: flex;
    // gap: @ns-gap;
    .tree,
    .table {
      background-color: @white;
      border-radius: @ns-border-radius;
    }

    .tree {
      overflow-y: auto;
      margin-right: @ns-gap;
      :deep(.ant-spin-nested-loading) {
        width: 300px;
        background-color: @white;
      }
    }
    .table {
      flex: 1;
      min-width: 0;
    }
  }

  .actionMore {
    display: none;
  }
  :deep(.ant-tree-node-content-wrapper) {
    &:hover {
      .actionMore {
        display: block;
      }
    }
  }

  .common-style {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .treeRow {
    .common-style;
    > div:first-child {
      .common-style;
    }
  }

  .tree,
  :deep(.ns-table-search),
  // :deep(.ns-list-table),
  :deep(.ns-table-main) {
    box-shadow: @ns-content-box-shadow;
  }
</style>
