<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      @submit.prevent
    >
      <el-form-item :label="t('admin.form.paperTitle')" prop="title">
        <el-input
          v-model="queryParams.title"
          :placeholder="
            t('admin.form.placeholder', { type: t('admin.form.paperTitle') })
          "
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          size="small"
          @click="handleQuery"
        >
          {{ t("admin.common.search") }}
        </el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">
          {{ t("admin.common.reset") }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
        >
          {{ t("admin.common.add") }}
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column :label="t('admin.common.dataNumber')" prop="id" />
      <el-table-column
        :label="t('admin.form.paperTitle')"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('admin.form.publication')"
        prop="ext"
        :show-overflow-tooltip="true"
      />
      <el-table-column :label="t('admin.form.author')" prop="author" />
      <el-table-column
        :label="t('admin.form.keywords')"
        align="center"
        prop="keyword"
      />
      <el-table-column :label="t('admin.form.publishDate')" align="center">
        <template #default="{ row }">
          <span>{{ dayjs(row.publishTime).format("YYYY-MM-DD") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('admin.common.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            icon="Edit"
            @click="handleUpdate(row)"
            >{{ t("admin.common.edit") }}
          </el-button>
          <el-button
            size="small"
            type="text"
            icon="Delete"
            @click="handleDelete(row.id)"
          >
            {{ t("admin.common.delete") }}
          </el-button>
        </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-dialog
      :title="title"
      v-model="showEditDialog"
      width="800px"
      append-to-body
    >
      <el-form ref="paperRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="t('admin.form.paperTitle')" prop="title">
          <el-input
            v-model="form.title"
            :placeholder="
              t('admin.form.placeholder', { type: t('admin.form.paperTitle') })
            "
          />
        </el-form-item>
        <el-form-item
          :label="
            t('admin.form.name', {
              type: t('admin.form.publication'),
            })
          "
          prop="ext"
        >
          <el-input
            v-model="form.ext"
            :placeholder="
              t('admin.form.placeholder', { type: t('admin.form.publication') })
            "
          />
        </el-form-item>
        <el-form-item :label="t('admin.form.author')" prop="author">
          <el-input
            v-model="form.author"
            :placeholder="t('admin.form.paperAuthorPlaceholder')"
          />
        </el-form-item>
        <el-form-item :label="t('admin.form.publishDate')" prop="publishTime">
          <el-date-picker
            v-model="form.publishTime"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="
              t('admin.form.pleaseSelect', {
                type: t('admin.form.publishDate'),
              })
            "
          ></el-date-picker>
        </el-form-item>
        <InputBoxAdd
          :labelWidth="100"
          v-model="form"
          :title="t('admin.form.keywords')"
          :placeholder="t('admin.form.inputKeywords')"
          fieldKey="keywords"
          ref="keywordsFormRef"
        />
        <el-form-item :label="t('admin.form.summary')" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :placeholder="t('admin.validation.pleaseEnterContent')"
          ></el-input>
        </el-form-item>
        <!-- //TODO:上传论文添加字段 -->
        <el-form-item :label="t('admin.table.uploadPaper')" prop="fileUrl">
          <FileUpload
            v-model="form.fileUrl"
            :limit="1"
            :fileType="['docx', 'doc', 'pdf']"
          ></FileUpload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            >{{ t("admin.common.confirm") }}
          </el-button>
          <el-button @click="cancel">{{ t("admin.common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import InputBoxAdd from "@/views/components/InputBoxAdd";
import {
  deleteCasPaper,
  insertCasPaper,
  paperList,
  updateCasPaper,
} from "@/api/admin/expert/technology";
import dayjs from "dayjs";
import { cloneDeep } from "lodash";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import modal from "@/plugins/modal";
import { useI18n } from "vue-i18n";
import { computed } from "vue";

const { t } = useI18n();
const router = useRouter();

const dataList = ref([]);
const showEditDialog = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const paperRef = ref();
const queryRef = ref();
const keywordsFormRef = ref();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // title: undefined,
  },
  rules: {
    title: [
      {
        required: true,
        /*"论文题目不能为空"*/
        message: computed(() =>
          t("admin.validation.required", { type: t("admin.form.paperTitle") })
        ),
        trigger: "blur",
      },
    ],
    ext: [
      {
        required: true,
        /*"刊物不能为空"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.publication"),
          })
        ),
        trigger: "blur",
      },
    ],
    author: [
      {
        required: true,
        /*"作者不能为空"*/
        message: computed(() =>
          t("admin.validation.required", { type: t("admin.form.author") })
        ),
        trigger: "blur",
      },
    ],
    publishTime: [
      {
        required: true,
        /*"请选择出版日期"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.publishDate"),
          })
        ),
        trigger: ["blur", "change"],
      },
    ],
    remark: [
      {
        required: true,
        // message: "请输入摘要",
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.summary"),
          })
        ),
        trigger: "blur",
      },
    ],
  },
});

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

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  const resp = await paperList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};

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

/** 重置按钮操作 */
function resetQuery() {
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(id) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        type: t("admin.common.item"),
        number: id,
        action: t("admin.common.delete"),
      })
    )
    .then(async () => {
      await deleteCasPaper(id);
      getList();
      ElMessage.success(t("admin.common.deleteSuccess"));
    });
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    // id: undefined,
    // title: undefined,
    // ext: undefined,
    // author: undefined,
    // publish_at: undefined,
    // keywords: [],
    // remark: undefined,
  };
  if (paperRef.value) {
    paperRef.value.resetFields();
  }
}

/** 添加数据 */
function handleAdd() {
  reset();
  showEditDialog.value = true;
  title.value = t("admin.form.add", {
    type: t("admin.common.paper"),
  });
}

/** 修改数据 */
function handleUpdate(row) {
  // form.value = JSON.parse(JSON.stringify(row));
  form.value = cloneDeep(row);
  form.value.keywords = [...form.value.keyword?.split(",")];
  showEditDialog.value = true;
  title.value = t("admin.form.edit", {
    type: t("admin.common.paper"),
  });
}

/** 提交按钮 */
function submitForm() {
  paperRef.value.validate(async (valid) => {
    const keywordsValid = keywordsFormRef.value.validateForm();
    if (valid && keywordsValid) {
      form.value.keyword = form.value.keywords.join(",");
      if (form.value.id) {
        await updateCasPaper(form.value);
        ElMessage.success(t("admin.common.editSuccess"));
        showEditDialog.value = false;
        getList();
      } else {
        await insertCasPaper(form.value);
        ElMessage.success(t("admin.common.addSuccess"));
        showEditDialog.value = false;
        getList();
      }
    } else {
      console.log("validation failed");
    }
  });
}

/** 取消按钮 */
function cancel() {
  showEditDialog.value = false;
  reset();
}

getList();
</script>
