<template>
  <div class="app-container">
    <div class="container-custom">
      <h2 class="custom-h2">农药使用监管</h2>
      <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" @click="addItem()">新增</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="700" :close-on-click-modal="false">
      <el-form
        ref="dialogRef"
        :model="dialogForm"
        :inline="true"
        :label-width="'80'"
        :rules="dialogFormRules"
        :disabled="formDisabled"
        class="dialog-form-container"
      >
        <div class="dialog-form-title">农药用药详情</div>
        <el-form-item label="姓名" prop="name" class="dialog-form-item">
          <el-input v-model="dialogForm.name" clearable placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone" class="dialog-form-item">
          <el-input v-model="dialogForm.phone" clearable placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="用药地块" prop="landId" class="dialog-form-item">
          <el-select v-model="dialogForm.landId" placeholder="请选择" @change="handleLandsChange">
            <el-option v-for="item in landList" :key="item.id" :value="item.id" :label="item.landName" />
          </el-select>
        </el-form-item>

        <div class="dialog-form-title">土地残留检测</div>
        <div style="display: flex">
          <div style="width: 48%; display: inline-block">
            <el-form-item label="检测时间" prop="detectionTime" class="dialog-form-item">
              <el-date-picker
                v-model="dialogForm.detectionTime"
                :clearable="false"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择起始日期"
              />
            </el-form-item>
            <el-form-item label="检测结果" prop="detectionResult" class="dialog-form-item">
              <el-select v-model="dialogForm.detectionResult" placeholder="请选择">
                <el-option value="合格" label="合格" />
                <el-option value="不合格" label="不合格" />
              </el-select>
            </el-form-item>
            <el-form-item label="检测单位" prop="detectionUnit" class="dialog-form-item">
              <el-input v-model="dialogForm.detectionUnit" clearable placeholder="请输入检测单位" />
            </el-form-item>
          </div>
          <div style="width: 50%; display: inline-block">
            <el-form-item label="检测报告" prop="detectionReport" class="dialog-form-item" style="width: 100%">
              <FileUploader v-model="dialogForm.detectionReport" :limit="1" />
            </el-form-item>
          </div>
        </div>

        <div class="dialog-form-title">
          农药用药信息
          <el-button v-if="!formDisabled" type="primary" icon="plus" size="small" style="margin-left: 10px" @click="addMedicationInfo()"
            >添加用药信息</el-button
          >
        </div>
        <div v-for="(item, index) in dialogForm.pesticideSuperviseDetailVO" :key="index" class="dialog-form-many">
          <el-form-item
            label="农药名称"
            required
            :prop="`pesticideSuperviseDetailVO.${index}.pesticideId`"
            :rules="dialogFormRules.pesticideSuperviseDetailVO.defaultField.pesticideId"
            class="dialog-form-item"
          >
            <el-select v-model="item.pesticideId" placeholder="请选择" @change="handlePesticideChange(item, index)">
              <el-option v-for="el in pesticideList" :key="el.id" :value="el.id" :label="el.pesticideName" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="用药量"
            required
            :prop="`pesticideSuperviseDetailVO.${index}.useNumber`"
            :rules="dialogFormRules.pesticideSuperviseDetailVO.defaultField.useNumber"
            class="dialog-form-item"
          >
            <el-input-number v-model="item.useNumber" :min="1" :controls="false" placeholder="请输入用药量" style="width: 120px" />
            <el-select v-model="item.useUnit" placeholder="请选择" style="width: 80px">
              <el-option v-for="el in unitList" :key="el.unit" :value="el.unit" :label="el.unit" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="使用时间"
            required
            :prop="`pesticideSuperviseDetailVO.${index}.useTime`"
            :rules="dialogFormRules.pesticideSuperviseDetailVO.defaultField.useTime"
            class="dialog-form-item"
          >
            <el-date-picker v-model="item.useTime" :clearable="false" type="date" value-format="YYYY-MM-DD" placeholder="请选择使用时间" />
          </el-form-item>
          <el-form-item
            label="检测结果"
            required
            :prop="`pesticideSuperviseDetailVO.${index}.detailDetectionResult`"
            :rules="dialogFormRules.pesticideSuperviseDetailVO.defaultField.detailDetectionResult"
            class="dialog-form-item"
          >
            <el-select v-model="item.detailDetectionResult" placeholder="请选择" style="width: 200px">
              <el-option value="合格" label="合格" />
              <el-option value="不合格" label="不合格" />
            </el-select>
          </el-form-item>
          <div v-if="!formDisabled" class="dialog-form-many-delete">
            <el-button v-if="index !== 0" type="danger" plain size="small" @click="deleteMedicationInfo(index)">删除</el-button>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!formDisabled" type="primary" @click="onSaveCategory">保存</el-button>
          <el-button v-if="!formDisabled" @click="cancelDialog">取消</el-button>
          <el-button v-else @click="cancelDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick } from 'vue';
import tableComponent from '@/components/tableComponent.vue';
import { ElMessage } from 'element-plus';
import inputSuppliesApi from '@/apis/inputSuppliesApi';
import { id } from 'element-plus/es/locales.mjs';
const { getPesticideList, addPesticide, pesticideReportSave, delPesticide, getLandList, getPesticideSelectList } = inputSuppliesApi;
import { useApp } from '@/hooks';
const app = useApp();

// 查询条件
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);
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 landList = ref([]);
const getLandsList = async () => {
  try {
    let response = await getLandList();
    if (response.code == 200) {
      landList.value = response.data;
    }
  } catch (error) {
    console.error(error);
  }
};
const handleLandsChange = () => {
  const landItem = landList.value.find((item) => item.id == dialogForm.landId);
  dialogForm.landName = landItem.landName;
};
const pesticideList = ref([]);
const getPesticidesList = async () => {
  try {
    let response = await getPesticideSelectList();
    if (response.code == 200) {
      pesticideList.value = response.data;
    }
  } catch (error) {
    console.error(error);
  }
};
const unitList = ref([
  { id: '1', unit: 'kg' },
  { id: '2', unit: 'g' },
  { id: '3', unit: 'L' },
  { id: '4', unit: 'ml' },
]);
const handlePesticideChange = (item, index) => {
  dialogForm.pesticideSuperviseDetailVO[index].pesticideName = pesticideList.value[index].pesticideName;
  console.log(dialogForm.pesticideSuperviseDetailVO);
};
const deleteMedicationInfo = (index) => {
  dialogForm.pesticideSuperviseDetailVO.splice(index, 1);
};

const dialogFormVisible = ref(false);
const dialogRef = ref(null);
const dialogTitle = ref('新增');
const formDisabled = ref(false);
const dialogForm = reactive({
  id: '',
  name: '',
  phone: '',
  landId: '',
  landName: '',
  detectionTime: '',
  detectionResult: '',
  detectionUnit: '',
  detectionReport: '',
  pesticideSuperviseDetailVO: [{ pesticideId: '', pesticideName: '', useNumber: 1, useTime: '', useUnit: 'ml', detailDetectionResult: '' }],
});
const dialogFormRules = ref({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' },
  ],
  landId: [
    {
      required: true,
      message: '请选择用药地块',
      trigger: ['change', 'blur'],
    },
  ],
  detectionTime: [{ required: true, message: '请选择检测时间', trigger: ['change', 'blur'] }],
  detectionResult: [
    {
      required: true,
      message: '请选择检测结果',
      trigger: ['change', 'blur'],
    },
  ],
  detectionUnit: [{ required: true, message: '请输入检测单位', trigger: 'blur' }],
  pesticideSuperviseDetailVO: {
    type: 'array',
    defaultField: {
      pesticideId: [{ required: true, message: '请选择农药名称', trigger: 'change' }],
      useNumber: [
        { required: true, message: '请输入用药量', trigger: 'blur' },
        { type: 'number', min: 1, message: '用药量必须大于0', trigger: 'blur' },
      ],
      useUnit: [{ required: true, message: '请选择单位', trigger: 'change' }],
      useTime: [{ required: true, message: '请选择使用时间', trigger: 'change' }],
      detailDetectionResult: [{ required: true, message: '请选择检测结果', trigger: 'change' }],
    },
  },
});
const addMedicationInfo = () => {
  dialogForm.pesticideSuperviseDetailVO.push({
    pesticideSuperviseId: '',
    detailId: '',
    pesticideId: '',
    pesticideName: '',
    useNumber: 1,
    useTime: '',
    useUnit: 'ml',
  });
};
// 新增操作
const addItem = async () => {
  restDialogForm();
  dialogTitle.value = '新增';
  formDisabled.value = false;
  dialogFormVisible.value = true;
};
// 查看详情
const seeDetails = async (row) => {
  dialogTitle.value = '详情';
  setDialogForm(row);
  formDisabled.value = true;
  dialogFormVisible.value = true;
};
// 编辑操作
const handleEdit = (row) => {
  console.log('要编辑的行: ', row);
  dialogTitle.value = '编辑';
  setDialogForm(row);
  formDisabled.value = false;
  dialogFormVisible.value = true;
};
const setDialogForm = (row) => {
  dialogForm.id = row.id;
  dialogForm.name = row.name;
  dialogForm.phone = row.phone;
  dialogForm.landId = row.landId;
  dialogForm.landName = row.landName;
  dialogForm.detectionTime = row.detectionTime;
  dialogForm.detectionResult = row.detectionResult;
  dialogForm.detectionUnit = row.detectionUnit;
  dialogForm.detectionReport = row.detectionReport;
  if (row.pesticideSuperviseDetailVO.length > 0) {
    dialogForm.pesticideSuperviseDetailVO = row.pesticideSuperviseDetailVO.map((el) => {
      el.useNumber = Number(el.useNumber);
      el.pesticideId = Number(el.pesticideId);
      return el;
    });
  }
};
// 删除操作
const handleDelete = (row) => {
  app
    .$confirm(`删除后信息将不可查看，确认要删除吗？`, '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      deleteGoods(row.id)
        .then((res) => {
          if (res.code === 200) {
            onSubmit();
            app.$message.success('删除成功！');
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};
const deleteGoods = async (ids) => {
  try {
    let res = await delPesticide(ids);
    return res;
  } catch (error) {
    return false;
  }
};
const onSaveCategory = () => {
  console.log(dialogForm);
  dialogRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        let param = { ...dialogForm };
        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 = async () => {
  restDialogForm();
  dialogFormVisible.value = false;
};
const restDialogForm = () => {
  Object.assign(dialogForm, {
    id: '',
    name: '',
    phone: '',
    landId: '',
    landName: '',
    detectionTime: '',
    detectionResult: '',
    detectionUnit: '',
    detectionReport: '',
    pesticideSuperviseDetailVO: [{ pesticideId: '', pesticideName: '', useNumber: 1, useTime: '', useUnit: 'ml' }],
  });
};

onMounted(() => {
  onSubmit();
  getLandsList();
  getPesticidesList();
});
</script>
<style lang="scss" scoped>
.dialog-form-item {
  :deep(.el-upload--picture-card) {
    width: 120px;
    height: 120px;
  }
  :deep(.file-uploader__upload) {
    width: 120px;
    height: 120px;
  }
  :deep(.el-upload-list__item) {
    width: 120px;
    height: 120px;
  }
}
</style>
