<template>
  <div class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model="state.form"
      v-model:page="state.pageData"
      :table-loading="state.loading"
      :data="state.data"
      :option="state.options"
      @refresh-change="refreshChange"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
    >
      <template #menu-left>
        <el-button type="primary" icon="Plus" @click="onAdd">新增</el-button>
        <el-button type="success" icon="download" @click="onExport">导出</el-button>
      </template>
      <template #menu="{ row }">
        <custom-table-operate :actions="state.options.actions" :data="{ row }" />
      </template>

      <template #search>
        <div class="custom-search">
          <div class="search-fields">
            <div class="search-item">
              <AreaCascader
                v-model:region-code="areaQuery.regionCode"
                v-model:grid-id="areaQuery.gridId"
                placeholder="选择行政区域与网格"
                :show-separator="true"
                :width="500"
              />
            </div>
            <div class="search-item">
              <span>种植作物：</span>
              <el-select v-model="state.query.cropsId" placeholder="种植作物" :clearable="true">
                <el-option v-for="item in cropsOptions" :key="item.id" :label="item.cropsName" :value="item.id" />
              </el-select>
            </div>
            <div class="search-item">
              <span>计划编号：</span>
              <el-input v-model="state.query.id" placeholder="计划编号" :clearable="true" />
            </div>
            <div class="search-item">
              <span>计划名称：</span>
              <el-input v-model="state.query.planName" placeholder="计划名称" :clearable="true" />
            </div>
          </div>
          <div class="search-buttons">
            <el-button type="primary" @click="searchChange"> 查询 </el-button>
            <el-button @click="resetSearch"> 重置 </el-button>
          </div>
        </div>
      </template>
    </avue-crud>

    <el-dialog v-model="detailDialogVisible" title="年度种植计划详情页" width="800" class="detail-dialog">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="年度种植计划" name="basic">
          <h3>{{ currentDetailRow.planName }}</h3>
          <div>所属行政区域：{{ currentDetailRow.regionName }}</div>
          <div>所属网格：{{ currentDetailRow.gridName }}</div>
          <div>计划编号：{{ currentDetailRow.id }}</div>
          <div>计划名称：{{ currentDetailRow.planName }}</div>
          <div>种植作物：{{ currentDetailRow.cropsName }}</div>
          <div>种植面积：{{ currentDetailRow.planParameters?.plantingArea }}</div>
          <div>种植月份：{{ currentDetailRow.planParameters?.plantingMonths }}</div>
          <div>
            生长周期：{{ currentDetailRow.planParameters?.growthCycle }}
            {{ getGrowthCycleUnitName(currentDetailRow.planParameters?.growthCycleUnit) }}
          </div>
        </el-tab-pane>
        <el-tab-pane label="实际种植情况" name="planting">
          <h3>{{ currentDetailRow.planName }}</h3>
          <div>所属行政区域：{{ currentDetailRow.regionName }}</div>
          <div>所属网格：{{ currentDetailRow.gridName }}</div>
          <div>计划编号：{{ currentDetailRow.id }}</div>
          <div>计划名称：{{ currentDetailRow.planName }}</div>
          <div>种植作物：{{ currentDetailRow.cropsName }}</div>
          <div>种植面积：{{ currentDetailRow.actualParameters?.plantingArea }}</div>
          <div>种植月份：{{ currentDetailRow.actualParameters?.plantingMonths }}</div>
          <div>
            生长周期：{{ currentDetailRow.actualParameters?.growthCycle }}
            {{ getGrowthCycleUnitName(currentDetailRow.actualParameters?.growthCycleUnit) }}
          </div>
          <div>当前进度：{{ currentDetailRow.currentProgress }}%</div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增、重新制定计划和填写实际种植信息操作的共用弹窗 -->
    <el-dialog v-model="commonDialogVisible" :title="dialogTitle">
      <template #default>
        <el-form ref="planForm" :model="formData" :rules="formRules" label-width="120px" class="common-dialog">
          <el-form-item label="" label-width="0px">
            <AreaCascader v-model:value="areaFormData" split-rows label="所属行政区域-网格" :width="500" />
          </el-form-item>
          <!-- <AreaCascader v-model:value="areaFormData" split-rows label="所属行政区域-网格" :width="500" /> -->
          <el-form-item label="计划名称">
            <el-input v-model="formData.planName" style="width: 380px" />
          </el-form-item>
          <el-form-item label="种植作物" prop="cropsName">
            <el-select v-model="formData.cropsId" placeholder="种植作物" style="width: 380px" :clearable="true">
              <el-option v-for="item in cropsOptions" :key="item.id" :label="item.cropsName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="种植面积" prop="plantingArea">
            <el-input v-model="formData.plantingArea" style="width: 380px" />
          </el-form-item>
          <el-form-item label="种植月份" prop="plantingMonths">
            <el-select v-model="formData.plantingMonths" placeholder="请选择月份" style="width: 380px" :clearable="true">
              <el-option v-for="item in monthsOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="生长周期" prop="growthCycle">
            <el-input-number v-model="formData.growthCycle" :min="1" style="width: 300px" />
            <el-select v-model="formData.growthCycleUnit" disabled style="width: 68px; margin: 0; padding: 0">
              <el-option label="天" value="1" />
              <el-option label="周" value="2" />
              <el-option label="月" value="3" />
              <el-option label="年" value="4" />
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commonDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref, computed, onMounted, watch } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { isEmpty, downloadFile } from '@/utils';
import { useUserStore } from '@/store/modules/user';
import { getAnnualList, examineAnnual, delAnnual, exportAnnua } from '@/apis/land.js';
import { pageCropsList } from '@/apis/landResourceManagement/cropsManagement/index.js';
import { saveAnnual, editAnnual, saveActualProgress, getAnnualDetail } from '@/apis/landResourceManagement/plantingPlan/index.js';

const app = useApp();
const crudRef = ref(null);
const userStore = useUserStore();
// 用于 AreaCascader 绑定的对象
const areaFormData = ref({
  regionCode: '',
  gridName: '',
  gridId: '',
});
watch(
  areaFormData,
  (newVal) => {
    formData.value.regionCode = newVal.regionCode;
    formData.value.gridName = newVal.gridName;
    formData.value.gridId = newVal.gridId;
  },
  { deep: true }
);
const formRules = reactive({
  // planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  // cropsId: [{ required: true, message: '请选择种植作物', trigger: 'change' }],
  // plantingArea: [
  //   { required: true, message: '请输入种植面积', trigger: 'blur' },
  //   { type: 'number', message: '种植面积必须为数字', trigger: 'blur' },
  // ],
  // plantingMonths: [{ required: true, message: '请选择种植月份', trigger: 'change' }],
  // growthCycle: [
  //   { required: true, message: '请输入生长周期', trigger: 'blur' },
  //   { type: 'number', message: '生长周期必须为数字', trigger: 'blur' },
  // ],
});
// 存储种植作物列表
const cropsOptions = ref([]);
// 初始化种植作物列表
const fetchCropsList = async () => {
  try {
    // 调用 pageCropsList 获取种植作物分页列表
    const res = await pageCropsList({ status: '0' });
    if (res.code === 200) {
      console.log('res :>> ', res.data.records);
      cropsOptions.value = res.data.records;
      console.log('object :>> ', cropsOptions.value);
    }
  } catch (error) {
    app.$message.error('获取种植作物列表失败');
  }
};
onMounted(() => {
  fetchCropsList();
});

// 根据单位值获取单位名称
const getGrowthCycleUnitName = (unit) => {
  const unitMap = {
    1: '天',
    2: '周',
    3: '月',
    4: '年',
  };
  return unitMap[unit] || '';
};
// 获取详情数据
const fetchDetailData = async (id) => {
  try {
    const res = await getAnnualDetail(id);
    if (res.code === 200) {
      currentDetailRow.value = res.data;
    } else {
      app.$message.error(res.msg || '获取详情数据失败');
    }
  } catch (error) {
    console.error('获取详情数据出错:', error);
    app.$message.error('获取详情数据失败，请稍后重试');
  }
};
const openDetailDialog = async (row) => {
  detailDialogVisible.value = true;
  await fetchDetailData(row.id);
};
// 详情弹窗
const detailDialogVisible = ref(false);
// 详情弹窗当前激活的标签页
const activeTab = ref('basic');
const currentDetailRow = ref({});
// 共用弹窗
const commonDialogVisible = ref(false);
// 当前操作类型，跟弹窗标题一致
const currentAction = ref('');
// 弹窗标题
const dialogTitle = computed(() => {
  if (currentAction.value === 'reCreate') {
    return '重新制定计划';
  } else if (currentAction.value === 'fillActual') {
    return '填写实际种植信息';
  } else if (currentAction.value === 'add') {
    return '新增年度种植计划';
  }
  return '';
});

const monthsOptions = ref([
  { value: 1, label: '1月' },
  { value: 2, label: '2月' },
  { value: 3, label: '3月' },
  { value: 4, label: '4月' },
  { value: 5, label: '5月' },
  { value: 6, label: '6月' },
  { value: 7, label: '7月' },
  { value: 8, label: '8月' },
  { value: 9, label: '9月' },
  { value: 10, label: '10月' },
  { value: 11, label: '11月' },
  { value: 12, label: '12月' },
]);
// 表单引用
const planForm = ref(null);
// 判断当前用户是否是网格员
const isGridMember = computed(() => {
  const userRoles = userStore.getUserInfo().roles;
  console.log('当前用户角色:', userRoles);
  return userRoles.some((role) => role.roleKey === 'gridMember');
  // return true;
});

// 级联选择器查询参数，必须使用 ref ，否则无法使用 v-model:value 更新
const areaQuery = ref({
  regionCode: '',
  gridName: '',
  gridId: '',
});

const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
    id: '',
    planName: '',
    cropsName: '',
    cropsId: '',
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '',
    addBtn: false,
    searchBtn: false,
    emptyBtn: false,
    fit: true,
    column: [
      { label: '计划编号', prop: 'id', minWidth: 100 },
      { label: '计划名称', prop: 'planName' },
      { label: '种植作物', prop: 'cropsName' },
      { label: '种植面积', prop: 'plantingArea', formatter: (row, column, cellValue) => `${cellValue} 亩` },
      { label: '种植月份', prop: 'plantingMonths', formatter: (row, column, cellValue) => `${cellValue} 月` },
      {
        label: '生长周期',
        prop: 'growthCycle',
        formatter: (row, column, cellValue) => {
          const unitMap = { 1: '天', 2: '周', 3: '月', 4: '年' };
          const unit = unitMap[row.growthCycleUnit] || '';
          return `${cellValue} ${unit}`;
        },
      },
      { label: '所属行政区域', prop: 'regionName' },
      { label: '所属网格', prop: 'gridName' },
      { label: '当前进度', prop: 'currentProgress' },
    ],
    actions: [
      {
        name: '查看',
        icon: 'view',
        event: ({ row }) => {
          openDetailDialog(row);
        },
      },
      {
        name: '重新制定计划',
        icon: 'edit',
        event: ({ row }) => {
          currentAction.value = 'reCreate';
          formData.value = { ...row };
          if (isGridMember.value) {
            formData.value.regionName = row.regionName;
            formData.value.gridName = row.gridName;
          }
          formData.value.growthCycleUnit = row.growthCycleUnit || '1';
          commonDialogVisible.value = true;
        },
      },
      {
        name: '填写实际种植信息',
        icon: 'edit',
        event: ({ row }) => {
          currentAction.value = 'fillActual';
          formData.value = { ...row };
          if (isGridMember.value) {
            formData.value.regionName = row.regionName;
            formData.value.gridName = row.gridName;
          }
          formData.value.growthCycleUnit = row.growthCycleUnit || '1';
          commonDialogVisible.value = true;
        },
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});

const formData = ref({
  year: '',
  regionCode: '',
  gridId: '',
  regionName: '',
  gridName: '',
  planName: '', // 必填
  cropsId: null,
  cropsName: '',
  plantingArea: null,
  plantingMonths: '',
  growthCycle: '',
  growthCycleUnit: '1', // 默认单位为周
  note: '',
});
// 提交计划表单
const submitForm = async () => {
  try {
    // 表单验证
    await planForm.value.validate();
    // 验证通过，提交表单
    console.log('表单数据:', formData.value);

    if (currentAction.value === 'reCreate') {
      // 重新制定计划的提交逻辑
      await editAnnual(formData.value);
      app.$message.success('重新制定计划成功');
    } else if (currentAction.value === 'fillActual') {
      // 填写实际种植信息的提交逻辑
      await saveActualProgress(formData.value);
      app.$message.success('填写实际种植信息成功');
    } else if (currentAction.value === 'add') {
      // 新增计划的提交逻辑
      await saveAnnual(formData.value);
      app.$message.success('新增年度种植计划成功');
    }

    commonDialogVisible.value = false;
    loadData();
  } catch (error) {
    console.error('表单提交失败:', error);
    if (error.errors) {
      // 表单验证失败
      app.$message.error('请填写完整且正确的表单信息');
    } else {
      // API 调用失败
      app.$message.error('操作失败，请稍后重试');
    }
  }
};

const onAdd = () => {
  currentAction.value = 'add';
  formData.value = {
    regionName: '',
    gridName: '',
    planName: '',
    cropsName: '',
    plantingArea: '',
    plantingMonths: '',
    growthCycle: '',
    growthCycleUnit: '1',
  };
  commonDialogVisible.value = true;
};

// 加载
const loadData = () => {
  state.loading = true;
  getAnnualList(state.query)
    .then((res) => {
      if (res.code === 200) {
        const { current, size, total, records } = res.data;
        state.data = records;
        state.pageData = {
          currentPage: current || 1,
          pageSize: size || 10,
          total: total,
        };
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
      state.data = [];
    })
    .finally(() => {
      state.loading = false;
    });
};

loadData();

// 页数
const currentChange = (current) => {
  state.query.current = current;
  loadData();
};

// 条数
const sizeChange = (size) => {
  state.query.size = size;
  loadData();
};

// 搜索
const searchChange = () => {
  state.query = {
    ...state.query,
    ...areaQuery.value,
    current: 1,
  };
  console.log('搜索参数', state.query);
  loadData();
};

// 重置搜索
const resetSearch = () => {
  state.query = {
    current: 1,
    size: 10,
    id: '',
    planName: '',
    cropsName: '',
    cropsId: '',
  };
  areaQuery.value.regionCode = '';
  areaQuery.value.gridName = '';
  areaQuery.value.gridId = '';
  loadData();
};

// 刷新
const refreshChange = () => {
  loadData();
  app.$message.success('刷新成功');
};

// 选择
const selectionChange = (rows) => {
  state.selection = rows;
};

// 删除
const rowDel = (row, index, done) => {
  if (isEmpty(row)) return;
  app
    .$confirm(`删除后信息将不可查看，确认要删除吗？`, '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      console.info('删除');
      delAnnual({ id: row.id })
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('删除成功！');
            // done();
            loadData();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};
// 导出
const onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('当前暂时没有可供导出的数据！');
    return;
  }
  state.loading = true;
  const fileName = '年度计划明细表';
  exportAnnua(state.query)
    .then((res) => {
      if (res.status === 200) {
        downloadFile(res.data, `${fileName}.xlsx`, 'blob');
        app.$message.success('导出成功！');
      }
    })
    .catch((err) => {
      app.$message.error('导出失败！');
    })
    .finally(() => {
      state.loading = false;
    });
};
</script>
<style scoped lang="scss">
.custom-page {
  /* 详情弹窗样式 */

  /* 表单弹窗样式 */
  .el-dialog {
    .el-form {
      padding: 0 20px;
      width: 100%;
      // background-color: aqua;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;

      &-item {
        margin-bottom: 18px;
        width: 60%;
        // background-color: #606266;

        &__label {
          font-weight: 500;
          color: #606266;
        }

        /* 输入框和选择器统一宽度 */
        .el-input,
        .el-select,
        .el-cascader {
          width: 100%;
          max-width: 400px;
        }

        /* 数字输入框和单位选择器组合 */
        .el-input-number {
          margin-right: 10px;

          & + .el-select {
            width: 100px;
          }
        }
      }
    }
  }

  /* 按钮样式微调 */
  .el-button {
    padding: 8px 16px;
    border-radius: 4px;

    & + .el-button {
      margin-left: 12px;
    }
  }

  /* 搜索区域样式 */
  .custom-search {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 16px;
    border-radius: 8px;
    // background-color: #f5f7fa;

    .search-fields {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      width: 100%;
      margin-bottom: 16px;
    }

    .search-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .el-input,
      .el-select,
      .el-cascader {
        width: 200px;
      }
      span {
        font-size: 14px;
        color: #606266;
        align-self: center;
      }
    }

    .search-buttons {
      display: flex;
      align-self: center;
      gap: 12px;
      margin-left: 8px;
    }
  }
}
</style>
