<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="表名称" prop="formName">
          <el-input
            v-model="queryParams.tableName"
            placeholder="请输入表名称进行模糊搜索"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="表单名称" prop="formName">
          <el-input
            v-model="queryParams.formName"
            placeholder="请输入表单名称进行模糊搜索"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户端类型" prop="clientType">
          <el-select v-model="queryParams.clientType" placeholder="请选择客户端类型进行精确搜索" clearable>
            <el-option
              v-for="dict in ai_form_setting_client_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="success" icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表展示 -->
    <el-card shadow="never" class="mt-4">
      <el-table v-loading="loading" :data="aiFormSettingList" @selection-change="handleSelectionChange">
        <el-table-column label="编号" align="center" prop="formSettingId"/>
        <el-table-column label="表名称" align="center" prop="tableName"/>
        <el-table-column label="表单名称" align="center" prop="formName"/>
        <el-table-column label="客户端类型" align="center" prop="clientType">
          <template #default="scope">
            <dict-tag :options="ai_form_setting_client_type" :value="scope.row.clientType"/>
          </template>
        </el-table-column>
        <el-table-column label="路径" align="center" prop="formPath" :show-overflow-tooltip="true"/>
        <el-table-column label="加载类型" align="center" prop="formLoadType" :show-overflow-tooltip="true">
          <template #default="scope">
            <dict-tag :options="ai_form_setting_load_type" :value="scope.row.formLoadType"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ai:aiFormSetting:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ai:aiFormSetting:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>


      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 设置弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="80vw" top="5vh" append-to-body>
      <el-form :model="form" ref="aiFormSettingFormRef" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="表名称" prop="tableName">
              <el-input v-model="form.tableName" readonly>
                <template #append>
                  <el-button @click="openTableSelectDialog">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表单名称" prop="formName">
              <el-input v-model="form.formName" placeholder="请输入表单名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户端类型" prop="clientType">
              <el-select v-model="form.clientType" placeholder="请选择端" clearable>
                <el-option
                  v-for="dict in ai_form_setting_client_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="路径" prop="path">
              <el-input v-model="form.formPath" placeholder="请输入路径">
<!--                <template #append>-->
<!--                  <el-button @click="openMenuSelectDialog">选择</el-button>-->
<!--                </template>-->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加载类型" prop="formLoadType">
              <el-select v-model="form.formLoadType" placeholder="请选择加载类型" clearable>
                <el-option
                  v-for="dict in ai_form_setting_load_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>

      <el-divider content-position="left">字段配置</el-divider>

      <el-table :data="form.aiFormSettingDetailList" border height="40vh" v-loading="columnLoading">
        <el-table-column label="字段名称" prop="fieldName"/>
        <el-table-column label="字段注释" prop="fieldDesc" >
          <template #default="scope">
            <el-input v-model="scope.row.fieldDesc" type="textarea"/>
          </template>
        </el-table-column>
        <el-table-column label="表单prop" prop="propName">
          <template #default="scope">
            <el-input v-model="scope.row.formProp"/>
          </template>
        </el-table-column>
        <el-table-column label="赋值标识">
          <template #default="scope">
            <el-radio-group v-model='scope.row.settingFlag'>
              <el-radio v-for='dict in ai_form_setting_flag' :key='dict.value' :value='dict.value'>{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </template>
        </el-table-column>

        <el-table-column label="字段类型">
          <template #default="scope">
            <el-select v-model="scope.row.fieldType" placeholder="请选择字段类型" clearable>
              <el-option
                v-for="dict in ai_form_setting_field_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="字段样式">
          <template #default="scope">
            <el-select v-model="scope.row.fieldStyle" placeholder="请选择字段样式" clearable>
              <el-option
                v-for="dict in ai_form_setting_field_style"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="获取字段" prop="relateTableFields" >
          <template #default="scope">
            <el-input v-model="scope.row.relateTableFields" type="textarea" placeholder="filedType是1的代表赋值，filedType是2的代表显示；例:[{fieldName:'dept_id',formProp:'deptId',fieldType:'1'},{fieldName:'dept_name',formProp:'deptName',fieldType:'2'}]"/>
          </template>
        </el-table-column>
        <el-table-column label="过滤条件" prop="relateFilterCondition" >
          <template #default="scope">
            <el-input v-model="scope.row.relateFilterCondition" type="textarea" placeholder="例:[{fieldKey:'delFlag',fieldValue:'0',conditionSymbol:'='}]"/>
          </template>
        </el-table-column>


      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSave" v-loading="buttonLoading">保 存</el-button>
          <el-button @click="dialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择表对话框 -->
    <el-dialog title='选择表信息' v-model="selectTableOpen" width='1200px' append-to-body>
      <SelectTable ref='selectTableRef' v-if='selectTableOpen'></SelectTable>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='submitSelectTable'>确 定</el-button>
        <el-button @click='selectTableOpen = false'>取 消</el-button>
      </div>
    </el-dialog>


    <!-- 选择表弹窗 -->
    <el-dialog title="选择表" v-model="tableSelectDialogVisible" width="40%" append-to-body>
      <el-input v-model="tableSearch" placeholder="根据表名称模糊搜索" clearable class="mb-4"/>
      <el-table :data="filteredTables" @row-click="handleTableSelect" height="50vh" highlight-current-row>
        <el-table-column property="tableName" label="表名"/>
        <el-table-column property="tableComment" label="表注释"/>
      </el-table>
    </el-dialog>

    <!-- 选择菜单弹窗 -->
    <el-dialog title="选择菜单" v-model="menuSelectDialogVisible" width="40%" append-to-body>
      <el-input v-model="menuSearch" placeholder="根据菜单名称模糊搜索" clearable class="mb-4"/>
      <el-table :data="filteredMenus" @row-click="handleMenuSelect" height="50vh" highlight-current-row>
        <el-table-column property="menuName" label="菜单名称"/>
        <el-table-column property="path" label="菜单路径"/>
      </el-table>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed} from 'vue';
import SelectTable from './selectTable.vue';
import {listAiFormSetting, getAiFormSetting, delAiFormSetting, addAiFormSetting, updateAiFormSetting,listDbTableColumn} from '@/api/ai/base/aiFormSetting';
import {AiFormSettingForm,AiFormSettingVO,AiFormSettingDetailVO,AiFormSettingQuery} from '@/api/ai/base/aiFormSetting/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  ai_form_setting_flag,ai_form_setting_client_type,ai_form_setting_field_type,ai_form_setting_field_style,ai_form_setting_load_type
} = toRefs<any>(proxy?.useDict('ai_form_setting_flag','ai_form_setting_client_type','ai_form_setting_field_type','ai_form_setting_field_style','ai_form_setting_load_type'));

const aiFormSettingList = ref<AiFormSettingVO[]>([]);
const loading = ref(false);
const queryFormRef = ref<ElFormInstance>();
const aiFormSettingFormRef = ref<ElFormInstance>();
const selectTableOpen = ref(false)
const selectTableRef = ref();
const columnLoading = ref(false);
const buttonLoading = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const FORM_TYPE = {
  SINGLE_TABLE: '1',//单表
  MAIN_CHILD_TABLE: '2',//主子表
  MAIN_FORM_SUB_TABLE: '3'//主form子table
}
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AiFormSettingForm = {
  formSettingId: undefined,
  formType: FORM_TYPE.SINGLE_TABLE,
  dataName:undefined,
  tableName: undefined,
  formName: undefined,
  formPath: undefined,
  formLoadType:undefined,
  dialogVisibleVariable: undefined,
  subTableName: undefined,
  subTableFkName: undefined,
  clientType: undefined,
  remark: undefined,
  aiFormSettingDetailList:[]
}
const data = reactive<PageData<AiFormSettingForm, AiFormSettingQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    formSettingId: undefined,
    formType: undefined,
    tableName: undefined,
    formName: undefined,
    formPath: undefined,
    dialogVisibleVariable: undefined,
    subTableName: undefined,
    subTableFkName: undefined,
    clientType: undefined,
    params: {
    }
  },
  rules: {
    tableName: [
      { required: true, message: "表名称不能为空", trigger: "blur" }
    ],
    formName: [
      { required: true, message: "表单名称不能为空", trigger: "blur" }
    ],
    formPath: [
      { required: true, message: "表单路径不能为空", trigger: "blur" }
    ],
    clientType: [
      { required: true, message: "客户端类型不能为空", trigger: "change" }
    ],
    loadType: [
      { required: true, message: "加载类型不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询AI表单设置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAiFormSetting(queryParams.value);
  aiFormSettingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  aiFormSettingFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AiFormSettingVO[]) => {
  ids.value = selection.map(item => item.formSettingId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


// 新增按钮操作
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加AI表单设置";
};

const openTableSelectDialog = async () => {
  selectTableOpen.value = true;
};

/** 提交物料信息按钮 */
const submitSelectTable = () => {
  let selectedRow = selectTableRef.value.dbTableRef.store.states.currentRow.value;
  form.value = selectedRow;
  form.value.formName = selectedRow.tableComment;
  getFieldList();
  selectTableOpen.value = false;
};

const getFieldList = async () => {
  columnLoading.value = true;
  let query = {
    tableName: form.value.tableName,
    dataName: form.value.dataName,
  }
  let res = await listDbTableColumn(query);
  form.value.aiFormSettingDetailList = res.data;
  columnLoading.value = false;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AiFormSettingVO) => {
  reset();
  const _formSettingId = row?.formSettingId || ids.value[0]
  const res = await getAiFormSetting(_formSettingId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改AI表单设置";
}


// 保存按钮操作
const handleSave = () => {
  form.value.formType = FORM_TYPE.SINGLE_TABLE;
  aiFormSettingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.formSettingId) {
        await updateAiFormSetting(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAiFormSetting(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });

};

/** 删除按钮操作 */
const handleDelete = async (row?: AiFormSettingVO) => {
  const _formSettingIds = row?.formSettingId || ids.value;
  await proxy?.$modal.confirm('是否确认删除AI表单设置编号为"' + _formSettingIds + '"的数据项？').finally(() => loading.value = false);
  await delAiFormSetting(_formSettingIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}










// ================= UTILS =================
/**
 * 将下划线命名转换为驼峰命名
 * @param {string} str
 */
const toCamelCase = (str) => {
  return str.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
};













// ================= 选择菜单弹窗逻辑 =================
const menuSelectDialogVisible = ref(false);
const menuSearch = ref('');
const allMenus = ref([]);

const filteredMenus = computed(() => {
  if (!menuSearch.value) {
    return allMenus.value;
  }
  return allMenus.value.filter(menu =>
    menu.menuName.toLowerCase().includes(menuSearch.value.toLowerCase())
  );
});

const openMenuSelectDialog = async () => {
  // const res = await api.getAllMenus();

  menuSelectDialogVisible.value = true;
};

const handleMenuSelect = (menu) => {
  form.value.path = menu.path;
  menuSelectDialogVisible.value = false;
  menuSearch.value = '';
};
// ================= 选择菜单弹窗逻辑 END =================


// ================= 生命周期 =================
onMounted(() => {
  getList();
});


</script>

<style scoped>
.mt-4 {
  margin-top: 1.25rem;
}

.mb-4 {
  margin-bottom: 1.25rem;
}
</style>
