<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 prop="villageDeptId">
          <template slot="label">{{ dmT("queryVillage") }}</template>
          <el-select
            v-model="queryParams.villageDeptId"
            :placeholder="dmT('phVillageSearch')"
            clearable
            filterable
            style="width: 220px"
          >
            <el-option
              v-for="item in villageOptions"
              :key="'q-v-' + item.deptId"
              :label="item.label"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="enterpriseName">
          <template slot="label">{{ dmT("queryEnterpriseName") }}</template>
          <el-input
            v-model="queryParams.enterpriseName"
            :placeholder="dmT('phEnterpriseName')"
            clearable
            style="width: 180px"
            @keyup.enter.native="handleQuery"
          />
        </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:largeLivestockFarmer:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dmCommon("add") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:largeLivestockFarmer:import']"
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImportOpen"
          >{{ dmT("btnImport") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:largeLivestockFarmer: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="100" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colVillageName')" prop="villageName" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colEnterpriseName')" prop="enterpriseName" align="center" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colLegalRepresentative')" prop="legalRepresentative" align="center" min-width="90" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colEnterpriseType')" prop="enterpriseType" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colRegisteredCapital')" align="center" width="100">
          <template slot-scope="scope">{{ formatDecimal(scope.row.registeredCapital) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colEstablishDate')" prop="establishDate" align="center" width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colCattleYearEndStock')" align="center" width="90">
          <template slot-scope="scope">{{ formatCount(scope.row.cattleYearEndStock) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colCattleOutbound')" align="center" width="90">
          <template slot-scope="scope">{{ formatCount(scope.row.cattleOutbound) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colGrasslandArea')" align="center" width="100">
          <template slot-scope="scope">{{ formatDecimal(scope.row.grasslandAreaSubtotal) }}</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:largeLivestockFarmer:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:largeLivestockFarmer:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:largeLivestockFarmer: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="llf-form" label-width="220px" size="small">
        <div class="llf-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-row>

        <div class="llf-section-title">{{ dmT("sectionFarmerInfo") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="enterpriseName" :rules="formRules.enterpriseName">
              <template slot="label">{{ dmT("formEnterpriseName") }}</template>
              <el-input v-model="form.enterpriseName" :placeholder="dmT('phEnterpriseName')" maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="legalRepresentative" :rules="formRules.legalRepresentative">
              <template slot="label">{{ dmT("formLegalRepresentative") }}</template>
              <el-input v-model="form.legalRepresentative" maxlength="64" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="enterpriseType">
              <template slot="label">{{ dmT("formEnterpriseType") }}</template>
              <el-select v-model="form.enterpriseType" :placeholder="dmCommon('pleaseSelect')" style="width: 100%">
                <el-option v-for="item in enterpriseTypeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="registeredCapital" :rules="formRules.decimal">
              <template slot="label">{{ dmT("formRegisteredCapital") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number
                  v-model="form.registeredCapital"
                  :min="0"
                  :precision="4"
                  controls-position="right"
                  class="dm-input-with-unit__input"
                />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="establishDate">
              <template slot="label">{{ dmT("formEstablishDate") }}</template>
              <el-date-picker
                v-model="form.establishDate"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="dmCommon('pleaseSelect')"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="livestockLaborCount" :rules="formRules.count">
              <template slot="label">{{ dmT("formLivestockLaborCount") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number
                  v-model="form.livestockLaborCount"
                  :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="llf-section-title">{{ dmT("sectionStock") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in stockInventoryFields" :key="field.prop" :span="12">
            <el-form-item :prop="field.prop" :rules="formRules.count">
              <template slot="label">{{ dmT(field.labelKey) }}</template>
              <div class="dm-input-with-unit">
                <el-input-number
                  v-model="form[field.prop]"
                  :min="0"
                  :precision="0"
                  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("formStockSubtotal") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number :value="stockSubtotalDisplay" :controls="false" disabled class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitHeadSheepHorse") }}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionOutbound") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in stockOutboundFields" :key="field.prop" :span="12">
            <el-form-item :prop="field.prop" :rules="formRules.count">
              <template slot="label">{{ dmT(field.labelKey) }}</template>
              <div class="dm-input-with-unit">
                <el-input-number
                  v-model="form[field.prop]"
                  :min="0"
                  :precision="0"
                  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("formOutboundSubtotal") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number :value="outboundSubtotalDisplay" :controls="false" disabled class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitHeadSheepHorse") }}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionGrassland") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in grasslandDecimalFields" :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("formGrasslandAreaSubtotal") }}</template>
              <div class="dm-input-with-unit">
                <el-input :value="grasslandAreaSubtotalDisplay" 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 :span="12">
            <el-form-item>
              <template slot="label">{{ dmT("formIsGrassBalanced") }}</template>
              <el-input :value="isGrassBalancedDisplay" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionFinance") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="income" :rules="formRules.decimal">
              <template slot="label">{{ dmT("formIncome") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.income" :min="0" :precision="4" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="expense" :rules="formRules.decimal">
              <template slot="label">{{ dmT("formExpense") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.expense" :min="0" :precision="4" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <template slot="label">{{ dmT("formProfit") }}</template>
              <div class="dm-input-with-unit">
                <el-input :value="profitDisplay" disabled class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionSubsidy") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="hasSubsidy">
              <template slot="label">{{ dmT("formHasSubsidy") }}</template>
              <el-radio-group v-model="form.hasSubsidy">
                <el-radio v-for="item in yesNoOptions" :key="'hs-' + item" :label="item">{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="subsidyYear">
              <template slot="label">{{ dmT("formSubsidyYear") }}</template>
              <el-date-picker
                v-model="form.subsidyYear"
                type="year"
                value-format="yyyy"
                :placeholder="dmCommon('pleaseSelect')"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="subsidyAmount" :rules="formRules.decimal">
              <template slot="label">{{ dmT("formSubsidyAmount") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.subsidyAmount" :min="0" :precision="4" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionOther") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="hasTrademark">
              <template slot="label">{{ dmT("formHasTrademark") }}</template>
              <el-radio-group v-model="form.hasTrademark">
                <el-radio v-for="item in yesNoOptions" :key="'ht-' + item" :label="item">{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="hasQualityCert">
              <template slot="label">{{ dmT("formHasQualityCert") }}</template>
              <el-radio-group v-model="form.hasQualityCert">
                <el-radio v-for="item in yesNoOptions" :key="'hq-' + item" :label="item">{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="salesChannel">
              <template slot="label">{{ dmT("formSalesChannel") }}</template>
              <el-select v-model="form.salesChannel" :placeholder="dmCommon('pleaseSelect')" style="width: 100%">
                <el-option v-for="item in salesChannelOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="drivenPopulation" :rules="formRules.count">
              <template slot="label">{{ dmT("formDrivenPopulation") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.drivenPopulation" :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-col :span="12">
            <el-form-item prop="wagePaid" :rules="formRules.decimal">
              <template slot="label">{{ dmT("formWagePaid") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.wagePaid" :min="0" :precision="4" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</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 llf-form" label-width="220px" size="small">
        <div class="llf-section-title">{{ dmT("sectionBasic") }}</div>
        <el-row :gutter="8">
          <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-row>

        <div class="llf-section-title">{{ dmT("sectionFarmerInfo") }}</div>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item :label="dmT('formEnterpriseName')"><span>{{ viewRow.enterpriseName || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formLegalRepresentative')"><span>{{ viewRow.legalRepresentative || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formEnterpriseType')"><span>{{ viewRow.enterpriseType || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formRegisteredCapital')">
              <span>{{ formatWithUnit(formatDecimal(viewRow.registeredCapital), "unitWanYuan") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formEstablishDate')"><span>{{ viewRow.establishDate || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formLivestockLaborCount')">
              <span>{{ formatWithUnit(formatCount(viewRow.livestockLaborCount), "unitPerson") }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionStock") }}</div>
        <el-row :gutter="8">
          <el-col v-for="field in stockInventoryFields" :key="'vs-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)">
              <span>{{ formatWithUnit(formatCount(viewRow[field.prop]), field.unitKey) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formStockSubtotal')">
              <span>{{ formatWithUnit(formatCount(stockSubtotalOf(viewRow)), "unitHeadSheepHorse") }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionOutbound") }}</div>
        <el-row :gutter="8">
          <el-col v-for="field in stockOutboundFields" :key="'vo-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)">
              <span>{{ formatWithUnit(formatCount(viewRow[field.prop]), field.unitKey) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formOutboundSubtotal')">
              <span>{{ formatWithUnit(formatCount(outboundSubtotalOf(viewRow)), "unitHeadSheepHorse") }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionGrassland") }}</div>
        <el-row :gutter="8">
          <el-col v-for="field in grasslandDecimalFields" :key="'vg-' + 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('formGrasslandAreaSubtotal')">
              <span>{{ formatWithUnit(formatDecimal(grasslandAreaSubtotalOf(viewRow)), "unitMu") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formIsGrassBalanced')"><span>{{ viewRow.isGrassBalanced || dash }}</span></el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionFinance") }}</div>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item :label="dmT('formIncome')">
              <span>{{ formatWithUnit(formatDecimal(viewRow.income), "unitWanYuan") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formExpense')">
              <span>{{ formatWithUnit(formatDecimal(viewRow.expense), "unitWanYuan") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formProfit')">
              <span>{{ formatWithUnit(formatDecimal(viewRow.profit), "unitWanYuan") }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionSubsidy") }}</div>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item :label="dmT('formHasSubsidy')"><span>{{ viewRow.hasSubsidy || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formSubsidyYear')"><span>{{ viewRow.subsidyYear || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formSubsidyAmount')">
              <span>{{ formatWithUnit(formatDecimal(viewRow.subsidyAmount), "unitWanYuan") }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="llf-section-title">{{ dmT("sectionOther") }}</div>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item :label="dmT('formHasTrademark')"><span>{{ viewRow.hasTrademark || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formHasQualityCert')"><span>{{ viewRow.hasQualityCert || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formSalesChannel')"><span>{{ viewRow.salesChannel || dash }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formDrivenPopulation')">
              <span>{{ formatWithUnit(formatCount(viewRow.drivenPopulation), "unitPerson") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formWagePaid')">
              <span>{{ formatWithUnit(formatDecimal(viewRow.wagePaid), "unitWanYuan") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="dmT('formRemark')">
              <span class="llf-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:largeLivestockFarmer: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="llf-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("queryTown") }}</template>
          <el-select
            v-model="exportForm.townDeptId"
            :placeholder="dmCommon('pleaseSelect')"
            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 {
  listLargeLivestockFarmer,
  getLargeLivestockFarmer,
  addLargeLivestockFarmer,
  updateLargeLivestockFarmer,
  delLargeLivestockFarmer,
  listLargeLivestockFarmerYearOptions,
  listLargeLivestockFarmerMonthOptions,
  listLargeLivestockFarmerTownOptions,
  listLargeLivestockFarmerVillageTree,
  importLargeLivestockFarmer,
  downloadLargeLivestockFarmerTemplate,
  exportLargeLivestockFarmer
} from "@/api/dataModel/largeLivestockFarmer"
import { blobValidate } from "@/utils/ruoyi"
import { saveAs } from "file-saver"

const ENTERPRISE_TYPE_OPTIONS = ["个体工商户", "个人独资企业", "有限责任公司", "合伙企业", "其他"]
const SALES_CHANNEL_OPTIONS = ["其他", "线上销售", "线下集市", "企事业单位", "商超门店"]
const YES_NO_OPTIONS = ["是", "否"]
const DEFAULT_ENTERPRISE_TYPE = "个体工商户"
const DEFAULT_SALES_CHANNEL = "其他"

const STOCK_INVENTORY_FIELDS = [
  { prop: "cattleYearEndStock", labelKey: "formCattleYearEndStock", unitKey: "unitHead" },
  { prop: "cattleBreedingFemaleStock", labelKey: "formCattleBreedingFemaleStock", unitKey: "unitHead" },
  { prop: "sheepYearEndStock", labelKey: "formSheepYearEndStock", unitKey: "unitHead" },
  { prop: "sheepBreedingFemaleStock", labelKey: "formSheepBreedingFemaleStock", unitKey: "unitHead" }
]

const STOCK_OUTBOUND_FIELDS = [
  { prop: "cattleOutbound", labelKey: "formCattleOutbound", unitKey: "unitHead" },
  { prop: "sheepOutbound", labelKey: "formSheepOutbound", unitKey: "unitHead" }
]

const GRASSLAND_DECIMAL_FIELDS = [
  { prop: "grassBalanceArea", labelKey: "formGrassBalanceArea", unitKey: "unitMu" },
  { prop: "transferGrassArea", labelKey: "formTransferGrassArea", unitKey: "unitMu" },
  { prop: "approvedCarryingCapacity", labelKey: "formApprovedCarryingCapacity", unitKey: "unitHead" },
  { prop: "yearEndStockSheepUnit", labelKey: "formYearEndStockSheepUnit", unitKey: "unitHead" }
]

const COUNT_PROPS = [
  "livestockLaborCount",
  ...STOCK_INVENTORY_FIELDS.map((f) => f.prop),
  ...STOCK_OUTBOUND_FIELDS.map((f) => f.prop),
  "drivenPopulation"
]

const DECIMAL_PROPS = [
  "registeredCapital",
  ...GRASSLAND_DECIMAL_FIELDS.map((f) => f.prop),
  "income",
  "expense",
  "subsidyAmount",
  "wagePaid"
]

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,
    enterpriseName: undefined,
    legalRepresentative: undefined,
    enterpriseType: undefined,
    establishDate: undefined,
    subsidyYear: undefined,
    hasSubsidy: undefined,
    hasTrademark: undefined,
    hasQualityCert: undefined,
    salesChannel: undefined,
    remark: undefined
  }
  COUNT_PROPS.forEach((p) => {
    form[p] = undefined
  })
  DECIMAL_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)
  })
  // 年份选择器 value-format=yyyy，表单内用字符串
  if (row.subsidyYear == null || row.subsidyYear === "") {
    row.subsidyYear = undefined
  } else {
    row.subsidyYear = String(row.subsidyYear)
  }
  ;["hasSubsidy", "hasTrademark", "hasQualityCert"].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
}

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

export default {
  name: "LargeLivestockFarmer",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "largeLivestockFarmer",
      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: [],
      enterpriseTypeOptions: ENTERPRISE_TYPE_OPTIONS,
      salesChannelOptions: SALES_CHANNEL_OPTIONS,
      yesNoOptions: YES_NO_OPTIONS,
      stockInventoryFields: STOCK_INVENTORY_FIELDS,
      stockOutboundFields: STOCK_OUTBOUND_FIELDS,
      grasslandDecimalFields: GRASSLAND_DECIMAL_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,
        villageDeptId: undefined,
        enterpriseName: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    stockSubtotalDisplay() {
      return safeNum(this.form.cattleYearEndStock) + safeNum(this.form.sheepYearEndStock)
    },
    outboundSubtotalDisplay() {
      return safeNum(this.form.cattleOutbound) + safeNum(this.form.sheepOutbound)
    },
    grasslandAreaSubtotalDisplay() {
      const n = safeNum(this.form.grassBalanceArea) + safeNum(this.form.transferGrassArea)
      return Number(n.toFixed(4))
    },
    profitDisplay() {
      if (this.form.income == null || this.form.expense == null) {
        return this.dash
      }
      return Number((safeNum(this.form.income) - safeNum(this.form.expense)).toFixed(4))
    },
    isGrassBalancedDisplay() {
      if (this.form.approvedCarryingCapacity == null || this.form.yearEndStockSheepUnit == null) {
        return this.dash
      }
      return safeNum(this.form.approvedCarryingCapacity) >= safeNum(this.form.yearEndStockSheepUnit) ? "是" : "否"
    },
    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" }],
        enterpriseName: [
          { required: true, message: this.dmT("ruleEnterpriseNameRequired"), trigger: "blur" },
          { max: 200, message: this.dmT("ruleEnterpriseNameLen"), trigger: "blur" }
        ],
        legalRepresentative: [{ max: 64, message: this.dmT("ruleLegalRepLen"), trigger: "blur" }],
        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() {
      listLargeLivestockFarmerYearOptions().then((res) => {
        this.yearOptions = Array.isArray(res.data) ? res.data : []
      })
      listLargeLivestockFarmerMonthOptions().then((res) => {
        if (Array.isArray(res.data) && res.data.length) {
          this.monthOptions = res.data
        }
      })
      listLargeLivestockFarmerTownOptions().then((res) => {
        this.townOptions = Array.isArray(res.data) ? res.data : []
      })
      this.loadVillageTree()
    },
    loadVillageTree() {
      return listLargeLivestockFarmerVillageTree()
        .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
    },
    formatViewField(row, field) {
      let val
      if (field.type === "count") {
        val = this.formatCount(row[field.prop])
      } else if (field.type === "decimal") {
        val = this.formatDecimal(row[field.prop])
      } else {
        val = row[field.prop] || this.dash
      }
      return this.formatWithUnit(val, field.unitKey)
    },
    stockSubtotalOf(row) {
      if (!row) {
        return 0
      }
      if (row.stockSubtotal != null && row.stockSubtotal !== "") {
        return row.stockSubtotal
      }
      return safeNum(row.cattleYearEndStock) + safeNum(row.sheepYearEndStock)
    },
    outboundSubtotalOf(row) {
      if (!row) {
        return 0
      }
      if (row.outboundSubtotal != null && row.outboundSubtotal !== "") {
        return row.outboundSubtotal
      }
      return safeNum(row.cattleOutbound) + safeNum(row.sheepOutbound)
    },
    grasslandAreaSubtotalOf(row) {
      if (!row) {
        return undefined
      }
      if (row.grasslandAreaSubtotal != null && row.grasslandAreaSubtotal !== "") {
        return row.grasslandAreaSubtotal
      }
      if (row.grassBalanceArea == null && row.transferGrassArea == null) {
        return undefined
      }
      return Number((safeNum(row.grassBalanceArea) + safeNum(row.transferGrassArea)).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 (!Number.isInteger(value) || value < 0) {
        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
      }
      if (this.queryParams.villageDeptId != null) {
        q.villageDeptId = this.queryParams.villageDeptId
      }
      const name = this.queryParams.enterpriseName != null ? String(this.queryParams.enterpriseName).trim() : ""
      if (name) {
        q.enterpriseName = name
      }
      return q
    },
    buildPayload() {
      const remarkText = this.form.remark != null ? String(this.form.remark).trim() : ""
      const enterpriseName = this.form.enterpriseName != null ? String(this.form.enterpriseName).trim() : ""
      const legalRep = this.form.legalRepresentative != null ? String(this.form.legalRepresentative).trim() : ""
      let subsidyYear
      if (this.form.subsidyYear != null && this.form.subsidyYear !== "") {
        const y = Number(this.form.subsidyYear)
        subsidyYear = Number.isFinite(y) ? y : undefined
      }
      const payload = {
        statYear: this.form.statYear,
        statMonth: this.form.statMonth,
        villageDeptId: this.form.villageDeptId,
        enterpriseName,
        legalRepresentative: legalRep !== "" ? legalRep : undefined,
        enterpriseType: this.form.enterpriseType || undefined,
        establishDate: this.form.establishDate || undefined,
        subsidyYear,
        hasSubsidy: this.form.hasSubsidy || undefined,
        hasTrademark: this.form.hasTrademark || undefined,
        hasQualityCert: this.form.hasQualityCert || undefined,
        salesChannel: this.form.salesChannel || undefined,
        remark: remarkText !== "" ? remarkText : undefined
      }
      COUNT_PROPS.concat(DECIMAL_PROPS).forEach((prop) => {
        const val = this.form[prop]
        payload[prop] = val == null || val === "" ? undefined : val
      })
      return payload
    },
    getList() {
      this.loading = true
      listLargeLivestockFarmer(this.buildListQuery())
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total != null ? res.total : 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.statYear = undefined
      this.queryParams.statMonth = undefined
      this.queryParams.townDeptId = undefined
      this.queryParams.villageDeptId = undefined
      this.queryParams.enterpriseName = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      const openDialog = () => {
        this.formKey += 1
        const current = getCurrentYearMonth()
        this.form = createEmptyForm()
        this.form.statYear = current.statYear
        this.form.statMonth = current.statMonth
        this.form.enterpriseType = DEFAULT_ENTERPRISE_TYPE
        this.form.salesChannel = DEFAULT_SALES_CHANNEL
        this.dialogEdit = false
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      }
      if (!this.villageOptions.length) {
        this.loadVillageTree().finally(openDialog)
      } else {
        openDialog()
      }
    },
    handleEdit(row) {
      const openWithData = (data) => {
        this.formKey += 1
        this.dialogEdit = true
        this.form = normalizeForm(data)
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      }
      getLargeLivestockFarmer(row.id).then((res) => {
        const data = res.data || {}
        if (!this.villageOptions.length) {
          this.loadVillageTree().finally(() => openWithData(data))
        } else {
          openWithData(data)
        }
      })
    },
    handleEditFromView() {
      this.handleEdit(this.viewRow)
    },
    handleView(row) {
      getLargeLivestockFarmer(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dmT("confirmDelete"))
        .then(() => delLargeLivestockFarmer(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateLargeLivestockFarmer(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addLargeLivestockFarmer(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.form = createEmptyForm()
    },
    handleImportOpen() {
      const current = getCurrentYearMonth()
      this.importForm.statYear = current.statYear
      this.importForm.statMonth = current.statMonth
      this.importOpen = true
      this.$nextTick(() => this.resetImportFiles())
    },
    resetImportFiles() {
      if (this.$refs.importUpload) {
        this.$refs.importUpload.clearFiles()
      }
    },
    resetImport() {
      this.importing = false
      this.importForm.statYear = undefined
      this.importForm.statMonth = undefined
      this.resetImportFiles()
    },
    handleDownloadTemplate() {
      const filename = `large_livestock_farmer_template_${new Date().getTime()}.xlsx`
      this.$modal.loading("正在下载模板，请稍候")
      downloadLargeLivestockFarmerTemplate()
        .then(async (data) => {
          if (blobValidate(data)) {
            saveAs(new Blob([data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }), filename)
          } else {
            const resText = await data.text()
            const rspObj = JSON.parse(resText)
            this.$modal.msgError(rspObj.msg || "下载模板失败")
          }
        })
        .catch(() => this.$modal.msgError("下载模板失败"))
        .finally(() => this.$modal.closeLoading())
    },
    handleExportOpen() {
      const current = getCurrentYearMonth()
      this.exportForm.statYear = current.statYear
      this.exportForm.statMonth = current.statMonth
      this.exportForm.townDeptId = this.queryParams.townDeptId
      this.exportOpen = true
      this.$nextTick(() => {
        if (this.$refs.exportFormRef) {
          this.$refs.exportFormRef.clearValidate()
        }
      })
    },
    resetExport() {
      this.exporting = false
      this.exportForm.statYear = undefined
      this.exportForm.statMonth = undefined
      this.exportForm.townDeptId = undefined
    },
    handleExportSubmit() {
      this.$refs.exportFormRef.validate((valid) => {
        if (!valid) {
          return
        }
        const { statYear, statMonth } = this.exportForm
        if (!this.yearOptions.includes(statYear) || !this.monthOptions.includes(statMonth)) {
          this.$modal.msgError(this.dmT("exportStatYearInvalid"))
          return
        }
        const filename = `${statYear}年${statMonth}月养殖大户数据.xlsx`
        this.exporting = true
        this.$modal.loading(this.dmT("exportLoading"))
        exportLargeLivestockFarmer(statYear, statMonth, this.exportForm.townDeptId)
          .then(async (data) => {
            if (blobValidate(data)) {
              saveAs(new Blob([data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }), filename)
              this.exportOpen = false
            } else {
              const resText = await data.text()
              const rspObj = JSON.parse(resText)
              this.$modal.msgError(rspObj.msg || this.dmT("exportFail"))
            }
          })
          .catch(() => this.$modal.msgError(this.dmT("exportFail")))
          .finally(() => {
            this.exporting = false
            this.$modal.closeLoading()
          })
      })
    },
    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("请选择要上传的文件")
          return
        }
        const raw = files[0].raw
        const name = (raw.name || "").toLowerCase()
        if (!name.endsWith(".xlsx") && !name.endsWith(".xls")) {
          this.$modal.msgError('请选择后缀为 "xls" 或 "xlsx" 的文件')
          return
        }
        this.importing = true
        this.$modal.loading(this.dmT("importLoading"))
        importLargeLivestockFarmer(raw, this.importForm.statYear, this.importForm.statMonth)
          .then((res) => {
            this.importOpen = false
            this.showImportResult(res.data || {})
            this.getList()
          })
          .finally(() => {
            this.importing = false
            this.$modal.closeLoading()
            this.resetImportFiles()
          })
      })
    },
    showImportResult(data) {
      const insert = data.insertCount != null ? data.insertCount : 0
      const update = data.updateCount != null ? data.updateCount : 0
      const fail = data.failCount != null ? data.failCount : 0
      let html = this.dmT("importSummary", { insert, update, fail })
      if (data.warnMessages && data.warnMessages.length) {
        html += `<p><strong>${this.dmT("importWarnTitle")}</strong></p><p>${data.warnMessages.join("<br/>")}</p>`
      }
      if (data.failMessages && data.failMessages.length) {
        html += `<p><strong>${this.dmT("importFailTitle")}</strong></p><p>${data.failMessages.join("<br/>")}</p>`
      }
      this.$alert(
        `<div style='overflow:auto;overflow-x:hidden;max-height:70vh;padding:10px 20px 0;'>${html}</div>`,
        this.dmT("importTitle"),
        { dangerouslyUseHTMLString: true }
      )
    }
  }
}
</script>

<style scoped>
.llf-section-title {
  margin: 4px 0 12px;
  font-weight: 600;
  color: #303133;
}
.llf-form >>> .el-form-item__label {
  white-space: nowrap;
  line-height: 32px;
}
.llf-import-tip {
  margin: 0 0 12px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}
.llf-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>
