<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.equipment') })"
        prop="title"
      >
        <el-input
          v-model="queryParams.title"
          clearable
          :placeholder="
            t('admin.form.placeholder', { type: t('admin.common.equipment') })
          "
          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">
      <el-col :span="1.5">
        <el-button
          icon="Plus"
          plain
          size="small"
          type="primary"
          @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
        align="center"
        :label="t('admin.common.dataNumber')"
        prop="deviceId"
      />
      <el-table-column
        align="center"
        :label="t('admin.form.name', { type: t('admin.common.equipment') })"
        prop="name"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        align="center"
        :label="t('admin.form.model')"
        prop="model"
      />
      <el-table-column
        align="center"
        :label="t('admin.form.buyDate')"
        prop="buyDate"
      >
        <template #default="{ row }">
          <span>{{ dayjs(row.buyDate).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="handleUpdate(row)"
            >{{ t("admin.common.edit") }}
          </el-button>
          <el-button
            icon="Delete"
            size="small"
            type="text"
            @click="handleDelete(row)"
          >
            {{ 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="600px">
      <el-form
        ref="equipmentRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          :label="t('admin.form.name', { type: t('admin.common.equipment') })"
          prop="name"
        >
          <el-input
            v-model="form.name"
            :placeholder="
              t('admin.form.placeholder', { type: t('admin.common.equipment') })
            "
          />
        </el-form-item>
        <el-form-item :label="t('admin.form.model')" prop="model">
          <el-input
            v-model="form.model"
            :placeholder="
              t('admin.form.placeholder', { type: t('admin.form.model') })
            "
          />
        </el-form-item>
        <el-form-item :label="t('admin.form.buyDate')" prop="buyDate">
          <el-date-picker
            v-model="form.buyDate"
            :placeholder="
              t('admin.form.placeholder', {
                type: t('admin.form.buyDate'),
              })
            "
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          :label="t('admin.form.achievementParameter')"
          prop="param"
        >
          <el-input
            v-model="form.param"
            :placeholder="
              t('admin.form.placeholder', {
                type: t('admin.form.achievementParameter'),
              })
            "
          />
        </el-form-item>
        <el-form-item
          :label="t('admin.form.deviceDescription')"
          prop="description"
        >
          <el-input
            v-model="form.description"
            :placeholder="
              t('admin.form.placeholder', {
                type: t('admin.form.deviceDescription'),
              })
            "
            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 {expertPaper, paperAdd, paperDelete, paperEdit,} from "@/api/admin/expert/technology";
import { computed, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import modal from "@/plugins/modal";
import {
  deleteEquipment,
  equipmentList,
  getEquipment,
  insertEquipment,
  updateEquipment,
} from "@/api/admin/laboratory/equipment";
import dayjs from "dayjs";

import { useI18n } from "vue-i18n";

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

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const equipmentRef = ref();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
  rules: {
    name: [
      {
        required: true,
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.name", { type: t("admin.common.equipment") }),
          })
        ),
        trigger: "blur",
      },
    ],
    model: [
      {
        required: true,
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.name", { type: t("admin.form.model") }),
          })
        ),
        trigger: "blur",
      },
    ],
    param: [
      {
        required: true,
        message: computed(() =>
          t("admin.validation.required", {
            type: t("admin.form.achievementParameter"),
          })
        ),
        trigger: "blur",
      },
    ],
    buyDate: [
      {
        required: true,
        // message: "请选择购买时间",
        message: computed(() =>
          t("admin.form.placeholder", {
            type: t("admin.form.buyDate"),
          })
        ),
        trigger: ["blur", "change"],
      },
    ],
  },
});

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

/** 查询数据列表 */
function getList() {
  loading.value = true;
  equipmentList(queryParams.value).then((response) => {
    console.log(response);
    dataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

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

/** 删除按钮操作 */
function handleDelete(row) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        number: row.deviceId,
        action: t("admin.common.delete"),
        type: t("admin.common.equipment"),
      })
    )
    .then(function () {
      return deleteEquipment([row.deviceId]);
    })
    .then(() => {
      getList();
      ElMessage.success(t("admin.common.deleteSuccess"));
    })
    .catch(() => {});
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    name: null,
    model: null,
    buyDate: null,
    param: null,
    description: null,
  };
  equipmentRef.value?.resetFields();
}

/** 添加数据 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = t("admin.form.addData");
}

/** 修改数据 */
async function handleUpdate(row) {
  const resp = await getEquipment(row.deviceId);
  form.value = resp.data;
  open.value = true;
  title.value = t("admin.form.editData");
}

/** 提交按钮 */
function submitForm() {
  equipmentRef.value?.validate((valid) => {
    if (valid) {
      if (form.value.deviceId) {
        updateEquipment(form.value).then((response) => {
          ElMessage.success(t("admin.common.editSuccess"));
          open.value = false;
          getList();
        });
      } else {
        insertEquipment(form.value).then((response) => {
          ElMessage.success(t("admin.common.addSuccess"));
          open.value = false;
          getList();
        });
      }
    }
  });
}

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

getList();
</script>
