<template>
  <div class="main">
    <div class="left">
      <div class="top">
        <a-form style="width: 100%;margin: 0 auto;">
          <div class="ns-form-title"><span>因子分类</span></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="searchValue"
                  placeholder="请输入关键词"
                  @search="onSearchTreeData"
                />
              </a-col>
            </a-row>
          </div>
        </a-form>
        <a-tree
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          :tree-data="gData"
          @expand="onExpand"
          style="padding: 0 16px !important;"
        >
          <template #title="{ title }">
            <span v-if="title.indexOf(searchValue) > -1">
              {{ title.substring(0, title.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{ title.substring(title.indexOf(searchValue) + searchValue.length) }}
            </span>
            <span v-else>{{ title }}</span>
          </template>
        </a-tree>
      </div>
    </div>
    <div class="right">
      <a-table 
        :columns="columns" 
        :data-source="tableData" 
        bordered
        :pagination="false">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'action'">
            <span>
              <a @click="editData(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="delData(record)">删除</a>
            </span>
          </template>
        </template>
        <template #title>
          <div class="ns-table-title"><span>排放因子库</span></div>
          <div class="buttonGroup">
            <a-button type="primary" @click="addNewData">新增</a-button>
          </div>
        </template>
      </a-table>
      <a-pagination 
        :current="queryParams.pageNum"
        :total="total"
        :page-size="queryParams.pageSize"
        style="display: flex;justify-content: center;margin-top: 16px;"
        :show-size-changer="true"
        :show-quick-jumper="true"
        @change="onChange" />
        <!-- 新增/编辑 -->
        <a-drawer
          :width="500"
          :visible="visible"
          :body-style="{ paddingBottom: '80px' }"
          :footer-style="{ textAlign: 'right' }"
          destroyOnClose
          @close="onClose">
          <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-item ref="name" label="能源种类" name="energyType">
              <a-input v-model:value="formState.energyType" placeholder="请输入能源种类" />
            </a-form-item>
            <a-form-item label="计量单位" name="unit">
              <a-cascader v-model:value="formState.unit" :options="options" />
            </a-form-item>
            <a-form-item label="自动采集节点" name="collectionNode">
              <a-tree-select
                v-model:value="formState.collectionNode"
                :tree-line="true"
                :tree-data="treeData"
                tree-node-filter-prop="title"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item label="计算碳排" name="isComputeCarbon">
              <a-radio-group v-model:value="formState.isComputeCarbon" @change="changeRadio">
                <a-radio :value="0">是</a-radio>
                <a-radio :value="1">否</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="排放类型" name="emissionType">
              <a-select v-model:value="formState.emissionType" placeholder="请选择排放类型">
                <a-select-option v-for="(item, index) in emissionTypeDic" :key="index" :value="item.cnValue">
                  {{ item.cnValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
          <template #footer>
            <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
            <a-button type="primary" @click="onSubmit">确定</a-button>
          </template>
        </a-drawer>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import type { TreeProps } from 'ant-design-vue';
  import { Pagination } from 'ant-design-vue';
  import { columns } from '../config';
  import { http } from '/nerv-lib/util/http';
  defineOptions({
    energyType: 'quickCalculation', // 与页面路由name一致缓存才可生效
    components: {
      'a-pagination': Pagination,
    },
  });
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;
  const fetch = (api, params = { orgId } ) => {
    return http.post(api, params);
  };
  // 数结构
  const x = 3;
  const y = 2;
  const z = 1;
  const genData: TreeProps['treeData'] = [];

  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);

  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 searchValue = ref<string>('');
  const autoExpandParent = ref<boolean>(true);
  const gData = ref<TreeProps['treeData']>(genData);

  const onExpand = (keys: string[]) => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
  };

  watch(searchValue, 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;
    searchValue.value = value;
    autoExpandParent.value = true;
  });
  // 列表数据
  const total = ref<number>()
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
  })
  const tableData = [
    {
      key: '1',
      name: 'John Brown',
      money: '￥300,000.00',
      address: 'New York No. 1 Lake Park',
    },
    {
      key: '2',
      name: 'Jim Green',
      money: '￥1,256,000.00',
      address: 'London No. 1 Lake Park',
    },
    {
      key: '3',
      name: 'Joe Black',
      money: '￥120,000.00',
      address: 'Sidney No. 1 Lake Park',
    },
  ];
  // 分页器
  const onChange = (pageNumber: number,size: number) => {
    queryParams.value.pageNum = pageNumber;
    queryParams.value.pageSize = size;
    // getTableList()
  };
  // 新增/编辑
  const formRef = ref();
  const labelCol = { span: 5 };
  const wrapperCol = { span: 19 };
  const formState = ref({})
  const visible = ref(false);
  
  // 定义form表单的必填
  const rules: Record<string, Rule[]> = {
    energyType: [{ required: true, message: '请输入能源种类', trigger: 'change' }],
    isComputeCarbon: [{ required: true, message: '请选择是否计算碳排', trigger: 'change' }]
  };
  // 点击编辑按钮
  const editData = (record) =>{
    visible.value = true
  };
  // 关闭新增抽屉
  const onClose = () => {
    visible.value = false;
    formRef.value.resetFields();
  };
</script>

<style lang="less" scoped>
  .main {
    background-color: @ns-content-bg;
    display: flex;
    height: 100%;
  }
  .left {
    width: 300px;
    margin-right: @ns-gap;
    min-width: fit-content;
    > div {
      background-color: @white;
      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;
    height: 100%;
    background: #ffffff;
  }
  ::v-deep .ant-table-container{
    padding: 0px 16px;
  }
  .top {
    overflow: auto;
  }
  .ns-form-title{
    font-weight: bold;
    user-select: text;
    padding: 16px;
    margin-bottom: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9e9e9;
  }
  ::v-deep .ant-table-title{
    display: flex;
    height: 100%;
    align-items: center;
  }
  .ns-table-title{
    font-weight: bold;
  }
  .buttonGroup{
    margin-left: 1vw;
    width: 5vw;
    display: flex;
    justify-content: space-around;
  }
</style>
<style scoped>
  th.column-money,
  td.column-money {
    text-align: right !important;
  }
</style>