<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          #foreach($fieldConfig in $fieldConfigs)
              #if($fieldConfig.isShowInQuery == 1)
                <el-form-item label="$fieldConfig.fieldComment" prop="$fieldConfig.fieldName">
                    #if($fieldConfig.formType == "INPUT")
                      <el-input
                          v-model="queryParams.$fieldConfig.fieldName"
                          placeholder="$fieldConfig.fieldComment"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                    #elseif($fieldConfig.formType == "SELECT")
                        #if($fieldConfig.dictType != "")
                          <dictionary v-model="queryParams.$fieldConfig.fieldName" code="$fieldConfig.dictType" />
                        #else
                          <el-select v-model="queryParams.$fieldConfig.fieldName" placeholder="请选择$fieldConfig.fieldComment">
                            <el-option :key="1" :value="1" label="选项一"/>
                            <el-option :key="2" :value="2" label="选项二"/>
                          </el-select>
                        #end
                    #elseif($fieldConfig.formType == "RADIO")
                      <el-radio-group v-model="queryParams.$fieldConfig.fieldName">
                        <el-radio :key="1" :label="1">选项一</el-radio>
                        <el-radio :key="2" :label="2">选项二</el-radio>
                      </el-radio-group>
                    #elseif($fieldConfig.formType == "CHECK_BOX")
                      <el-checkbox-group v-model="queryParams.$fieldConfig.fieldName">
                        <el-checkbox :key="1" :label="1">选项一</el-checkbox>
                        <el-checkbox :key="2" :label="2">选项二</el-checkbox>
                      </el-checkbox-group>
                    #elseif($fieldConfig.formType == "INPUT_NUMBER")
                      <el-input-number
                          v-model="queryParams.$fieldConfig.fieldName"
                          placeholder="$fieldConfig.fieldComment"
                      />
                    #elseif($fieldConfig.formType == "SWITCH")
                      <el-switch
                          v-model="queryParams.$fieldConfig.fieldName"
                          :active-value="1"
                          :inactive-value="0"
                      />
                    #elseif($fieldConfig.formType == "TEXT_AREA")
                      <el-input type="textarea"
                                v-model="queryParams.$fieldConfig.fieldName"
                                placeholder="$fieldConfig.fieldComment"
                      />
                    #elseif($fieldConfig.formType == "DATE_TIME")
                      <el-date-picker
                          v-model="queryParams.$fieldConfig.fieldName"
                          #if($fieldConfig.queryType == "BETWEEN")
                          type="daterange"
                          range-separator="~"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          #else
                          type="datetime"
                          placeholder="$fieldConfig.fieldComment"
                          #end
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                    #elseif($fieldConfig.formType == "DATE")
                      <el-date-picker
                          class="!w-[240px]"
                          v-model="queryParams.$fieldConfig.fieldName"
                          #if($fieldConfig.queryType == "BETWEEN")
                          type="daterange"
                          range-separator="~"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          #else
                          type="date"
                          placeholder="$fieldConfig.fieldComment"
                          #end
                          value-format="YYYY-MM-DD"
                      />
                    #end
                </el-form-item>
              #end
          #end
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"><i-ep-search />搜索</el-button>
          <el-button @click="handleResetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
            v-hasPerm="['${moduleName}:${lowerFirstEntityName}:add']"
            type="success"
            @click="handleOpenDialog()"
        >
          <i-ep-plus />
          新增
        </el-button>
        <el-button
            v-hasPerm="['${moduleName}:${lowerFirstEntityName}:delete']"
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        ><i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
          #foreach($fieldConfig in $fieldConfigs)
              #if($fieldConfig.isShowInList == 1)
                <el-table-column
                    key="$fieldConfig.fieldName"
                    label="$fieldConfig.fieldComment"
                    prop="$fieldConfig.fieldName"
                    min-width="150"
                    align="center"
                />
              #end
          #end
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
                v-hasPerm="['${moduleName}:${lowerFirstEntityName}:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
                v-hasPerm="['${moduleName}:${lowerFirstEntityName}:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- $!{businessName}表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
          #foreach($fieldConfig in $fieldConfigs)
              #if($fieldConfig.isShowInForm == 1)
                <el-form-item label="$fieldConfig.fieldComment" prop="$fieldConfig.fieldName">
                    #if($fieldConfig.formType == "INPUT")
                      <el-input
                          v-model="formData.$fieldConfig.fieldName"
                          placeholder="$fieldConfig.fieldComment"
                      />
                    #elseif($fieldConfig.formType == "SELECT")
                        #if($fieldConfig.dictType != "")
                          <dictionary v-model="formData.$fieldConfig.fieldName" code="$fieldConfig.dictType" />
                        #else
                          <el-select v-model="formData.$fieldConfig.fieldName" placeholder="请选择$fieldConfig.fieldComment">
                            <el-option :value="0" label="选项一"/>
                            <el-option :value="1" label="选项二"/>
                          </el-select>
                        #end
                    #elseif($fieldConfig.formType == "RADIO")
                      <el-radio-group v-model="formData.$fieldConfig.fieldName">
                        <el-radio :value="0">选项一</el-radio>
                        <el-radio :value="1">选项二</el-radio>
                      </el-radio-group>
                    #elseif($fieldConfig.formType == "CHECK_BOX")
                      <el-checkbox-group v-model="formData.$fieldConfig.fieldName">
                        <el-checkbox :value="0">选项一</el-checkbox>
                        <el-checkbox :value="1">选项二</el-checkbox>
                      </el-checkbox-group>
                    #elseif($fieldConfig.formType == "INPUT_NUMBER")
                      <el-input-number
                          v-model="formData.$fieldConfig.fieldName"
                          placeholder="$fieldConfig.fieldComment"
                      />
                    #elseif($fieldConfig.formType == "SWITCH")
                      <el-switch
                          v-model="formData.$fieldConfig.fieldName"
                          :active-value="1"
                          :inactive-value="0"
                      />
                    #elseif($fieldConfig.formType == "TEXT_AREA")
                      <el-input type="textarea"
                                v-model="formData.$fieldConfig.fieldName"
                                placeholder="$fieldConfig.fieldComment"
                      />
                    #elseif($fieldConfig.formType == "DATE_TIME")
                      <el-date-picker
                          v-model="formData.$fieldConfig.fieldName"
                          type="datetime"
                          placeholder="$fieldConfig.fieldComment"
                          value-format="YYYY-MM-DD HH:mm:ss"
                      />
                    #elseif($fieldConfig.formType == "DATE")
                      <el-date-picker
                          class="!w-[240px]"
                          v-model="formData.$fieldConfig.fieldName"
                          type="date"
                          placeholder="$fieldConfig.fieldComment"
                          value-format="YYYY-MM-DD"
                      />
                    #end
                </el-form-item>
              #end
          #end
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  defineOptions({
    name: "${entityName}",
    inheritAttrs: false,
  });

  import ${entityName}API, { ${entityName}PageVO, ${entityName}Form, ${entityName}PageQuery } from "@/api/${kebabCaseEntityName}";

  const queryFormRef = ref(ElForm);
  const dataFormRef = ref(ElForm);

  const loading = ref(false);
  const removeIds = ref<number[]>([]);
  const total = ref(0);

  const queryParams = reactive<${entityName}PageQuery>({
    pageNum: 1,
    pageSize: 10,
  });

  // $!{businessName}表格数据
  const pageData = ref<${entityName}PageVO[]>([]);

  // 弹窗
  const dialog = reactive({
    title: "",
    visible: false,
  });

  // $!{businessName}表单数据
  const formData = reactive<${entityName}Form>({});

  // $!{businessName}表单校验规则
  const rules = reactive({
      #if($fieldConfigs)
          #foreach($fieldConfig in ${fieldConfigs})
              #if($fieldConfig.isShowInForm && $fieldConfig.isRequired)
                      ${fieldConfig.fieldName}: [{ required: true, message: "请输入${fieldConfig.fieldComment}", trigger: "blur" }],
              #end
          #end
      #end
  });

  /** 查询$!{businessName} */
  function handleQuery() {
    loading.value = true;
          ${entityName}API.getPage(queryParams)
        .then((data) => {
          pageData.value = data.list;
          total.value = data.total;
        })
        .finally(() => {
          loading.value = false;
        });
  }

  /** 重置$!{businessName}查询 */
  function handleResetQuery() {
    queryFormRef.value!.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
  }

  /** 行复选框选中记录选中ID集合 */
  function handleSelectionChange(selection: any) {
    removeIds.value = selection.map((item: any) => item.id);
  }

  /** 打开$!{businessName}弹窗 */
  function handleOpenDialog(id?: number) {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改$!{businessName}";
            ${entityName}API.getFormData(id).then((data) => {
        Object.assign(formData, data);
      });
    } else {
      dialog.title = "新增$!{businessName}";
    }
  }

  /** 提交$!{businessName}表单 */
  function handleSubmit() {
    dataFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        const id = formData.id;
        if (id) {
                ${entityName}API.update(id, formData)
              .then(() => {
                ElMessage.success("修改成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        } else {
                ${entityName}API.add(formData)
              .then(() => {
                ElMessage.success("新增成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        }
      }
    });
  }

  /** 关闭$!{businessName}弹窗 */
  function handleCloseDialog() {
    dialog.visible = false;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
    formData.id = undefined;
  }

  /** 删除$!{businessName} */
  function handleDelete(id?: number) {
    const ids = [id || removeIds.value].join(",");
    if (!ids) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
        () => {
          loading.value = true;
                ${entityName}API.deleteByIds(ids)
              .then(() => {
                ElMessage.success("删除成功");
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        },
        () => {
          ElMessage.info("已取消删除");
        }
    );
  }

  onMounted(() => {
    handleQuery();
  });
</script>
