<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="seedTypeId">
                <el-select v-model="formInline.seedTypeId" placeholder="请选择" clearable @change="seedTypeChange">
                  <el-option v-for="item in seedTypeList" :key="item.id" :value="item.id" :label="item.dataName" />
                </el-select>
              </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="false"
          @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="800" :close-on-click-modal="false">
      <el-form :inline="true" :label-width="'auto'">
        <LandSelect
          ref="landSelectRef"
          v-model="dialogForm.landId"
          :options="landSelectList"
          :disabled="formDisabled"
          :width="500"
          @change="handleLandChange"
        />
      </el-form>
      <el-descriptions title="地块信息" border class="mb-20 custom-descriptions" :column="2">
        <el-descriptions-item label="行政区域编码">{{ dialogForm.regionCode }}</el-descriptions-item>
        <el-descriptions-item label="行政区域名称">{{ dialogForm.regionName }}</el-descriptions-item>
        <el-descriptions-item label="网格编码">{{ dialogForm.gridId }}</el-descriptions-item>
        <el-descriptions-item label="网格名称">{{ dialogForm.gridName }}</el-descriptions-item>
        <el-descriptions-item label="地块编码">{{ dialogForm.landName }}</el-descriptions-item>
        <el-descriptions-item label="地块名称">{{ dialogForm.landId }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="经营主体信息" border class="mb-20 custom-descriptions" :column="2">
        <el-descriptions-item label="经营主体编码">{{ dialogForm.businessEntityCode }}</el-descriptions-item>
        <el-descriptions-item label="经营主体名称">{{ dialogForm.businessEntityName }}</el-descriptions-item>
      </el-descriptions>
      <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="fertilizeId" class="dialog-form-item">
          <el-input v-model="dialogForm.fertilizeId" clearable placeholder="请输入肥料编号" />
        </el-form-item>
        <el-form-item label="肥料名称" prop="fertilizeName" class="dialog-form-item">
          <el-input v-model="dialogForm.fertilizeName" clearable placeholder="请输入肥料名称" />
        </el-form-item>
        <el-form-item label="使用量" required prop="useNumber" class="dialog-form-item">
          <el-input-number v-model="dialogForm.useNumber" :min="1" :controls="false" placeholder="请输入使用量" style="width: 150px" />
          <el-select v-model="dialogForm.useUnit" placeholder="请选择" style="width: 80px">
            <el-option v-for="el in unitList" :key="el.dictValue" :value="el.dictValue" :label="el.dictValue" />
          </el-select>
        </el-form-item>
        <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>
      <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';
const { getMaterailTypes } = inputSuppliesApi;
import {
  getFertilizeUseRegulatoryRecords,
  fertilizeUseRegulatorySave,
  editFertilizeUseRegulatory,
  delFertilizeUseRegulatory,
  getLandList,
} from '@/apis/inputSuppliesApi/supervisionOfInputs';
import request from '@/utils/axios';
import { GetDictTypeInfo } from '@/apis/system/dictType';
import { useApp } from '@/hooks';
const app = useApp();

// 查询条件
const formInline = reactive({
  name: '',
  seedTypeId: '',
  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 tableLoading = ref(false);
const tableTotal = ref(0);
const columns = ref([
  { prop: 'regionCode', label: '行政区域编码' },
  { prop: 'regionName', label: '行政区域名称' },
  { prop: 'gridId', label: '网格编码' },
  { prop: 'gridName', label: '网格名称' },
  { prop: 'landId', label: '地块编码' },
  { prop: 'landName', label: '地块名称' },
  { prop: 'name', label: '姓名' },
  { prop: 'phone', label: '联系方式' },
  { prop: 'fertilizeId', label: '肥料编号' },
  { prop: 'fertilizeName', label: '肥料名称' },
  { prop: 'action', label: '操作', slotName: 'action', width: 230, fixed: 'right' },
]);
const handlePaginationChange = ({ page, pageSize }) => {
  formInline.current = page;
  formInline.size = pageSize;
  loadData();
};
const loadData = async () => {
  tableLoading.value = true;
  try {
    let response = await getFertilizeUseRegulatoryRecords(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 extractThirdLevelChildren = (dataArray) => {
  let result = [];
  // 遍历第一层数组
  for (const level1 of dataArray) {
    // 检查第一层是否有children且是数组
    if (level1.children && Array.isArray(level1.children)) {
      // 遍历第二层数组
      for (const level2 of level1.children) {
        // 检查第二层是否有children且是数组
        if (level2.children && Array.isArray(level2.children)) {
          // 将第三层的所有对象添加到结果数组中
          result.push(...level2.children);
        }
      }
    }
  }
  return result;
};
const seedTypeChange = () => {
  console.log(formInline.seedTypeId);
  // 重新获取表格数据，需添加参数
};

const dialogFormVisible = ref(false);
const dialogRef = ref(null);
const dialogTitle = ref('新增');
const formDisabled = ref(false);
const landSelectRef = ref(null);
const dialogForm = reactive({
  regionCode: '', //所属行政区域代码
  regionName: '', //所属行政区域名称
  gridId: '', //所属网格代码
  gridName: '', //所属网格名称
  landId: '', //地块id
  landName: '', //地块名称
  name: '', //姓名
  phone: '', //联系方式
  fertilizeId: '', //肥料名称id
  fertilizeName: '', //肥料名称
  useNumber: 1, //使用量
  useUnit: 'g', //使用量单位
  detectionTime: '', //使用时间
  businessEntityCode: '', //经营主体编码
  businessEntityName: '', //经营主体名称
});
const dialogFormRules = ref({
  fertilizeId: [{ required: true, message: '请输入肥料编号', trigger: 'blur' }],
  fertilizeName: [{ required: true, message: '请输入肥料名称', trigger: 'blur' }],
  useNumber: [{ required: true, message: '请输入使用量', trigger: ['change', 'blur'] }],
  detectionTime: [{ required: true, message: '请选择使用时间', trigger: 'blur' }],
});

const addItem = async () => {
  restDialogForm();
  dialogTitle.value = '新增';
  formDisabled.value = false;
  dialogFormVisible.value = true;
};
const seeDetails = async (row) => {
  dialogTitle.value = '详情';
  formDisabled.value = true;
  dialogForm.landId = row.landId;
  getDetails();
  dialogForm.fertilizeId = row.fertilizeId;
  dialogForm.fertilizeName = row.fertilizeName;
  dialogForm.useNumber = row.useNumber;
  dialogForm.useUnit = row.useUnit;
  dialogForm.detectionTime = row.useTime;
  dialogFormVisible.value = true;
};
const handleEdit = (row) => {
  console.log('要编辑的行: ', row);
  dialogTitle.value = '编辑';
  formDisabled.value = false;
  dialogForm.landId = row.landId;
  getDetails();
  dialogForm.fertilizeId = row.fertilizeId;
  dialogForm.fertilizeName = row.fertilizeName;
  dialogForm.useNumber = row.useNumber;
  dialogForm.useUnit = row.useUnit;
  dialogForm.detectionTime = row.useTime;
  dialogFormVisible.value = true;
};
const setDialogForm = (row) => {
  dialogForm.regionCode = row.gridAreaCode;
  dialogForm.regionName = row.fullRegionName;
  dialogForm.gridId = row.gridId;
  dialogForm.gridName = row.gridName;
  dialogForm.landId = row.id;
  dialogForm.landName = row.landName;
  dialogForm.name = row.propertyName;
  dialogForm.phone = row.propertyPhone;
  dialogForm.businessEntityCode = row.businessEntityCode ?? '';
  dialogForm.businessEntityName = row.businessEntityName ?? '';
};
// 获取地块信息
const getDetails = async () => {
  let response = await request({
    url: `/land-resource/landManage/getLandInfo?landId=${dialogForm.landId}`,
  });
  console.log(response);
  if (response.code == 200) {
    if (response.data) {
      setDialogForm(response.data);
    } else {
      ElMessage.error('未查询到数据');
    }
  } else {
    ElMessage.error(response.message);
  }
};
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 delFertilizeUseRegulatory(ids);
    return res;
  } catch (error) {
    return false;
  }
};
const onSaveCategory = () => {
  console.log(dialogForm);
  if (dialogForm.landId == '') {
    landSelectRef.value.handleChange();
    return;
  }
  dialogRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        let param = { ...dialogForm };
        console.log(param);
        let response;
        if (dialogTitle.value == '新增') {
          response = await fertilizeUseRegulatorySave(param);
        } else {
          response = await editFertilizeUseRegulatory(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, {
    regionCode: '', //所属行政区域代码
    regionName: '', //所属行政区域名称
    gridId: '', //所属网格代码
    gridName: '', //所属网格名称
    landId: '', //地块id
    landName: '', //地块名称
    name: '', //姓名
    phone: '', //联系方式
    fertilizeId: '', //肥料名称id
    fertilizeName: '', //肥料名称
    useNumber: 1, //使用量
    useUnit: 'g', //使用量单位
    useTime: '', //使用时间
    businessEntityCode: '', //经营主体编码
    businessEntityName: '', //经营主体名称
  });
};

const seedTypeList = ref([]);
const seedTypeDialogList = ref([]);
const getSeedTypeList = async () => {
  try {
    let response = await getMaterailTypes({ moduleType: '4' });
    console.log(response);
    if (response.code == 200) {
      if (response.data?.length > 0) {
        seedTypeDialogList.value = response.data[0].children;
        let result = extractThirdLevelChildren(response.data);
        seedTypeList.value = result;
        console.log(seedTypeDialogList.value);
      }
    }
  } catch (error) {
    console.error(error);
  }
};

const unitList = ref([
  { dictCode: '52', dictValue: 'g' },
  { dictCode: '53', dictValue: 'kg' },
]);

const landSelectList = ref([]);
const getLandsList = async () => {
  let res = await getLandList();
  if (res.code == 200) {
    landSelectList.value = res.data;
  }
};
const handleLandChange = (val) => {
  console.log(val);
  if (val) {
    getDetails();
  } else {
    restDialogForm();
  }
};

const getEntityOptions = async () => {
  let res = await GetDictTypeInfo('sys_use_supervise_number');
  console.log(res);
  if (res.code == 200) {
    unitList.value = res.data;
  } else {
    unitList.value = [
      { dictCode: '52', dictValue: 'g' },
      { dictCode: '53', dictValue: 'kg' },
    ];
  }
};

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

  :deep(.file-uploader__upload) {
    width: 100px;
    height: 100px;
  }

  :deep(.el-upload-list__item) {
    width: 100px;
    height: 100px;
  }
}

/* 必须使用深度选择器 + 精确DOM层级 */
.custom-descriptions :deep(.el-descriptions__body) table.el-descriptions__table {
  table-layout: fixed; /* 关键属性1：强制等宽 */
  width: 100%;
}
.custom-descriptions :deep(.el-descriptions__label) {
  width: 130px !important; /* 关键属性2：固定宽度 */
  min-width: 130px !important;
  max-width: 130px !important;
  background: #f5f7fa;
  font-weight: bold;
  text-align: left;
  padding-right: 20px;
}
.custom-descriptions :deep(.el-descriptions__content) {
  width: calc(100% - 130px) !important; /* 自动填充剩余空间 */
  word-break: break-word;
}
</style>
