<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="statYear">
          <template slot="label">{{ dmT("queryStatYear") }}</template>
          <el-select v-model="queryParams.statYear" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 120px">
            <el-option v-for="y in yearOptions" :key="y" :label="String(y)" :value="y" />
          </el-select>
        </el-form-item>
        <el-form-item prop="statMonth">
          <template slot="label">{{ dmT("queryStatMonth") }}</template>
          <el-select v-model="queryParams.statMonth" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 120px">
            <el-option v-for="m in monthOptions" :key="'q-' + m" :label="formatStatMonth(m)" :value="m" />
          </el-select>
        </el-form-item>
        <el-form-item prop="townDeptId">
          <template slot="label">{{ dmT("queryTown") }}</template>
          <el-select v-model="queryParams.townDeptId" :placeholder="dmCommon('pleaseSelect')" clearable filterable style="width: 180px">
            <el-option v-for="item in townOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ dmCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ dmCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:farmerHousehold:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dmCommon("add") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:farmerHousehold:import']"
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImportOpen"
          >{{ dmT("btnImport") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:farmerHousehold:export']"
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExportOpen"
          >{{ dmCommon("export") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <template slot="empty">
          <span>{{ dmT("emptyList") }}</span>
        </template>
        <el-table-column :label="dmT('colStatYear')" prop="statYear" align="center" width="90" />
        <el-table-column :label="dmT('colStatMonth')" align="center" width="80">
          <template slot-scope="scope">{{ formatStatMonth(scope.row.statMonth) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colTownName')" prop="townName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colVillageName')" prop="villageName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colHouseholdCount')" align="center" width="90">
          <template slot-scope="scope">{{ formatCount(scope.row.householdCount) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colPopulationCount')" align="center" width="90">
          <template slot-scope="scope">{{ formatCount(scope.row.populationCount) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colPastureContractArea')" align="center" width="130">
          <template slot-scope="scope">{{ formatDecimal(scope.row.pastureContractArea) }}</template>
        </el-table-column>
        <el-table-column :label="dmCommon('colOp')" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['dataModel:farmerHousehold:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:farmerHousehold:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:farmerHousehold:remove']" type="text" size="mini" @click="handleDelete(scope.row)">{{ dmCommon("delete") }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="open" width="980px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" class="fh-form" label-width="200px" size="small">
        <div class="fh-section-title">{{ dmT("sectionBasic") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="statYear" :rules="formRules.statYear">
              <template slot="label">{{ dmT("formStatYear") }}</template>
              <el-select v-model="form.statYear" :placeholder="dmCommon('pleaseSelect')" style="width: 100%">
                <el-option v-for="y in yearOptions" :key="'f-' + y" :label="String(y)" :value="y" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="statMonth" :rules="formRules.statMonth">
              <template slot="label">{{ dmT("formStatMonth") }}</template>
              <el-select v-model="form.statMonth" :placeholder="dmCommon('pleaseSelect')" style="width: 100%">
                <el-option v-for="m in monthOptions" :key="'fm-' + m" :label="formatStatMonth(m)" :value="m" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="villageDeptId" :rules="formRules.villageDeptId">
              <template slot="label">{{ dmT("formVillage") }}</template>
              <el-select
                v-model="form.villageDeptId"
                :placeholder="dmT('phVillageSearch')"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in villageOptions"
                  :key="'f-v-' + item.deptId"
                  :label="item.label"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="householdCount" :rules="formRules.count">
              <template slot="label">{{ dmT("formHouseholdCount") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.householdCount" :min="0" :precision="0" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitHousehold") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="populationCount" :rules="formRules.count">
              <template slot="label">{{ dmT("formPopulationCount") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.populationCount" :min="0" :precision="0" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitPerson") }}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="fh-section-title">{{ dmT("sectionPasture") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in pastureAreaFields" :key="field.prop" :span="12">
            <el-form-item :prop="field.prop" :rules="formRules.decimal">
              <template slot="label">{{ dmT(field.labelKey) }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form[field.prop]" :min="0" :precision="4" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT(field.unitKey) }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <template slot="label">{{ dmT("formPastureContractArea") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number :value="pastureContractAreaDisplay" :controls="false" disabled class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitMu") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-for="field in carryingFields" :key="field.prop" :span="12">
            <el-form-item :prop="field.prop" :rules="formRules.decimal">
              <template slot="label">{{ dmT(field.labelKey) }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form[field.prop]" :min="0" :precision="4" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT(field.unitKey) }}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="fh-section-title">{{ dmT("sectionCapFloor") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in yesNoFields" :key="field.prop" :span="12">
            <el-form-item :prop="field.prop">
              <template slot="label">{{ dmT(field.labelKey) }}</template>
              <el-radio-group v-model="form[field.prop]">
                <el-radio v-for="item in yesNoOptions" :key="field.prop + '-' + item" :label="item">{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="fh-section-title">{{ dmT("sectionSubsidy") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in subsidyRewardFields" :key="field.prop" :span="12">
            <el-form-item :prop="field.prop" :rules="formRules.decimal">
              <template slot="label">{{ dmT(field.labelKey) }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form[field.prop]" :min="0" :precision="4" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT(field.unitKey) }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <template slot="label">{{ dmT("formSubsidyRewardSubtotal") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number :value="subsidyRewardSubtotalDisplay" :controls="false" disabled class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitYuan") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-for="field in subsidyExtraFields" :key="field.prop" :span="12">
            <el-form-item :prop="field.prop" :rules="formRules.decimal">
              <template slot="label">{{ dmT(field.labelKey) }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form[field.prop]" :min="0" :precision="4" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT(field.unitKey) }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <template slot="label">{{ dmT("formSubsidyTotal") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number :value="subsidyTotalDisplay" :controls="false" disabled class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitYuan") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="remark" :rules="formRules.remark">
              <template slot="label">{{ dmT("formRemark") }}</template>
              <el-input v-model="form.remark" type="textarea" :rows="2" :placeholder="dmT('phRemark')" maxlength="500" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ dmCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ dmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dmCommon('viewTitle')" :visible.sync="viewOpen" width="980px" append-to-body>
      <el-form class="dm-view-form fh-form" label-width="200px" size="small">
        <div class="fh-section-title">{{ dmT("sectionBasic") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item :label="dmT('formStatYear')"><span>{{ viewRow.statYear || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formStatMonth')"><span>{{ formatStatMonth(viewRow.statMonth) }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formTown')"><span>{{ viewRow.townName || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formVillage')"><span>{{ viewRow.villageName || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formHouseholdCount')">
              <span>{{ formatWithUnit(formatCount(viewRow.householdCount), "unitHousehold") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formPopulationCount')">
              <span>{{ formatWithUnit(formatCount(viewRow.populationCount), "unitPerson") }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="fh-section-title">{{ dmT("sectionPasture") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in pastureAreaFields" :key="'vp-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)">
              <span>{{ formatWithUnit(formatDecimal(viewRow[field.prop]), field.unitKey) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formPastureContractArea')">
              <span>{{ formatWithUnit(formatDecimal(pastureContractAreaOf(viewRow)), "unitMu") }}</span>
            </el-form-item>
          </el-col>
          <el-col v-for="field in carryingFields" :key="'vc-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)">
              <span>{{ formatWithUnit(formatDecimal(viewRow[field.prop]), field.unitKey) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="fh-section-title">{{ dmT("sectionCapFloor") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in yesNoFields" :key="'vy-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)"><span>{{ viewRow[field.prop] || dash }}</span></el-form-item>
          </el-col>
        </el-row>

        <div class="fh-section-title">{{ dmT("sectionSubsidy") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in subsidyRewardFields" :key="'vsr-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)">
              <span>{{ formatWithUnit(formatDecimal(viewRow[field.prop]), field.unitKey) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formSubsidyRewardSubtotal')">
              <span>{{ formatWithUnit(formatDecimal(subsidyRewardSubtotalOf(viewRow)), "unitYuan") }}</span>
            </el-form-item>
          </el-col>
          <el-col v-for="field in subsidyExtraFields" :key="'vse-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)">
              <span>{{ formatWithUnit(formatDecimal(viewRow[field.prop]), field.unitKey) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formSubsidyTotal')">
              <span>{{ formatWithUnit(formatDecimal(subsidyTotalOf(viewRow)), "unitYuan") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="dmT('formRemark')">
              <span class="fh-view-text">{{ viewRow.remark || dash }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-hasPermi="['dataModel:farmerHousehold:edit']" type="primary" @click="handleEditFromView">{{ dmCommon("edit") }}</el-button>
        <el-button @click="viewOpen = false">{{ dmCommon("close") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dmT('importTitle')" :visible.sync="importOpen" width="480px" append-to-body @close="resetImport">
      <el-form ref="importFormRef" :model="importForm" label-width="100px" size="small">
        <el-form-item prop="statYear" :rules="importRules.statYear">
          <template slot="label">{{ dmT("importStatYear") }}</template>
          <el-select v-model="importForm.statYear" :placeholder="dmT('importStatYearPh')" style="width: 100%">
            <el-option v-for="y in yearOptions" :key="'iy-' + y" :label="String(y)" :value="y" />
          </el-select>
        </el-form-item>
        <el-form-item prop="statMonth" :rules="importRules.statMonth">
          <template slot="label">{{ dmT("importStatMonth") }}</template>
          <el-select v-model="importForm.statMonth" :placeholder="dmT('importStatMonthPh')" style="width: 100%">
            <el-option v-for="m in monthOptions" :key="'im-' + m" :label="formatStatMonth(m)" :value="m" />
          </el-select>
        </el-form-item>
        <p class="fh-import-tip">{{ dmT("importTip") }}</p>
        <el-upload ref="importUpload" drag :limit="1" accept=".xlsx,.xls" :auto-upload="false" action="#">
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">
            <el-link type="primary" :underline="false" @click="handleDownloadTemplate">{{ dmT("btnDownloadTemplate") }}</el-link>
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="importing" @click="handleImportSubmit">{{ dmCommon("ok") }}</el-button>
        <el-button @click="importOpen = false">{{ dmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dmT('exportTitle')" :visible.sync="exportOpen" width="480px" append-to-body @close="resetExport">
      <el-form ref="exportFormRef" :model="exportForm" label-width="100px" size="small">
        <el-form-item prop="statYear" :rules="exportRules.statYear">
          <template slot="label">{{ dmT("exportStatYear") }}</template>
          <el-select v-model="exportForm.statYear" :placeholder="dmT('exportStatYearPh')" style="width: 100%">
            <el-option v-for="y in yearOptions" :key="'ey-' + y" :label="String(y)" :value="y" />
          </el-select>
        </el-form-item>
        <el-form-item prop="statMonth" :rules="exportRules.statMonth">
          <template slot="label">{{ dmT("exportStatMonth") }}</template>
          <el-select v-model="exportForm.statMonth" :placeholder="dmT('exportStatMonthPh')" style="width: 100%">
            <el-option v-for="m in monthOptions" :key="'em-' + m" :label="formatStatMonth(m)" :value="m" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <template slot="label">{{ dmT("exportTown") }}</template>
          <el-select
            v-model="exportForm.townDeptId"
            :placeholder="dmT('exportTownPh')"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option v-for="item in townOptions" :key="'et-' + item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="exporting" @click="handleExportSubmit">{{ dmCommon("ok") }}</el-button>
        <el-button @click="exportOpen = false">{{ dmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataModelLocaleMixin from "@/mixins/dataModelLocaleMixin"
import {
  listFarmerHousehold,
  getFarmerHousehold,
  addFarmerHousehold,
  updateFarmerHousehold,
  delFarmerHousehold,
  listFarmerHouseholdYearOptions,
  listFarmerHouseholdMonthOptions,
  listFarmerHouseholdTownOptions,
  listFarmerHouseholdVillageTree,
  importFarmerHousehold,
  downloadFarmerHouseholdTemplate,
  exportFarmerHousehold
} from "@/api/dataModel/farmerHousehold"
import { blobValidate } from "@/utils/ruoyi"
import { saveAs } from "file-saver"

const YES_NO_OPTIONS = ["是", "否"]

const PASTURE_AREA_FIELDS = [
  { prop: "grazingBanArea", labelKey: "formGrazingBanArea", unitKey: "unitMu" },
  { prop: "grassBalanceArea", labelKey: "formGrassBalanceArea", unitKey: "unitMu" }
]

const CARRYING_FIELDS = [
  { prop: "approvedCarryingCapacity", labelKey: "formApprovedCarryingCapacity", unitKey: "unitSheepUnit" },
  { prop: "yearEndStockSheepUnit", labelKey: "formYearEndStockSheepUnit", unitKey: "unitSheepUnit" }
]

const YES_NO_FIELDS = [
  { prop: "isPureHerder", labelKey: "formIsPureHerder" },
  { prop: "isNoLivestock", labelKey: "formIsNoLivestock" },
  { prop: "isExtinctHousehold", labelKey: "formIsExtinctHousehold" },
  { prop: "isOverloadHerder", labelKey: "formIsOverloadHerder" },
  { prop: "needCap", labelKey: "formNeedCap" },
  { prop: "needFloor", labelKey: "formNeedFloor" }
]

const SUBSIDY_REWARD_FIELDS = [
  { prop: "grazingBanSubsidy", labelKey: "formGrazingBanSubsidy", unitKey: "unitYuan" },
  { prop: "grassBalanceReward", labelKey: "formGrassBalanceReward", unitKey: "unitYuan" }
]

const SUBSIDY_EXTRA_FIELDS = [
  { prop: "afterCapFloorSubsidy", labelKey: "formAfterCapFloorSubsidy", unitKey: "unitYuan" },
  { prop: "villageSupervisorSubsidy", labelKey: "formVillageSupervisorSubsidy", unitKey: "unitYuan" }
]

const COUNT_PROPS = ["householdCount", "populationCount"]
const DECIMAL_PROPS = [
  ...PASTURE_AREA_FIELDS.map((f) => f.prop),
  ...CARRYING_FIELDS.map((f) => f.prop),
  ...SUBSIDY_REWARD_FIELDS.map((f) => f.prop),
  ...SUBSIDY_EXTRA_FIELDS.map((f) => f.prop)
]
const YES_NO_PROPS = YES_NO_FIELDS.map((f) => f.prop)

function safeNum(val) {
  const n = Number(val)
  return Number.isFinite(n) ? n : 0
}

function getCurrentYearMonth() {
  const now = new Date()
  return { statYear: now.getFullYear(), statMonth: now.getMonth() + 1 }
}

function createEmptyForm() {
  const form = {
    id: undefined,
    statYear: undefined,
    statMonth: undefined,
    villageDeptId: undefined,
    remark: undefined
  }
  COUNT_PROPS.forEach((p) => {
    form[p] = undefined
  })
  DECIMAL_PROPS.forEach((p) => {
    form[p] = undefined
  })
  YES_NO_PROPS.forEach((p) => {
    form[p] = undefined
  })
  return form
}

function normalizeForm(data) {
  const row = Object.assign(createEmptyForm(), data || {})
  COUNT_PROPS.concat(DECIMAL_PROPS).forEach((prop) => {
    const val = row[prop]
    row[prop] = val == null || val === "" ? undefined : Number(val)
  })
  YES_NO_PROPS.forEach((prop) => {
    if (row[prop] === "") {
      row[prop] = undefined
    }
  })
  return row
}

function flattenVillageOptions(tree) {
  const list = []
  ;(tree || []).forEach((county) => {
    ;(county.children || []).forEach((town) => {
      ;(town.children || []).forEach((village) => {
        if (village == null || village.id == null) {
          return
        }
        const townName = town.label || ""
        const villageName = village.label || ""
        list.push({
          deptId: village.id,
          label: townName ? `${townName} / ${villageName}` : villageName
        })
      })
    })
  })
  return list
}

export default {
  name: "FarmerHousehold",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "farmerHousehold",
      loading: false,
      importing: false,
      exporting: false,
      open: false,
      viewOpen: false,
      importOpen: false,
      exportOpen: false,
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      yearOptions: [],
      monthOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      townOptions: [],
      villageOptions: [],
      yesNoOptions: YES_NO_OPTIONS,
      pastureAreaFields: PASTURE_AREA_FIELDS,
      carryingFields: CARRYING_FIELDS,
      yesNoFields: YES_NO_FIELDS,
      subsidyRewardFields: SUBSIDY_REWARD_FIELDS,
      subsidyExtraFields: SUBSIDY_EXTRA_FIELDS,
      viewRow: {},
      importForm: { statYear: undefined, statMonth: undefined },
      exportForm: { statYear: undefined, statMonth: undefined, townDeptId: undefined },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        statYear: undefined,
        statMonth: undefined,
        townDeptId: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    // 草场承包总面积 = 禁牧面积 + 草畜平衡面积
    pastureContractAreaDisplay() {
      return Number((safeNum(this.form.grazingBanArea) + safeNum(this.form.grassBalanceArea)).toFixed(4))
    },
    // 补助奖励总资金 = 禁牧补助 + 草畜平衡奖励
    subsidyRewardSubtotalDisplay() {
      return Number((safeNum(this.form.grazingBanSubsidy) + safeNum(this.form.grassBalanceReward)).toFixed(4))
    },
    // 补助合计金额 = 封顶保底后享受补助奖励总资金 + 村级草原监督员补助
    subsidyTotalDisplay() {
      return Number((safeNum(this.form.afterCapFloorSubsidy) + safeNum(this.form.villageSupervisorSubsidy)).toFixed(4))
    },
    formRules() {
      return {
        statYear: [{ required: true, message: this.dmT("ruleStatYearRequired"), trigger: "change" }],
        statMonth: [
          { required: true, message: this.dmT("ruleStatMonthRequired"), trigger: "change" },
          { validator: this.validateFormStatMonth, trigger: "change" }
        ],
        villageDeptId: [{ required: true, message: this.dmT("ruleVillageRequired"), trigger: "change" }],
        count: [{ validator: this.validateOptionalCount, trigger: "change" }],
        decimal: [{ validator: this.validateOptionalDecimal, trigger: "change" }],
        remark: [{ max: 500, message: this.dmCommon("ruleLen500"), trigger: "blur" }]
      }
    },
    importRules() {
      return {
        statYear: [{ required: true, message: this.dmT("ruleStatYearRequired"), trigger: "change" }],
        statMonth: [
          { required: true, message: this.dmT("ruleStatMonthRequired"), trigger: "change" },
          { validator: this.validateImportStatMonth, trigger: "change" }
        ]
      }
    },
    exportRules() {
      return {
        statYear: [{ required: true, message: this.dmT("exportStatYearRequired"), trigger: "change" }],
        statMonth: [
          { required: true, message: this.dmT("exportStatMonthRequired"), trigger: "change" },
          { validator: this.validateExportStatMonth, trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.loadOptions()
    this.getList()
  },
  methods: {
    loadOptions() {
      listFarmerHouseholdYearOptions().then((res) => {
        this.yearOptions = Array.isArray(res.data) ? res.data : []
      })
      listFarmerHouseholdMonthOptions().then((res) => {
        if (Array.isArray(res.data) && res.data.length) {
          this.monthOptions = res.data
        }
      })
      listFarmerHouseholdTownOptions().then((res) => {
        this.townOptions = Array.isArray(res.data) ? res.data : []
      })
      this.loadVillageTree()
    },
    loadVillageTree() {
      return listFarmerHouseholdVillageTree()
        .then((res) => {
          const raw = res && res.data !== undefined ? res.data : res
          this.villageOptions = flattenVillageOptions(Array.isArray(raw) ? raw : [])
          if (!this.villageOptions.length) {
            this.$modal.msgWarning(this.dmT("villageTreeEmpty"))
          }
        })
        .catch(() => {
          this.villageOptions = []
        })
    },
    formatStatMonth(month) {
      if (month == null || month === "") {
        return this.dash
      }
      return this.dmT("statMonthLabel", { month })
    },
    formatCount(val) {
      return val == null || val === "" ? this.dash : val
    },
    formatDecimal(val) {
      return val == null || val === "" ? this.dash : val
    },
    pastureContractAreaOf(row) {
      if (!row) {
        return undefined
      }
      if (row.pastureContractArea != null && row.pastureContractArea !== "") {
        return row.pastureContractArea
      }
      if (row.grazingBanArea == null && row.grassBalanceArea == null) {
        return undefined
      }
      return Number((safeNum(row.grazingBanArea) + safeNum(row.grassBalanceArea)).toFixed(4))
    },
    subsidyRewardSubtotalOf(row) {
      if (!row) {
        return undefined
      }
      if (row.subsidyRewardSubtotal != null && row.subsidyRewardSubtotal !== "") {
        return row.subsidyRewardSubtotal
      }
      if (row.grazingBanSubsidy == null && row.grassBalanceReward == null) {
        return undefined
      }
      return Number((safeNum(row.grazingBanSubsidy) + safeNum(row.grassBalanceReward)).toFixed(4))
    },
    subsidyTotalOf(row) {
      if (!row) {
        return undefined
      }
      // 前端展示公式：封顶保底后 + 村级监督员（与本次需求一致）
      if (row.afterCapFloorSubsidy == null && row.villageSupervisorSubsidy == null) {
        if (row.subsidyTotal != null && row.subsidyTotal !== "") {
          return row.subsidyTotal
        }
        return undefined
      }
      return Number((safeNum(row.afterCapFloorSubsidy) + safeNum(row.villageSupervisorSubsidy)).toFixed(4))
    },
    isFutureStatPeriod(statYear, statMonth) {
      if (statYear == null || statMonth == null) {
        return false
      }
      const now = new Date()
      const y = now.getFullYear()
      const m = now.getMonth() + 1
      return statYear > y || (statYear === y && statMonth > m)
    },
    validateFormStatMonth(rule, value, callback) {
      if (this.isFutureStatPeriod(this.form.statYear, value)) {
        callback(new Error(this.dmT("ruleStatMonthFuture")))
        return
      }
      callback()
    },
    validateImportStatMonth(rule, value, callback) {
      if (this.isFutureStatPeriod(this.importForm.statYear, value)) {
        callback(new Error(this.dmT("ruleStatMonthFuture")))
        return
      }
      callback()
    },
    validateExportStatMonth(rule, value, callback) {
      if (this.isFutureStatPeriod(this.exportForm.statYear, value)) {
        callback(new Error(this.dmT("ruleStatMonthFuture")))
        return
      }
      callback()
    },
    validateOptionalCount(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      if (typeof value !== "number" || Number.isNaN(value) || value < 0 || !Number.isInteger(value)) {
        callback(new Error(this.dmT("ruleCountNonNegative")))
        return
      }
      callback()
    },
    validateOptionalDecimal(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
        callback(new Error(this.dmT("ruleDecimalNonNegative")))
        return
      }
      callback()
    },
    buildListQuery() {
      const q = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      if (this.queryParams.statYear != null) {
        q.statYear = this.queryParams.statYear
      }
      if (this.queryParams.statMonth != null) {
        q.statMonth = this.queryParams.statMonth
      }
      if (this.queryParams.townDeptId != null) {
        q.townDeptId = this.queryParams.townDeptId
      }
      return q
    },
    getList() {
      this.loading = true
      listFarmerHousehold(this.buildListQuery())
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        statYear: undefined,
        statMonth: undefined,
        townDeptId: undefined
      }
      this.getList()
    },
    handleAdd() {
      this.dialogEdit = false
      this.formKey += 1
      this.form = createEmptyForm()
      const ym = getCurrentYearMonth()
      this.form.statYear = ym.statYear
      this.form.statMonth = ym.statMonth
      this.open = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      getFarmerHousehold(row.id).then((res) => {
        this.dialogEdit = true
        this.formKey += 1
        this.form = normalizeForm(res.data)
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getFarmerHousehold(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleEditFromView() {
      if (!this.viewRow || this.viewRow.id == null) {
        return
      }
      this.handleEdit(this.viewRow)
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dmT("confirmDelete"))
        .then(() => delFarmerHousehold(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    buildSubmitPayload() {
      const payload = {
        id: this.form.id,
        statYear: this.form.statYear,
        statMonth: this.form.statMonth,
        villageDeptId: this.form.villageDeptId,
        remark: this.form.remark
      }
      COUNT_PROPS.concat(DECIMAL_PROPS).forEach((prop) => {
        const val = this.form[prop]
        payload[prop] = val == null || val === "" ? null : val
      })
      YES_NO_PROPS.forEach((prop) => {
        payload[prop] = this.form[prop] || null
      })
      return payload
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildSubmitPayload()
        if (this.dialogEdit) {
          updateFarmerHousehold(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addFarmerHousehold(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.form = createEmptyForm()
    },
    handleImportOpen() {
      const ym = getCurrentYearMonth()
      this.importForm = {
        statYear: this.queryParams.statYear != null ? this.queryParams.statYear : ym.statYear,
        statMonth: this.queryParams.statMonth != null ? this.queryParams.statMonth : ym.statMonth
      }
      this.importOpen = true
      this.$nextTick(() => {
        if (this.$refs.importFormRef) {
          this.$refs.importFormRef.clearValidate()
        }
        if (this.$refs.importUpload) {
          this.$refs.importUpload.clearFiles()
        }
      })
    },
    resetImport() {
      this.importForm = { statYear: undefined, statMonth: undefined }
      if (this.$refs.importUpload) {
        this.$refs.importUpload.clearFiles()
      }
    },
    handleDownloadTemplate() {
      downloadFarmerHouseholdTemplate().then(async (data) => {
        const isBlob = blobValidate(data)
        if (isBlob) {
          saveAs(data, `farmer_household_import_template_${new Date().getTime()}.xlsx`)
        } else {
          this.$modal.msgError(this.dmT("exportFail"))
        }
      })
    },
    handleImportSubmit() {
      this.$refs.importFormRef.validate((valid) => {
        if (!valid) {
          return
        }
        const files = this.$refs.importUpload ? this.$refs.importUpload.uploadFiles : []
        if (!files || !files.length) {
          this.$modal.msgError(this.dmCommon("pleaseSelect"))
          return
        }
        const raw = files[0].raw
        this.importing = true
        this.$modal.loading(this.dmT("importLoading"))
        importFarmerHousehold(raw, this.importForm.statYear, this.importForm.statMonth)
          .then((res) => {
            const data = res.data || {}
            const msg = this.dmT("importSummary", {
              insert: data.insertCount != null ? data.insertCount : 0,
              update: data.updateCount != null ? data.updateCount : 0,
              fail: data.failCount != null ? data.failCount : 0
            })
            this.$modal.msgSuccess(msg)
            if (data.warnMessages && data.warnMessages.length) {
              this.$alert(data.warnMessages.join("<br/>"), this.dmT("importWarnTitle"), { dangerouslyUseHTMLString: true })
            }
            if (data.failMessages && data.failMessages.length) {
              this.$alert(data.failMessages.join("<br/>"), this.dmT("importFailTitle"), { dangerouslyUseHTMLString: true })
            }
            this.importOpen = false
            this.getList()
          })
          .finally(() => {
            this.importing = false
            this.$modal.closeLoading()
          })
      })
    },
    handleExportOpen() {
      const ym = getCurrentYearMonth()
      this.exportForm = {
        statYear: this.queryParams.statYear != null ? this.queryParams.statYear : ym.statYear,
        statMonth: this.queryParams.statMonth != null ? this.queryParams.statMonth : ym.statMonth,
        townDeptId: this.queryParams.townDeptId
      }
      this.exportOpen = true
      this.$nextTick(() => {
        if (this.$refs.exportFormRef) {
          this.$refs.exportFormRef.clearValidate()
        }
      })
    },
    resetExport() {
      this.exportForm = { statYear: undefined, statMonth: undefined, townDeptId: undefined }
    },
    handleExportSubmit() {
      this.$refs.exportFormRef.validate((valid) => {
        if (!valid) {
          return
        }
        this.exporting = true
        const filename = `${this.exportForm.statYear}年${this.exportForm.statMonth}月农牧户数据.xlsx`
        this.$modal.loading(this.dmT("exportLoading"))
        exportFarmerHousehold(this.exportForm.statYear, this.exportForm.statMonth, this.exportForm.townDeptId)
          .then(async (data) => {
            const isBlob = blobValidate(data)
            if (isBlob) {
              saveAs(data, filename)
              this.exportOpen = false
            } else {
              this.$modal.msgError(this.dmT("exportFail"))
            }
          })
          .finally(() => {
            this.exporting = false
            this.$modal.closeLoading()
          })
      })
    }
  }
}
</script>

<style scoped>
.fh-section-title {
  margin: 4px 0 12px;
  font-weight: 600;
  color: #303133;
}
.fh-form >>> .el-form-item__label {
  white-space: nowrap;
  line-height: 32px;
}
.fh-import-tip {
  margin: 0 0 12px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}
.fh-view-text {
  white-space: pre-wrap;
  word-break: break-all;
}
.dm-input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;
}
.dm-input-with-unit__input {
  flex: 1;
  width: 100%;
}
.dm-input-with-unit__suffix {
  margin-left: 8px;
  color: #909399;
  white-space: nowrap;
}
.dm-input-with-unit >>> .el-input-number {
  width: 100%;
}
</style>
