<template>
  <div class="device-page">
    <div class="device-panel">

      <!-- 筛选 -->
      <div class="filter-bar">
        <div class="filter-l">
          <span class="filter-bar__label">搜索姓名</span>
          <el-select
            v-model="deviceName"
            class="filter-bar__select"
            clearable
            filterable
            placeholder="请选择姓名"
          >
            <el-option
              v-for="item in deviceNameOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="filter-r">
          <el-button class="btn-reset" @click="handleReset">重置</el-button>
          <el-button class="btn-search" type="warning" @click="handleSearch">搜索</el-button>
        </div>
      </div>

      <div class="device-content">
        <div class="toolbar">
          <div class="tabs">
            <div v-for="tab in tabs" :key="tab.key" class="tabs__item" :class="{ 'is-active': activeTab === tab.key }"
              @click="handleTabChange(tab.key)">
              {{ tab.label }}({{ tab.count }})
            </div>
          </div>
          <el-button class="btn-add" type="warning" @click="handleAdd">新增设备</el-button>
        </div>

        <el-table
          :data="tableData"
          :span-method="objectSpanMethod"
          class="device-table"
          row-key="rowKey"
          border
          header-cell-class-name="device-table__header"
        >
          <el-table-column label="姓名/手机号" min-width="120">
            <template #default="{ row }">
              <div class="person-cell">
                <div class="person-cell__name">{{ row.name }}</div>
                <div class="person-cell__phone">{{ row.phone }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="cropCategory" label="种植品类" min-width="100" show-overflow-tooltip />

          <el-table-column label="种植品种" min-width="110">
            <template #default="{ row }">
              <span class="variety-tag">{{ row.variety }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="phenology" label="物候期" min-width="110" />

          <el-table-column prop="area" label="种植面积" min-width="100" />

          <el-table-column label="起种点" min-width="170">
            <template #default="{ row }">
              <div class="start-point-cell">
                <span class="start-point-tag">{{ row.startPoint }}</span>
                <span class="start-point-date">{{ row.startDate }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="种植点位" min-width="160">
            <template #default="{ row }">
              <div class="location-cell">
                <span class="location-cell__text" :title="row.plantLocation">{{ row.plantLocation }}</span>
                <el-button link type="warning" class="link-btn" @click="handleViewPlantLocation(row)">
                  查看点位
                </el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="常驻点位" min-width="160">
            <template #default="{ row }">
              <div class="location-cell">
                <span class="location-cell__text" :title="row.residentLocation">{{ row.residentLocation }}</span>
                <el-button link type="warning" class="link-btn" @click="handleViewResidentLocation(row)">
                  查看点位
                </el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="168" fixed="right" align="center">
            <template #default="{ row }">
              <div class="ops">
                <el-button class="ops__btn" @click="handleEdit(row)">编辑</el-button>
                <el-button class="ops__btn" @click="handleDetail(row)">详情</el-button>
                <el-button class="ops__btn ops__btn--danger" type="danger" @click="handleDelete(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pager">
          <span class="pager__total">共 {{ total }} 项数据</span>
          <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
            layout="sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50]" :total="total" :pager-count="7" />
        </div>
      </div>

    </div>
  </div>

  <DeviceFormDialog
    v-model="dialogVisible"
    :mode="dialogMode"
    :data="editingRow"
    @submit="handleDialogSubmit"
  />

  <DeviceDetailDialog
    v-model="detailVisible"
    :data="detailRow"
    @edit="handleDetailEdit"
  />
</template>

<script setup>
import { computed, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DeviceFormDialog from "./DeviceFormDialog.vue";
import DeviceDetailDialog from "./DeviceDetailDialog.vue";

const NAMES = ["张洋", "李明", "王芳", "赵强", "陈丽"];
const VARIETIES = [
  ["妃子笑", "桂味"],
  ["糯米糍", "白糖罂"],
  ["仙进奉", "桂味", "妃子笑"],
  ["桂味"],
];

const buildMockRows = (count = 40) => {
  const list = [];
  for (let i = 1; i <= count; i++) {
    // 保证首条与设计图一致：一人 + 一品类 + 多品种
    const varieties = i === 1 ? ["妃子笑", "桂味"] : VARIETIES[i % VARIETIES.length];
    list.push({
      id: i,
      name: i === 1 ? "张洋" : NAMES[i % NAMES.length],
      phone: i === 1 ? "19871533168" : `1987153${String(3160 + (i % 40)).padStart(4, "0")}`,
      cropCategory: "荔枝",
      residentLocation: "位置位置位置位置",
      tabKey: i % 2 === 0 ? "service" : "owner",
      plantings: varieties.map((variety) => ({
        variety,
        phenology: "生育期一",
        area: "158亩",
        startPoint: "来白点",
        startDate: "2025.05.08",
        plantLocation: "位置位置位置位置",
      })),
    });
  }
  return list;
};

const allList = ref(buildMockRows());

const tabs = computed(() => [
  {
    key: "owner",
    label: "权属人员",
    count: allList.value.filter((i) => i.tabKey === "owner").length,
  },
  {
    key: "service",
    label: "农服人员",
    count: allList.value.filter((i) => i.tabKey === "service").length,
  },
]);

const activeTab = ref("owner");
const page = ref(1);
const pageSize = ref(20);
const deviceName = ref("");
const appliedDeviceName = ref("");

const deviceNameOptions = computed(() => {
  return [...new Set(allList.value.map((item) => item.name))];
});

/** 人员维度过滤 */
const filteredPersons = computed(() => {
  let list = allList.value.filter((item) => item.tabKey === activeTab.value);
  if (appliedDeviceName.value) {
    list = list.filter((item) => item.name === appliedDeviceName.value);
  }
  return list;
});

const total = computed(() => filteredPersons.value.length);

/** 人员维度分页后，按种植记录展开为表格行 */
const tableData = computed(() => {
  const start = (page.value - 1) * pageSize.value;
  const persons = filteredPersons.value.slice(start, start + pageSize.value);
  const rows = [];

  persons.forEach((person) => {
    const plantings = person.plantings?.length
      ? person.plantings
      : [{ variety: "-", phenology: "-", area: "-", startPoint: "-", startDate: "-", plantLocation: "-" }];

    plantings.forEach((planting, idx) => {
      rows.push({
        ...person,
        ...planting,
        rowKey: `${person.id}-${idx}`,
        plantIndex: idx,
        plantCount: plantings.length,
        // 兼容原弹窗字段
        code: person.code || "农场-类型-ID",
        type: person.cropCategory,
        location: person.residentLocation,
        ownerName: person.name,
        ownerPhone: person.phone,
        categories: [],
        serviceRecords: [],
      });
    });
  });

  return rows;
});

/** 需合并的列：姓名/手机号、种植品类、常驻点位、操作 */
const MERGE_COLUMN_INDEXES = new Set([0, 1, 7, 8]);

const objectSpanMethod = ({ row, columnIndex }) => {
  if (!MERGE_COLUMN_INDEXES.has(columnIndex)) {
    return { rowspan: 1, colspan: 1 };
  }

  if (row.plantIndex === 0) {
    return { rowspan: row.plantCount, colspan: 1 };
  }

  return { rowspan: 0, colspan: 0 };
};

const handleTabChange = (key) => {
  activeTab.value = key;
  page.value = 1;
};

const handleSearch = () => {
  appliedDeviceName.value = deviceName.value || "";
  page.value = 1;
};

const handleReset = () => {
  deviceName.value = "";
  appliedDeviceName.value = "";
  page.value = 1;
};

const dialogVisible = ref(false);
const dialogMode = ref("add");
const editingRow = ref(null);
const detailVisible = ref(false);
const detailRow = ref(null);

const handleAdd = () => {
  dialogMode.value = "add";
  editingRow.value = null;
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  const person = allList.value.find((item) => item.id === row.id) || row;
  dialogMode.value = "edit";
  editingRow.value = {
    ...person,
    ownerName: person.name,
    ownerPhone: person.phone,
    location: person.residentLocation,
  };
  dialogVisible.value = true;
};

const handleDetail = (row) => {
  const person = allList.value.find((item) => item.id === row.id) || row;
  detailRow.value = {
    ...person,
    // 兼容弹窗字段
    code: person.code || "农场-类型-ID",
    type: person.cropCategory,
    location: person.residentLocation,
    ownerName: person.name,
    ownerPhone: person.phone,
  };
  detailVisible.value = true;
};

const handleDetailEdit = () => {
  if (!detailRow.value) return;
  detailVisible.value = false;
  handleEdit(detailRow.value);
};

const handleDialogSubmit = ({ mode, data }) => {
  const plantings = (data.plantings || []).map((p) => ({
    variety: p.variety,
    phenology: p.phenology || "生育期一",
    area: p.area,
    startPoint: p.startPoint,
    startDate: p.startDate,
    plantLocation: p.plantLocation,
    plantLocationWkt: p.plantLocationWkt || "",
  }));

  const categories = (data.categories || []).map((g) => ({
    category: g.category,
    plantings: (g.plantings || []).map((p) => ({
      variety: p.variety,
      phenology: p.phenology || "生育期一",
      area: p.area,
      startPoint: p.startPoint,
      startDate: p.startDate,
      plantLocation: p.plantLocation,
      plantLocationWkt: p.plantLocationWkt || "",
    })),
  }));

  if (mode === "edit" && data.id != null) {
    const idx = allList.value.findIndex((item) => item.id === data.id);
    if (idx > -1) {
      allList.value[idx] = {
        ...allList.value[idx],
        name: data.ownerName || data.name || allList.value[idx].name,
        phone: data.ownerPhone || data.phone || allList.value[idx].phone,
        residentLocation:
          data.residentLocation || data.location || allList.value[idx].residentLocation,
        locationWkt: data.locationWkt || allList.value[idx].locationWkt || "",
        cropCategory: data.cropCategory || categories[0]?.category || allList.value[idx].cropCategory,
        categories,
        plantings: plantings.length ? plantings : allList.value[idx].plantings,
      };
      if (detailRow.value?.id === data.id) {
        detailRow.value = { ...allList.value[idx] };
      }
    }
    return;
  }

  const nextId = allList.value.reduce((max, item) => Math.max(max, item.id), 0) + 1;
  allList.value.unshift({
    id: nextId,
    name: data.ownerName || data.name || "新人员",
    phone: data.ownerPhone || data.phone || "",
    cropCategory: data.cropCategory || categories[0]?.category || "荔枝",
    residentLocation: data.residentLocation || data.location || "位置位置位置位置",
    locationWkt: data.locationWkt || "",
    tabKey: activeTab.value,
    categories,
    plantings: plantings.length
      ? plantings
      : [
          {
            variety: "妃子笑",
            phenology: "生育期一",
            area: "158亩",
            startPoint: "来白点",
            startDate: "2025.05.08",
            plantLocation: "位置位置位置位置",
          },
        ],
  });
};

const handleViewPlantLocation = () => ElMessage.info("查看种植点位");
const handleViewResidentLocation = () => ElMessage.info("查看常驻点位");

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除「${row.name}」吗？`, "提示", {
    type: "warning",
    confirmButtonText: "删除",
    cancelButtonText: "取消",
  })
    .then(() => {
      allList.value = allList.value.filter((item) => item.id !== row.id);
      ElMessage.success("已删除");
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
.device-page {
  box-sizing: border-box;
  min-height: 100%;
  padding: 25px;
}

.device-panel {
  min-height: calc(100% - 0px);
  display: flex;
  flex-direction: column;
}

.device-content {
  background: #fff;
  border-radius: 5px;
  padding: 0 10px;

}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 30px;
  padding: 0 12px;
  border-radius: 5px;
  height: 72px;
  background: #fff;
  margin-bottom: 20px;
}
.filter-r {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-bar__label {
  flex-shrink: 0;
  font-size: 14px;
  color: #333;
  padding-right: 8px;
}

.filter-bar__select {
  width: 220px;
}

.btn-reset {
  height: 32px;
  padding: 0 18px;
  color: $warning-color;
  background: #fff;
  border-color: $warning-color;
  border-radius: 4px;

  &:hover,
  &:focus {
    color: #fff;
    background: $warning-color;
    border-color: $warning-color;
  }
}

.btn-search {
  // --el-button-bg-color: #{$warning-color};
  // --el-button-border-color: #{$warning-color};
  // --el-button-hover-bg-color: #{mix(#fff, $warning-color, 12%)};
  // --el-button-hover-border-color: #{mix(#fff, $warning-color, 12%)};
  // --el-button-active-bg-color: #{mix(#000, $warning-color, 8%)};
  // --el-button-active-border-color: #{mix(#000, $warning-color, 8%)};
  height: 32px;
  padding: 0 18px;
  border-radius: 4px;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  border-bottom: 1px solid #f0f0f0;
}

.tabs {
  display: flex;
  align-items: stretch;
  height: 100%;
  gap: 28px;
}

.tabs__item {
  position: relative;
  display: flex;
  align-items: center;
  height: 100%;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  user-select: none;
  padding: 0 16px;

  &:hover {
    color: $warning-color;
  }

  &.is-active {
    color: $warning-color;
    font-weight: 500;

    &::after {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: 2px;
      background: $warning-color;
    }
  }
}

.btn-add {
  // --el-button-bg-color: #{$warning-color};
  // --el-button-border-color: #{$warning-color};
  // --el-button-hover-bg-color: #{mix(#fff, $warning-color, 12%)};
  // --el-button-hover-border-color: #{mix(#fff, $warning-color, 12%)};
  // --el-button-active-bg-color: #{mix(#000, $warning-color, 8%)};
  // --el-button-active-border-color: #{mix(#000, $warning-color, 8%)};
  height: 36px;
  padding: 0 18px;
  border-radius: 4px;
}

.device-table {
  flex: 1;
  width: 100%;
  margin-top: 20px;

  :deep(.device-table__header) {
    &:nth-child(2) {
      color: #818080;
    }
    background: #F5F5F5 !important;
    color: #535353;
    font-weight: 500;
  }

  :deep(.el-table__cell) {
    padding: 12px 0;
    vertical-align: middle;
  }

  :deep(.el-table__body .cell) {
    padding: 0 12px;
  }

  :deep(.el-checkbox__input.is-checked .el-checkbox__inner),
  :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
    background-color: $warning-color;
    border-color: $warning-color;
  }
}

.person-cell {
  color: #535353;
  font-size: 14px;
  line-height: 22px;
}

.person-cell__name {
  font-weight: 500;
}

.person-cell__phone {
  color: #818080;
  font-size: 13px;
}

.variety-tag {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 4px;
  background: rgba($warning-color, 0.12);
  color: $warning-color;
  font-size: 12px;
  line-height: 22px;
}

.start-point-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.start-point-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  background: #f2f2f2;
  color: #666;
  font-size: 12px;
  line-height: 20px;
}

.start-point-date {
  color: #535353;
  font-size: 14px;
}

.location-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 2px;
}

.location-cell__text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  color: #535353;
  font-size: 14px;
}

.link-btn {
  padding: 0;
  height: auto;
  font-size: 14px;
}

.ops {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.ops__btn {
  margin: 0 !important;
  height: 28px;
  padding: 0 6px;
  font-size: 14px;
  color: #4c4c4c;
  background: #f2f2f2;
  border: 1px solid #d2d2d2;
  border-radius: 2px;

  &:hover {
    color: $warning-color;
    border-color: rgba($warning-color, 0.45);
    background: rgba($warning-color, 0.06);
  }
}

.ops__btn--danger {
  color: #fff !important;
  background: #f56b6b !important;
  border-color: #f56b6b !important;

  &:hover {
    color: #fff !important;
  }
}

.pager {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 34px;
}

.pager__total {
  color: rgba(0, 0, 0, 0.6);
  font-size: 14px;
}

:deep(.el-pagination.is-background .el-pager li.is-active) {
  background-color: $warning-color !important;
}

:deep(.el-pagination.is-background .el-pager li:hover) {
  color: $warning-color;
}

:deep(.el-pagination__jump) {
  margin-left: 12px;
}
</style>
