<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="cooperativeName">
          <template slot="label">{{ dmT("queryCooperativeName") }}</template>
          <el-input
            v-model="queryParams.cooperativeName"
            :placeholder="dmT('phCooperativeName')"
            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-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['dataModel:cooperativeDevelopment:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dmCommon("add") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['dataModel:cooperativeDevelopment:import']"
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImportOpen"
          >{{ dmT("btnImport") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['dataModel:cooperativeDevelopment:export']"
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExportOpen"
          >{{ dmCommon("export") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['dataModel:cooperativeDevelopment:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!ids.length"
            @click="handleDeleteBatch"
          >{{ dmT("btnBatchDelete") }}</el-button>
        </el-col>
      </el-row>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border @selection-change="handleSelectionChange">
        <template slot="empty">
          <span>{{ dmT("emptyList") }}</span>
        </template>
        <el-table-column type="selection" width="50" align="center" fixed="left" />
        <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('colVillageName')" prop="villageName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colTownName')" prop="townName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colCooperativeName')" prop="cooperativeName" align="center" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colLegalRepresentative')" prop="legalRepresentative" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colEstablishDate')" prop="establishDate" align="center" width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colRegisteredCapital')" align="center" width="110">
          <template slot-scope="scope">{{ formatDecimal(scope.row.registeredCapital) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colYearEndTotalAssets')" align="center" width="120">
          <template slot-scope="scope">{{ formatDecimal(scope.row.yearEndTotalAssets) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colTotalIncome')" align="center" width="100">
          <template slot-scope="scope">{{ formatDecimal(scope.row.totalIncome) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colLossAmount')" align="center" width="90">
          <template slot-scope="scope">{{ formatDecimal(scope.row.lossAmount) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colCattleInventoryCount')" align="center" width="90">
          <template slot-scope="scope">{{ formatCount(scope.row.cattleInventoryCount) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colCattleOutboundCount')" align="center" width="90">
          <template slot-scope="scope">{{ formatCount(scope.row.cattleOutboundCount) }}</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:cooperativeDevelopment:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:cooperativeDevelopment:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:cooperativeDevelopment: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" label-width="150px" size="small">
        <div class="cd-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="cd-section-title">{{ dmT("sectionCooperativeInfo") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="cooperativeName" :rules="formRules.cooperativeName">
              <template slot="label">{{ dmT("formCooperativeName") }}</template>
              <el-input v-model="form.cooperativeName" :placeholder="dmT('phCooperativeName')" 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="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 v-for="field in basicDecimalFields" :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="true"
                  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="cd-section-title">{{ dmT("sectionMemberShare") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in memberCountFields" :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="true"
                  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("formLivestockShareTotal") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number :value="livestockShareTotalDisplay" :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-col v-for="field in shareDecimalFields" :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="true"
                  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 prop="laborShareCount" :rules="formRules.count">
              <template slot="label">{{ dmT("formLaborShareCount") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number
                  v-model="form.laborShareCount"
                  :min="0"
                  :precision="0"
                  :controls="true"
                  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="cd-section-title">{{ dmT("sectionBenefit") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in benefitDecimalFields" :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="true"
                  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="cd-section-title">{{ dmT("sectionEmployment") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in employmentFields" :key="field.prop" :span="12">
            <el-form-item :prop="field.prop" :rules="field.type === 'decimal' ? formRules.decimal : 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="field.type === 'decimal' ? 4 : 0"
                  :controls="true"
                  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="cd-section-title">{{ dmT("sectionLivestockInout") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in livestockInoutFields" :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="true"
                  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="cd-section-title">{{ dmT("sectionProductCert") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in productCertFields" :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="true"
                  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="cd-section-title">{{ dmT("sectionTraining") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in trainingFields" :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="true"
                  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="cd-section-title">{{ dmT("sectionOperation") }}</div>
        <el-form-item>
          <template slot="label">{{ dmT("formBusinessScope") }}</template>
          <el-checkbox-group v-model="form.businessScopeList">
            <el-checkbox v-for="item in businessScopeOptions" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <template slot="label">{{ dmT("formBusinessModel") }}</template>
          <el-radio-group v-model="form.businessModel">
            <el-radio v-for="item in businessModelOptions" :key="item" :label="item">{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="cd-section-title">{{ dmT("sectionOperationStatus") }}</div>
        <el-form-item>
          <template slot="label">{{ dmT("formOperationStatus") }}</template>
          <el-radio-group v-model="form.operationStatus">
            <el-radio v-for="item in operationStatusOptions" :key="item" :label="item">{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <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-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" label-width="150px" size="small">
        <div class="cd-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-row>

        <div class="cd-section-title">{{ dmT("sectionCooperativeInfo") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item :label="dmT('formCooperativeName')">
              <span>{{ viewRow.cooperativeName || 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('formEstablishDate')">
              <span>{{ viewRow.establishDate || dash }}</span>
            </el-form-item>
          </el-col>
          <el-col v-for="field in basicDecimalFields" :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="cd-section-title">{{ dmT("sectionMemberShare") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in memberCountFields" :key="'vm-' + 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('formLivestockShareTotal')">
              <span>{{ formatWithUnit(formatCount(livestockShareTotalOf(viewRow)), "unitHeadSheepHorse") }}</span>
            </el-form-item>
          </el-col>
          <el-col v-for="field in shareDecimalFields" :key="'vsd-' + 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('formLaborShareCount')">
              <span>{{ formatWithUnit(formatCount(viewRow.laborShareCount), "unitPerson") }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="cd-section-title">{{ dmT("sectionBenefit") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in benefitDecimalFields" :key="'vb-' + 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="cd-section-title">{{ dmT("sectionEmployment") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in employmentFields" :key="'ve-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)">
              <span>{{ formatWithUnit(field.type === 'decimal' ? formatDecimal(viewRow[field.prop]) : formatCount(viewRow[field.prop]), field.unitKey) }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="cd-section-title">{{ dmT("sectionLivestockInout") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in livestockInoutFields" :key="'vl-' + 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-row>

        <div class="cd-section-title">{{ dmT("sectionProductCert") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in productCertFields" :key="'vp-' + 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-row>

        <div class="cd-section-title">{{ dmT("sectionTraining") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in trainingFields" :key="'vt-' + 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-row>

        <div class="cd-section-title">{{ dmT("sectionOperation") }}</div>
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item :label="dmT('formBusinessScope')">
              <span class="cd-view-text">{{ viewRow.businessScope || dash }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formBusinessModel')">
              <span>{{ viewRow.businessModel || dash }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="cd-section-title">{{ dmT("sectionOperationStatus") }}</div>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item :label="dmT('formOperationStatus')">
              <span>{{ viewRow.operationStatus || dash }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="dmT('formRemark')">
              <span class="cd-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:cooperativeDevelopment: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="cd-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 { buildDataModelYearOptions } from "@/utils/dataModelYearOptions"
import {
  listCooperativeDevelopment,
  getCooperativeDevelopment,
  addCooperativeDevelopment,
  updateCooperativeDevelopment,
  delCooperativeDevelopment,
  listCooperativeDevelopmentMonthOptions,
  listCooperativeDevelopmentTownOptions,
  listCooperativeDevelopmentVillageTree,
  importCooperativeDevelopment,
  downloadCooperativeDevelopmentTemplate,
  exportCooperativeDevelopment
} from "@/api/dataModel/cooperativeDevelopment"
import { blobValidate } from "@/utils/ruoyi"
import { saveAs } from "file-saver"

const BUSINESS_SCOPE_OPTIONS = [
  "养殖业", "种养结合", "农产品加工", "农机服务", "劳务输出",
  "建筑工程", "旅游服务", "运输", "特色产品制作及销售", "其他"
]
const BUSINESS_MODEL_OPTIONS = [
  "整村合作社", "股份合作社", "联合合作社", "多种经营合作社", "公司型合作社", "其它"
]
const OPERATION_STATUS_OPTIONS = ["规范", "一般", "差"]

const BASIC_DECIMAL_FIELDS = [
  { prop: "registeredCapital", labelKey: "formRegisteredCapital", unitKey: "unitWanYuan" },
  { prop: "yearEndTotalAssets", labelKey: "formYearEndTotalAssets", unitKey: "unitWanYuan" }
]

const MEMBER_COUNT_FIELDS = [
  { prop: "memberHouseholdCount", labelKey: "formMemberHouseholdCount", unitKey: "unitHousehold" },
  { prop: "memberPopulationCount", labelKey: "formMemberPopulationCount", unitKey: "unitPerson" },
  { prop: "povertyMonitorCount", labelKey: "formPovertyMonitorCount", unitKey: "unitPerson" },
  { prop: "cattleShareCount", labelKey: "formCattleShareCount", unitKey: "unitHead" },
  { prop: "sheepShareCount", labelKey: "formSheepShareCount", unitKey: "unitHead" }
]

const SHARE_DECIMAL_FIELDS = [
  { prop: "grasslandShareArea", labelKey: "formGrasslandShareArea", unitKey: "unitWanMu" },
  { prop: "cashShareAmount", labelKey: "formCashShareAmount", unitKey: "unitWanYuan" },
  { prop: "otherShareAmount", labelKey: "formOtherShareAmount", unitKey: "unitWanYuan" }
]

const BENEFIT_DECIMAL_FIELDS = [
  { prop: "totalIncome", labelKey: "formTotalIncome", unitKey: "unitWanYuan" },
  { prop: "netIncome", labelKey: "formNetIncome", unitKey: "unitWanYuan" },
  { prop: "cashDividend", labelKey: "formCashDividend", unitKey: "unitWanYuan" },
  { prop: "inKindDividend", labelKey: "formInKindDividend", unitKey: "unitWanYuan" },
  { prop: "revolvingFund", labelKey: "formRevolvingFund", unitKey: "unitWanYuan" },
  { prop: "lossAmount", labelKey: "formLossAmount", unitKey: "unitWanYuan" }
]

const EMPLOYMENT_FIELDS = [
  { prop: "collegeGraduateCount", labelKey: "formCollegeGraduateCount", unitKey: "unitPerson", type: "count" },
  { prop: "collegeGraduateWage", labelKey: "formCollegeGraduateWage", unitKey: "unitWanYuan", type: "decimal" },
  { prop: "farmerTransferEmploymentCount", labelKey: "formFarmerTransferEmploymentCount", unitKey: "unitPerson", type: "count" },
  { prop: "farmerTransferWage", labelKey: "formFarmerTransferWage", unitKey: "unitWanYuan", type: "decimal" }
]

const LIVESTOCK_INOUT_FIELDS = [
  { prop: "cattleInventoryCount", labelKey: "formCattleInventoryCount", unitKey: "unitHead", type: "count" },
  { prop: "cattleOutboundCount", labelKey: "formCattleOutboundCount", unitKey: "unitHead", type: "count" },
  { prop: "sheepInventoryCount", labelKey: "formSheepInventoryCount", unitKey: "unitHead", type: "count" },
  { prop: "sheepOutboundCount", labelKey: "formSheepOutboundCount", unitKey: "unitHead", type: "count" }
]

const PRODUCT_CERT_FIELDS = [
  { prop: "trademarkProductCount", labelKey: "formTrademarkProductCount", unitKey: "unitGe" },
  { prop: "qualityCertProductCount", labelKey: "formQualityCertProductCount", unitKey: "unitGe" }
]

const TRAINING_FIELDS = [
  { prop: "trainingManageCount", labelKey: "formTrainingManageCount", unitKey: "unitPerson" },
  { prop: "trainingSkillCount", labelKey: "formTrainingSkillCount", unitKey: "unitPerson" },
  { prop: "trainingOtherCount", labelKey: "formTrainingOtherCount", unitKey: "unitPerson" }
]

const NUMERIC_PROPS = [
  ...BASIC_DECIMAL_FIELDS.map((f) => f.prop),
  ...MEMBER_COUNT_FIELDS.map((f) => f.prop),
  ...SHARE_DECIMAL_FIELDS.map((f) => f.prop),
  "laborShareCount",
  ...BENEFIT_DECIMAL_FIELDS.map((f) => f.prop),
  ...EMPLOYMENT_FIELDS.map((f) => f.prop),
  ...LIVESTOCK_INOUT_FIELDS.map((f) => f.prop),
  ...PRODUCT_CERT_FIELDS.map((f) => f.prop),
  ...TRAINING_FIELDS.map((f) => f.prop)
]

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,
    cooperativeName: undefined,
    legalRepresentative: undefined,
    establishDate: undefined,
    businessScopeList: [],
    businessModel: undefined,
    operationStatus: undefined,
    remark: undefined
  }
  NUMERIC_PROPS.forEach((prop) => {
    form[prop] = undefined
  })
  return form
}

function parseBusinessScope(value) {
  if (value == null || value === "") {
    return []
  }
  return String(value)
    .split(/[,，]/)
    .map((s) => s.trim())
    .filter(Boolean)
}

function normalizeForm(data) {
  const row = Object.assign(createEmptyForm(), data || {})
  NUMERIC_PROPS.forEach((prop) => {
    const val = row[prop]
    row[prop] = val == null || val === "" ? undefined : Number(val)
  })
  row.businessScopeList = parseBusinessScope(row.businessScope)
  if (row.businessModel === "") {
    row.businessModel = undefined
  }
  if (row.operationStatus === "") {
    row.operationStatus = 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,
          deptName: villageName,
          townName,
          label: townName ? `${townName} / ${villageName}` : villageName
        })
      })
    })
  })
  return list
}

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

export default {
  name: "CooperativeDevelopment",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "cooperativeDevelopment",
      loading: false,
      importing: false,
      exporting: false,
      open: false,
      viewOpen: false,
      importOpen: false,
      exportOpen: false,
      dialogEdit: false,
      formKey: 0,
      total: 0,
      ids: [],
      tableList: [],
      yearOptions: buildDataModelYearOptions(),
      monthOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      townOptions: [],
      villageOptions: [],
      businessScopeOptions: BUSINESS_SCOPE_OPTIONS,
      businessModelOptions: BUSINESS_MODEL_OPTIONS,
      operationStatusOptions: OPERATION_STATUS_OPTIONS,
      basicDecimalFields: BASIC_DECIMAL_FIELDS,
      memberCountFields: MEMBER_COUNT_FIELDS,
      shareDecimalFields: SHARE_DECIMAL_FIELDS,
      benefitDecimalFields: BENEFIT_DECIMAL_FIELDS,
      employmentFields: EMPLOYMENT_FIELDS,
      livestockInoutFields: LIVESTOCK_INOUT_FIELDS,
      productCertFields: PRODUCT_CERT_FIELDS,
      trainingFields: TRAINING_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,
        cooperativeName: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    livestockShareTotalDisplay() {
      return safeInt(this.form.cattleShareCount) + safeInt(this.form.sheepShareCount)
    },
    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" }],
        cooperativeName: [
          { required: true, message: this.dmT("ruleCooperativeNameRequired"), trigger: "blur" },
          { max: 200, message: this.dmT("ruleCooperativeNameLen"), 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() {

      listCooperativeDevelopmentMonthOptions().then((res) => {
        if (Array.isArray(res.data) && res.data.length) {
          this.monthOptions = res.data
        }
      })
      listCooperativeDevelopmentTownOptions().then((res) => {
        this.townOptions = Array.isArray(res.data) ? res.data : []
      })
      this.loadVillageTree()
    },
    loadVillageTree() {
      return listCooperativeDevelopmentVillageTree()
        .then((res) => {
          const raw = res && res.data !== undefined ? res.data : res
          const tree = Array.isArray(raw) ? raw : []
          this.villageOptions = flattenVillageOptions(tree)
          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 })
    },
    livestockShareTotalOf(row) {
      if (!row) {
        return 0
      }
      if (row.livestockShareTotal != null && row.livestockShareTotal !== "") {
        return row.livestockShareTotal
      }
      return safeInt(row.cattleShareCount) + safeInt(row.sheepShareCount)
    },
    formatCount(val) {
      if (val == null || val === "") {
        return this.dash
      }
      return val
    },
    formatDecimal(val) {
      if (val == null || val === "") {
        return this.dash
      }
      return val
    },
    isFutureStatPeriod(statYear, statMonth) {
      if (statYear == null || statMonth == null) {
        return false
      }
      const now = new Date()
      const currentYear = now.getFullYear()
      const currentMonth = now.getMonth() + 1
      if (statYear > currentYear) {
        return true
      }
      return statYear === currentYear && statMonth > currentMonth
    },
    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.cooperativeName != null ? String(this.queryParams.cooperativeName).trim() : ""
      if (name) {
        q.cooperativeName = name
      }
      return q
    },
    buildPayload() {
      const remarkText = this.form.remark != null ? String(this.form.remark).trim() : ""
      const cooperativeName = this.form.cooperativeName != null ? String(this.form.cooperativeName).trim() : ""
      const legalRep = this.form.legalRepresentative != null ? String(this.form.legalRepresentative).trim() : ""
      const establishDate = this.form.establishDate != null ? String(this.form.establishDate).trim() : ""
      const scopeList = Array.isArray(this.form.businessScopeList) ? this.form.businessScopeList : []
      const payload = {
        statYear: this.form.statYear,
        statMonth: this.form.statMonth,
        villageDeptId: this.form.villageDeptId,
        cooperativeName,
        legalRepresentative: legalRep !== "" ? legalRep : undefined,
        establishDate: establishDate !== "" ? establishDate : undefined,
        businessScope: scopeList.length ? scopeList.join(",") : undefined,
        businessModel: this.form.businessModel || undefined,
        operationStatus: this.form.operationStatus || undefined,
        remark: remarkText !== "" ? remarkText : undefined
      }
      NUMERIC_PROPS.forEach((prop) => {
        const val = this.form[prop]
        payload[prop] = val == null || val === "" ? undefined : val
      })
      return payload
    },
    getList() {
      this.loading = true
      listCooperativeDevelopment(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.cooperativeName = 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.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()
          }
        })
      }
      getCooperativeDevelopment(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) {
      getCooperativeDevelopment(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dmT("confirmDelete"))
        .then(() => delCooperativeDevelopment(String(row.id)))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    handleDeleteBatch() {
      if (!this.ids.length) {
        return
      }
      this.$modal
        .confirm(this.dmT("confirmDeleteBatch"))
        .then(() => delCooperativeDevelopment(this.ids.join(",")))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateCooperativeDevelopment(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addCooperativeDevelopment(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 = `cooperative_development_template_${new Date().getTime()}.xlsx`
      this.$modal.loading("正在下载模板，请稍候")
      downloadCooperativeDevelopmentTemplate()
        .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 = undefined
      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 = this.exportForm.statYear
        const statMonth = this.exportForm.statMonth
        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"))
        exportCooperativeDevelopment(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 upload = this.$refs.importUpload
        const files = upload && upload.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"))
        importCooperativeDevelopment(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>
.cd-section-title {
  margin: 4px 0 12px;
  font-weight: 600;
  color: #303133;
}
.cd-import-tip {
  margin: 0 0 12px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}
.cd-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>
