<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      @submit.prevent
    >
      <el-form-item
        :label="t('admin.form.name', { type: t('admin.common.achievement') })"
        prop="title"
      >
        <el-input
          v-model="queryParams.title"
          clearable
          :placeholder="
            t('admin.form.placeholder', { type: t('admin.common.patent') })
          "
          size="small"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          icon="Search"
          size="small"
          type="primary"
          @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">
      <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
        :show-overflow-tooltip="true"
        :label="t('admin.form.paperTitle')"
        prop="title"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        :label="t('admin.form.publication')"
        prop="ext"
      />
      <el-table-column :label="t('admin.form.belongExpert')" prop="author" />
      <el-table-column
        align="center"
        :label="t('admin.form.keywords')"
        prop="keyword"
      />
      <!--      <el-zh-column align="center" label="浏览量" prop="readCount"/>-->
      <el-table-column
        align="center"
        :label="t('admin.form.publishDate')"
        prop="publishTime"
      >
        <template #default="{ row }">
          <span>{{ dayjs(row.publishTime).format("YYYY-MM-DD") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        :label="t('admin.common.operation')"
      >
        <template #default="{ row }">
          <!--          <el-button-->
          <!--              icon="edit"-->
          <!--              size="small"-->
          <!--              type="text"-->
          <!--              @click="handleEdit(row)"-->
          <!--          >编辑-->
          <!--          </el-button-->
          <!--          >-->
          <el-button
            icon="Delete"
            size="small"
            type="text"
            @click="handleDelete(row.id)"
          >
            {{ t("admin.common.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改数据配置对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="800px">
      <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.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="publish_at">
          <el-date-picker
            v-model="form.publishAt"
            :placeholder="
              t('admin.form.pleaseSelect', {
                type: t('admin.form.publishDate'),
              })
            "
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <InputBoxAdd
          ref="keywordsFormRef"
          v-model="form"
          :labelWidth="100"
          fieldKey="keywords"
          :placeholder="t('admin.form.inputKeywords')"
          :title="t('admin.form.keywords')"
        />
        <el-form-item :label="t('admin.form.summary')">
          <el-input
            v-model="form.remark"
            :placeholder="t('admin.validation.pleaseEnterContent')"
            type="textarea"
          ></el-input>
        </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 { ElMessage } from "element-plus";
import modal from "@/plugins/modal";
import InputBoxAdd from "@/views/components/InputBoxAdd";
import { useRouter } from "vue-router";
import { computed, getCurrentInstance, reactive, ref, toRefs } from "vue";
import { cloneDeep } from "lodash";
import { deletePaper, paperList } from "@/api/admin/laboratory/paper";
import { useI18n } from "vue-i18n";
import dayjs from "dayjs";

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

const { proxy } = getCurrentInstance();
const paperRef = ref();
const keywordsFormRef = ref();

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: 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",
      },
    ],
    publish_at: [
      {
        required: true,
        /*"请选择出版日期"*/
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.table.publishDate"),
          })
        ),
        trigger: ["blur", "change"],
      },
    ],
  },
});

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

const queryRef = ref();

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

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

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

/** 删除按钮操作 */
function handleDelete(id) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        type: t("admin.common.paper"),
        number: id,
        action: t("admin.common.delete"),
      })
    )
    .then(function () {
      return deletePaper(id);
    })
    .then(() => {
      getList();
      ElMessage.success(t("admin.common.deleteSuccess"));
    })
    .catch((err) => {
      console.log(err);
    });
}

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

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

const handleEdit = (row) => {
  form.value = cloneDeep(row);
  open.value = true;
  title.value = t("admin.form.editData");
};

/** 提交按钮 */
function submitForm() {
  paperRef.value?.validate((valid) => {
    const keywordsFormValid = keywordsFormRef.value.validateForm();
    if (valid && keywordsFormValid) {
      if (form.value.id) {
        // TODO
        paperEdit(form.value).then((response) => {
          proxy.$modal.msgSuccess(t("admin.common.editSuccess"));
          open.value = false;
          getList();
        });
      }
      /*
      else {
        paperAdd(form.value).then((response) => {
          proxy.$modal.msgSuccess(t('admin.common.addSuccess'));
          open.value = false;
          getList();
        });
      }
      */
    }
  });
}

getList();
</script>
