<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-zh-column align="center" :label="t('admin.common.dataNumber')" prop="id"/>-->
      <el-table-column
        align="center"
        :label="t('admin.form.name', { type: t('admin.common.lab') })"
        prop="name"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        align="center"
        :label="t('admin.table.researchIndustry')"
        prop="industryStr"
      />
      <el-table-column
        align="center"
        :label="t('webContact.phone')"
        prop="phone"
      />
      <el-table-column
        align="center"
        :label="t('admin.table.labWebsite')"
        prop="url"
      />
      <el-table-column
        align="center"
        :label="t('admin.table.addDate')"
        prop="createTime"
      >
        <template #default="{ row }">
          <span>{{ dayjs(row.createTime).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 size="small" type="text" @click="handleCancelBind(row)"
            >{{ t("admin.table.unbind") }}
            <template #icon>
              <svg-icon icon-class="broken_link" />
            </template>
          </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.pleaseSelect', {
                type: t('admin.form.purchaseTime'),
              })
            "
            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 { computed, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import modal from "@/plugins/modal";
import {
  deleteEquipment,
  insertEquipment,
} from "@/api/admin/laboratory/equipment";
import {
  delBindLaboratory,
  laboratoryEdit,
  laboratoryList,
} from "@/api/admin/research/laboratory";
import SvgIcon from "@/components/SvgIcon/index.vue";

import { useI18n } from "vue-i18n";
import dayjs from "dayjs";

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.form.placeholder", {
            type: t("admin.form.name", {
              type: t("admin.common.equipment"),
            }),
          })
        ),
        trigger: "blur",
      },
    ],
    model: [
      {
        required: true,
        /*"型号不能为空"*/
        message: computed(() =>
          t("admin.form.placeholder", {
            type: t("admin.form.model"),
          })
        ),
        trigger: "blur",
      },
    ],
    param: [
      {
        required: true,
        /*"成果参数不能为空*/
        message: computed(() =>
          t("admin.form.placeholder", {
            type: t("admin.form.achievementParameter"),
          })
        ),
        trigger: "blur",
      },
    ],
    buyDate: [
      {
        required: true,
        /* "请选择购买时间"*/
        message: computed(() =>
          t("admin.form.pleaseSelect", {
            type: t("admin.form.purchaseTime"),
          })
        ),
        trigger: ["blur", "change"],
      },
    ],
  },
});

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

/** 查询数据列表 */
function getList() {
  loading.value = true;
  laboratoryList(queryParams.value).then((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", {
        type: t("admin.common.item"),
        number: row.deviceId,
        action: t("admin.common.delete"),
      })
    )
    .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) {
  router.push({
    path: "/admin/research/laboratory/edit",
    query: {
      id: row.id,
    },
  });
}

/** 提交按钮 */
function submitForm() {
  equipmentRef.value?.validate((valid) => {
    if (valid) {
      if (form.value.id) {
        laboratoryEdit(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();
        });
      }
    }
  });
}

const handleCancelBind = (row) => {
  modal
    .confirm(`${t("home.unbindLab")} - ${row.name}`)
    .then(() => {
      return delBindLaboratory(row.id);
    })
    .then(() => {
      getList();
      ElMessage.success(t("tips.unbindLabSuccess"));
    });
};

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

getList();
</script>
