<template>
  <doc-alert title="【采购】采购订单、入库、退货" url="https://doc.iocoder.cn/erp/purchase/" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="户主姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入户主姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="住址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入住址"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="种植基地" prop="plantingBase">
        <el-input
          v-model="queryParams.plantingBase"
          placeholder="请输入种植基地"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="管理员姓名" prop="adminName" label-width="100px">
        <el-input
          v-model="queryParams.adminName"
          placeholder="请输入管理员姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="使用品种" prop="usedVariety">
        <el-select
          v-model="queryParams.usedVariety"
          placeholder="请选择使用品种"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in varietyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="移栽时间" prop="transplantTime">
        <el-date-picker
          v-model="queryParams.transplantTime"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          class="!w-240px"
        />
      </el-form-item>
      <!--      <el-form-item label="手机号码" prop="mobile">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.mobile"-->
      <!--          placeholder="请输入手机号码"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--          class="!w-240px"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="联系电话" prop="telephone">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.telephone"-->
      <!--          placeholder="请输入联系电话"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--          class="!w-240px"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:farmer:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:farmer:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @row-click="handleRowClick">
      <el-table-column label="户主姓名" align="center" prop="name" />
      <el-table-column label="住址" align="center" prop="address" />
      <el-table-column label="所属种植基地" align="center" prop="plantingBase" />
      <el-table-column label="合同号" align="center" prop="contractNumber" />
      <el-table-column label="签订面积" align="center" prop="contractedArea" />
      <el-table-column label="订购数量" align="center" prop="orderQuantity" />
      <el-table-column label="实种面积" align="center" prop="actualArea" />
      <el-table-column label="使用品种" align="center" prop="usedVariety" />
      <el-table-column label="种植方式" align="center" prop="plantingMethod" />
      <el-table-column label="管理员姓名" align="center" prop="adminName" />
      <!--      <el-table-column label="联系人" align="center" prop="contact" />-->
      <!--      <el-table-column label="手机号码" align="center" prop="mobile" />-->
      <!--      <el-table-column label="联系电话" align="center" prop="telephone" />-->
      <!--      <el-table-column label="电子邮箱" align="center" prop="email" />-->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click.stop="openForm('update', scope.row.id)"
            v-hasPermi="['erp:farmer:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click.stop="handleDelete(scope.row.id)"
            v-hasPermi="['erp:farmer:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <FarmerForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import { FarmerApi, FarmerVO } from '@/api/erp/purchase/farmer'
import FarmerForm from './FarmerForm.vue'

/** ERP 农户 列表 */
defineOptions({ name: 'ErpFarmer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<FarmerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

// 品种选项
const varietyOptions = ref([
  { value: '红宝石', label: '红宝石' },
  { value: '1401', label: '1401' },
  { value: '1501', label: '1501' },
  { value: '3366', label: '3366' }
])

// 获取当年的起始和结束时间
const getCurrentYearRange = () => {
  const now = new Date()
  const year = now.getFullYear()
  const startDate = `${year}-01-01 00:00:00`
  const endDate = `${year}-12-31 23:59:59`
  return [startDate, endDate]
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  address: undefined,
  plantingBase: undefined,
  adminName: undefined,
  usedVariety: undefined,
  transplantTime: getCurrentYearRange(),
  beginTransplantTime: undefined,
  endTransplantTime: undefined,
  mobile: undefined,
  telephone: undefined,
  type: 2
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params: any = {
      ...queryParams
    }

    // 处理日期范围
    if (params.transplantTime && params.transplantTime.length === 2) {
      params.beginTransplantTime = params.transplantTime[0]
      params.endTransplantTime = params.transplantTime[1]
      delete params.transplantTime
    }

    const data = await FarmerApi.getFarmerPage(params)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 行点击操作 */
const handleRowClick = (row: FarmerVO) => {
  openForm('update', row.id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FarmerApi.deleteFarmer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true

    // 构建导出参数
    const params: any = {
      ...queryParams
    }

    // 处理日期范围
    if (params.transplantTime && params.transplantTime.length === 2) {
      params.beginTransplantTime = params.transplantTime[0]
      params.endTransplantTime = params.transplantTime[1]
      delete params.transplantTime
    }

    const data = await FarmerApi.exportFarmer(params)
    download.excel(data, 'ERP 农户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
