<template>
  <div>
    <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
      <div class="m-2 mr-0 w-1/4 xl:w-1/5 overflow-hidden bg-white">
        <BasicTree
          ref="leftTreeTreeRef"
          title="列表关联字段"
          checkable
          :treeData="colslist"
          :value="config.left.colField"
          :defaultExpandAll="true"
          :fieldNames="{ key: 'value', title: 'label' }"
          @check="handleCheck"
        />
      </div>
      <div class="l-rblock m-2 mr-0 overflow-hidden bg-white">
        <lrPanel title="设置">
          <a-form style="padding: 16px; maxwidth: 400px" size="mini" ref="form" label-width="80px">
            <a-form-item label="树形标题">
              <a-input v-model:value="config.left.title" />
            </a-form-item>
            <div style="text-align: center; margin-bottom: 16px">
              <a-radio-group
                v-model:value="config.left.dataType"
                size="mini"
                button-style="solid"
                @change="handleDataTypeChange"
              >
                <a-radio-button :value="1">静态数据</a-radio-button>
                <a-radio-button :value="2">数据字典</a-radio-button>
                <a-radio-button :value="3">数据源</a-radio-button>
              </a-radio-group>
            </div>
            <!--静态数据-->
            <div v-if="config.left.dataType == 1" style="text-align: left">
              <BasicTree
                :treeData="treeOptions"
                ref="staticDataTreeRef"
                :fieldNames="{ key: 'value', title: 'label' }"
                :actionList="actionList"
                :clickRowToExpand="false"
                :defaultExpandAll="true"
              />
              <div style="margin-left: 22px">
                <a-button size="mini" type="text" @click="handleParentNodeAdd">
                  <PlusCircleOutlined />
                  添加父级
                </a-button>
              </div>
            </div>
            <!--数据字典-->
            <div v-else-if="config.left.dataType == 2" style="text-align: left">
              <a-tree-select
                v-model:value="config.left.dataCode"
                :tree-data="dataCodes"
                :field-names="{ label: 'itemName', value: 'itemCode' }"
                placeholder="请选择数据字典"
                style="width: 300px"
              />
            </div>
            <!--远端数据-->
            <div v-else style="text-align: left">
              <!-- <a-form-item label="数据源">
                <l-select
                  v-model="config.left.dataCode"
                  placeholder="请选择数据源"
                  size="mini"
                  :options="lr_dataSource"
                  labelKey="f_Name"
                  valueKey="f_Code"
                  @change="handleDataSourceChange"
                />
              </a-form-item>
              <a-form-item label="关联字段">
                <l-select
                  v-model="config.left.dataValueKey"
                  placeholder="请选择选项关联字段"
                  size="mini"
                  :options="myColNameList"
                />
              </a-form-item>
              <a-form-item label="显示字段">
                <l-select
                  v-model="config.left.dataLabelKey"
                  placeholder="请选择选项显示字段"
                  size="mini"
                  :options="myColNameList"
                />
              </a-form-item>
              <a-form-item label="id字段">
                <l-select
                  v-model="config.left.dataIdKey"
                  placeholder="请选择选项id字段"
                  size="mini"
                  :options="myColNameList"
                />
              </a-form-item>
              <a-form-item label="pid字段">
                <l-select
                  v-model="config.left.dataPIdKey"
                  placeholder="请选择选项父级id字段"
                  size="mini"
                  :options="myColNameList"
                />
              </a-form-item> -->
            </div>
          </a-form>
        </lrPanel>
      </div>
    </PageWrapper>
  </div>

  <a-modal
    :open="dialogVisible"
    :title="dialogTitle"
    :height="200"
    @ok="handleDialogAdd"
    @cancel="closeDialog"
  >
    <div>
      <a-form :model="dialogForm" size="mini" :rules="dialogRules" label-width="80px">
        <a-form-item label="选项名" prop="label">
          <a-input v-model:value="dialogForm.label" />
        </a-form-item>
        <a-form-item label="选项值" prop="value">
          <a-input v-model:value="dialogForm.value" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { h, ref, inject, defineProps, unref, onMounted } from 'vue';
  import lrPanel from '@/components/lrPanel';
  import { PageWrapper } from '@/components/Page';
  import { BasicTree, TreeItem, TreeActionType, TreeActionItem } from '@/components/Tree';
  import { useMessage } from '@/hooks/web/useMessage';
  import { PlusCircleOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';

  import { Get_SysDataItemLoad } from '@/api/demo/formModule';
  import { getDataBasePageList } from '@/api/database';

  // config
  const config = inject('formConfig');
  // message
  const { createMessage } = useMessage();

  // 树目录--------------------
  // 定义props,树目录
  const props = defineProps({
    colslist: {
      type: Object,
      default: () => ({}), // 设置默认值为一个空对象
    },
  });
  const colslist = props.colslist;

  // 展开全部
  const leftTreeTreeRef = ref<Nullable<TreeActionType>>(null);
  // 树的选择变动
  function handleCheck(keys) {
    if (keys.length != 1) {
      keys.shift();
    }
    unref(leftTreeTreeRef)?.setCheckedKeys(keys);
  }

  // 静态数据--------------------
  // 弹窗
  let dialogTitle = '添加选项';
  const dialogVisible = ref(false);
  const dialogForm = ref({ label: '', value: '' });
  let dialogRules = {
    label: { required: true, message: '请输入选项名', trigger: 'null' },
    value: { required: true, message: '请输入选项值', trigger: 'null' },
  };
  let pData = undefined;

  // 静态数据树
  // const treeOptions: TreeItem[] = config.left.options;
  const treeOptions = ref<TreeItem[]>([]);
  const staticDataTreeRef = ref<Nullable<TreeActionType>>(null);
  const actionList: TreeActionItem[] = [];
  actionList.push({
    render: (node) => {
      return h(PlusOutlined, {
        class: 'ml-2',
        onClick: () => {
          handleNodeAdd(node);
        },
      });
    },
  });
  actionList.push({
    render: (node) => {
      return h(DeleteOutlined, {
        class: 'ml-2',
        onClick: () => {
          deleteNodeByKey(node.value);
        },
      });
    },
  });

  function getTree() {
    return unref(staticDataTreeRef);
  }
  // 开启弹窗
  function handleParentNodeAdd() {
    pData = undefined;
    dialogTitle = '添加父级选项';
    dialogVisible.value = true;
  }
  // 关闭弹窗
  function closeDialog() {
    dialogForm.value = { label: '', value: '' };
    dialogVisible.value = false;
  }
  // 子节点添加弹窗
  function handleNodeAdd(data) {
    pData = data;
    dialogTitle = `添加【${data.label}】的子选项`;
    dialogVisible.value = true;
  }
  // 子节点添加
  function appendNodeByKey(parentKey: string | null = null, { label, value }) {
    getTree().insertNodeByKey({
      parentKey: parentKey,
      node: {
        label: label,
        value: value,
      },
      // 往后插入
      push: 'push',
    });
    change();
  }
  // 子节点删除
  function deleteNodeByKey(value: string) {
    getTree().deleteNodeByKey(value);
    change();
  }
  // 添加
  function handleDialogAdd() {
    if (dialogForm.value) {
      if (find(dialogForm.value.value)) {
        createMessage.error('选项值重复');
      } else {
        if (pData) {
          appendNodeByKey(pData.value, dialogForm.value);
        } else {
          appendNodeByKey(null, dialogForm.value);
        }
        getTree().expandAll(true);
        change();
        closeDialog();
      }
    }
  }
  // 刷新config
  function change() {
    config.left.options = getTree().getTreeData();
  }
  // 寻找
  function find(value) {
    return JSON.stringify(getTree().getTreeData()).includes('"value":' + '"' + value + '"');
  }

  // 数据字典------------------
  // 数据字典tree
  const dataCodes = ref<TreeItem[]>([]);

  function handleDataTypeChange() {
    config.left.dataIdKey = '';
    config.left.dataPIdKey = '';
    config.left.dataCode = '';
    config.left.dataValueKey = '';
    config.left.dataLabelKey = '';
  }
  // 数据字典
  // 数据字典tree
  async function fetch() {
    dataCodes.value = await Get_SysDataItemLoad();
    console.log(config.left);
    treeOptions.value = config.left.options;
  }

  onMounted(() => {
    fetch();
  });
</script>
<style lang="scss" scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
