<template>
  <div class="app-container">
    <div class="container-custom">
      <div ref="searchBarRef" class="search-box">
        <div class="search-bar">
          <div class="search-bar-left">
            <el-form ref="searchForm" :inline="true" :model="formInline" class="demo-form-inline" :label-width="'auto'">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="formInline.name" placeholder="请输入姓名" clearable />
              </el-form-item>
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="formInline.phone" placeholder="请输入联系方式" clearable />
              </el-form-item>
              <el-form-item label="">
                <el-button type="primary" icon="Search" @click="onSubmit">查询</el-button>
                <el-button icon="Refresh" @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="table-toolbar">
        <el-button type="primary" icon="plus">新增</el-button>
      </div>
      <div class="table-cont">
        <tableComponent
          :table-data="tableData"
          :columns="columns"
          :show-selection="false"
          :loading="tableLoading"
          :total="tableTotal"
          :current-page="formInline.current"
          :page-size="formInline.size"
          :show-sort="true"
          @page-change="handlePaginationChange"
        >
          <!-- 自定义-操作 -->
          <template #action="slotProps">
            <el-button type="primary" @click="seeDetails(slotProps.row)">详情</el-button>
            <el-button type="primary" @click="handleEdit(slotProps.row)">编辑</el-button>
            <el-button @click="handleDelete(slotProps.row)">删除</el-button>
          </template>
        </tableComponent>
      </div>
    </div>

    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" :close-on-click-modal="false">
      <el-form ref="dialogRef" :model="dialogForm" :label-width="'80'" :rules="dialogFormRules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name" autocomplete="off" placeholder="请输入姓名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSaveCategory">保存</el-button>
          <el-button @click="cancelDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue';
import tableComponent from '@/components/tableComponent.vue';
import { ElMessage } from 'element-plus';
import inputSuppliesApi from '@/apis/inputSuppliesApi';
const { getPesticideList, addPesticide, pesticideReportSave, delPesticide } = inputSuppliesApi;

// 查询条件
const formInline = reactive({
  name: '',
  phone: '',
  current: 1,
  size: 10,
});
const searchForm = ref(null);
const onSubmit = () => {
  formInline.current = 1;
  loadData();
};
const resetForm = () => {
  searchForm.value.resetFields();
};

// 表格数据
const tableData = ref([]);
const selectedIds = ref([]);
const btnStatus = computed(() => {
  return selectedIds.value.length <= 0;
});
const tableLoading = ref(false);
const tableTotal = ref(0);
let nowClickRow = ref({});
const columns = ref([
  // { prop: "id", label: "ID" },
  { prop: 'name', label: '类别名称' },
  { prop: 'phone', label: '联系方式' },
  { prop: 'landName', label: '用药地块' },
  { prop: 'detectionTime', label: '检测时间' },
  { prop: 'detectionResult', label: '检测结果' },
  { prop: 'detectionUnit', label: '检测单位' },
  // { prop: 'status', label: '检测报告(是否上传)' },
  { prop: 'action', label: '操作', slotName: 'action', width: 230, fixed: 'right' },
]);
const handlePaginationChange = ({ page, pageSize }) => {
  formInline.current = page;
  formInline.size = pageSize;
  // 这里可以调用API获取新数据
  loadData();
};
const loadData = async () => {
  tableLoading.value = true;
  try {
    let response = await getPesticideList(formInline);
    tableLoading.value = false;
    if (response.code == 200) {
      tableData.value = response.data.records;
      tableTotal.value = response.data.total;
    }
  } catch (error) {
    tableLoading.value = false;
    console.error(error);
  }
};

// 查看详情
const seeDetails = async (row) => {
  nowClickRow.value = row;
  console.log('要查看详情的行: ', row);
};
// 编辑操作
const handleEdit = async (row) => {
  nowClickRow.value = row;
  dialogTitle.value = '编辑';
  dialogForm.id = row.id;
  dialogForm.name = row.name;
  dialogFormVisible.value = true;
};
// 删除操作
const handleDelete = (row) => {
  deleteGoods(row.id);
};
const deleteGoods = async (ids) => {
  try {
    tableLoading.value = true;
    let res = await delPesticide({ id: ids });
    tableLoading.value = false;
    if (res.code == 200) {
      onSubmit();
      ElMessage.success('删除成功');
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    tableLoading.value = false;
  }
};

const dialogFormVisible = ref(false);
const dialogRef = ref(null);
const dialogTitle = ref('新增');
const dialogForm = reactive({
  id: '',
  name: '',
});
const dialogFormRules = ref({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
});
const onSaveCategory = () => {
  dialogRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        let param = { ...dialogForm };
        param.level = dialogForm.selectedNode.level ?? '';
        param.type = dialogForm.selectedNode.type ?? '';
        let response;
        if (dialogTitle.value == '新增') {
          response = await addPesticide(param);
        } else {
          response = await pesticideReportSave(param);
        }
        if (response.code == 200) {
          cancelDialog();
          onSubmit();
          if (dialogTitle.value == '新增') {
            ElMessage.success('新增成功!');
          } else {
            ElMessage.success('编辑成功!');
          }
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        console.error(error);
      }
    }
  });
};
const cancelDialog = () => {
  Object.assign(dialogForm, {
    // 保持响应性，手动清空字段
    id: '',
    name: '',
  });
  dialogFormVisible.value = false;
};
onMounted(() => {
  onSubmit();
});
</script>
<style lang="scss" scoped></style>
