<template>
  <div :class="prefixCls">
    <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
      <div class="m-2 mr-0 w-1/4 xl:w-1/5 tree">
        <lrPanel title="列表关联字段">
          <a-radio-group v-bind="attrs" v-model:value="config.left.colField" size="large">
            <template v-for="item in colslist" :key="`${item.value}`">
              <a-radio :value="item.value" :style="radioStyle">
                {{ item.label }}
              </a-radio>
            </template>
          </a-radio-group>
        </lrPanel>
      </div>
      <div class="m-2 mr-0 w-3/4 xl:w-4/5 overflow-hidden">
        <div :class="`${prefixCls}_content`">
          <lrPanel title="设置">
            <a-form style="padding: 8px; 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: 8px">
                <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: center">
                <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-if="config.left.dataType == 3" style="text-align: left">
                <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-form-item label="数据源">
                    <a-select
                      v-model:value="config.left.dataCode"
                      placeholder="请选择数据源"
                      size="mini"
                      :options="dataSourceOptions"
                      @change="handleDataSourceChange"
                    />
                  </a-form-item>
                  <a-form-item label="关联字段">
                    <a-select
                      v-model:value="config.left.dataValueKey"
                      placeholder="请选择选项关联字段"
                      size="mini"
                      :options="myColNameList"
                    />
                  </a-form-item>
                  <a-form-item label="显示字段">
                    <a-select
                      v-model:value="config.left.dataLabelKey"
                      placeholder="请选择选项显示字段"
                      size="mini"
                      :options="myColNameList"
                    />
                  </a-form-item>
                  <a-form-item label="id字段">
                    <a-select
                      v-model:value="config.left.dataIdKey"
                      placeholder="请选择选项id字段"
                      size="mini"
                      :options="myColNameList"
                    />
                  </a-form-item>
                  <a-form-item label="pid字段">
                    <a-select
                      v-model:value="config.left.dataPIdKey"
                      placeholder="请选择选项父级id字段"
                      size="mini"
                      :options="myColNameList"
                    />
                  </a-form-item>
                </a-form>
              </div>
            </a-form>
          </lrPanel>
        </div>
      </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, reactive } 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';
  // api
  import { Get_SysDataItemLoad } from '@/api/demo/formModule';
  import { fun_LoadDataBaseInfo, fun_GetDataColName } from '@/api/demo/dbsource';

  // 表单栅格
  const labelCol = { span: 4 };
  const wrapperCol = { span: 20 };
  // config
  const config: any = inject('formConfig');
  // message
  const { createMessage } = useMessage();

  const radioStyle = reactive({
    display: 'flex',
    height: '30px',
    lineHeight: '30px',
  });

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

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

  // 静态数据树
  const treeOptions = ref<TreeItem[]>([]);
  // 静态数据按钮
  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);
        },
      });
    },
  });
  // 获取树
  const staticDataTreeRef = ref<Nullable<TreeActionType>>(null);
  function getTree(): any {
    return unref(staticDataTreeRef);
  }
  // 开启弹窗
  function handleParentNodeAdd() {
    pData = undefined;
    dialogTitle = '添加父级选项';
    dialogVisible.value = true;
  }
  // 关闭弹窗
  function closeDialog() {
    dialogForm.value = { key: '', label: '', value: '' };
    dialogVisible.value = false;
  }
  // 子节点添加弹窗
  function handleNodeAdd(data) {
    pData = data;
    dialogTitle = `添加子选项`;
    dialogVisible.value = true;
  }
  // 子节点添加
  function appendNodeByKey(parentKey: string | null = null, { label, value }) {
    getTree().insertNodeByKey({
      parentKey: parentKey,
      node: {
        key: config.left.colField,
        label: label,
        value: value,
      },
      // 往后插入
      push: 'push',
    });
    change();
  }
  // 子节点删除
  function deleteNodeByKey(value: string) {
    getTree().deleteNodeByKey(value);
    change();
  }
  // 添加
  function handleDialogAdd() {
    if (!config.left.colField) {
      createMessage.error('请先选择列表关联字段');
    } else 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 + '"');
  }

  // 数据字典
  const dataCodes: any = ref<TreeItem[]>([]);
  const dataSourceOptions: any = [];
  const myColNameList: any = ref([]);

  async function fetch() {
    // 静态数据
    treeOptions.value = config.left.options;
    // 数据字典
    dataCodes.value = await Get_SysDataItemLoad();
    // 远端数据-数据源
    setdataSourceOptions();
  }

  // 远端数据-数据源
  async function setdataSourceOptions() {
    const loadDataBaseInfo: any = await fun_LoadDataBaseInfo({});
    if (loadDataBaseInfo.items) {
      loadDataBaseInfo.items.forEach((item) => {
        dataSourceOptions.push({ value: item.code, label: item.name });
      });
    }
  }

  // 远端数据-关联字段、显示字段、id字段、pid字段
  async function handleDataSourceChange() {
    let dataColName: any = await fun_GetDataColName({ code: config.left.dataCode });
    dataColName.forEach((element) => {
      myColNameList.value.push({ value: element, label: element });
    });
  }

  // 切换静态数据、数据字典、远端数据
  function handleDataTypeChange() {
    config.left.dataCode = '';
    config.left.dataIdKey = '';
    config.left.dataPIdKey = '';
    config.left.dataValueKey = '';
    config.left.dataLabelKey = '';
  }

  onMounted(() => {
    fetch();
  });

  const prefixCls = 'l-left';
</script>
<style lang="less" scoped>
  .l-left {
    width: 100%;
    height: 100%;
    background-color: @border-color-base;

    &_content {
      background-color: @border-color-base;
      height: 100%;
    }
  }

  .tree {
    overflow: auto;
    height: calc(100vh - 60px);
  }
</style>
