<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="statYear">
          <template slot="label">{{ dmT("queryStatYear") }}</template>
          <el-select v-model="queryParams.statYear" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 120px">
            <el-option v-for="y in yearOptions" :key="y" :label="String(y)" :value="y" />
          </el-select>
        </el-form-item>
        <el-form-item prop="statMonth">
          <template slot="label">{{ dmT("queryStatMonth") }}</template>
          <el-select v-model="queryParams.statMonth" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 120px">
            <el-option v-for="m in monthOptions" :key="'q-' + m" :label="formatStatMonth(m)" :value="m" />
          </el-select>
        </el-form-item>
        <el-form-item prop="townDeptId">
          <template slot="label">{{ dmT("queryTown") }}</template>
          <el-select v-model="queryParams.townDeptId" :placeholder="dmCommon('pleaseSelect')" clearable filterable style="width: 180px">
            <el-option v-for="item in townOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ dmCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ dmCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:yakOutboundReport:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dmCommon("add") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:yakOutboundReport:import']"
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImportOpen"
          >{{ dmT("btnImport") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:yakOutboundReport: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="100" />
        <el-table-column :label="dmT('colStatMonth')" align="center" width="90">
          <template slot-scope="scope">{{ formatStatMonth(scope.row.statMonth) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colTownName')" prop="townName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colFarmerHouseholdCount')" align="center" width="100">
          <template slot-scope="scope">{{ formatCount(scope.row.farmerHouseholdCount) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colFarmerPopulationCount')" align="center" width="100">
          <template slot-scope="scope">{{ formatCount(scope.row.farmerPopulationCount) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colYakOutboundCount')" align="center" width="110">
          <template slot-scope="scope">{{ formatCount(scope.row.yakOutboundCount) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colSelfConsumptionCattle')" align="center" width="120">
          <template slot-scope="scope">{{ formatCount(scope.row.selfConsumptionCattleCount) }}</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:yakOutboundReport:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:yakOutboundReport:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:yakOutboundReport: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="920px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="168px" size="small">
        <div class="yor-section-title">{{ dmT("sectionBasic") }}</div>
        <el-row :gutter="16">
          <el-col :span="8">
            <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="8">
            <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="8">
            <el-form-item prop="townDeptId" :rules="formRules.townDeptId">
              <template slot="label">{{ dmT("formTown") }}</template>
              <el-select v-model="form.townDeptId" :placeholder="dmCommon('pleaseSelect')" filterable style="width: 100%">
                <el-option v-for="item in townOptions" :key="'ft-' + item.deptId" :label="item.deptName" :value="item.deptId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="yor-section-title">{{ dmT("sectionFarmer") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in farmerCountFields" :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="yor-section-title">{{ dmT("sectionOutbound") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in outboundCountFields" :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="yor-section-title">{{ dmT("sectionSelfConsumption") }}</div>
        <el-row :gutter="16">
          <el-col v-for="field in selfConsumptionCountFields" :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>
        <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="720px" append-to-body>
      <el-form label-width="168px" size="small">
        <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 v-for="field in viewFields" :key="'v-' + field.prop" :span="12">
            <el-form-item :label="dmT(field.labelKey)">
              <span>{{ formatCount(viewRow[field.prop]) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-hasPermi="['dataModel:yakOutboundReport: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="'i-' + 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="yor-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="'e-' + 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>
      <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 {
  listYakOutboundReport,
  getYakOutboundReport,
  addYakOutboundReport,
  updateYakOutboundReport,
  delYakOutboundReport,
  listYakOutboundReportYearOptions,
  listYakOutboundReportMonthOptions,
  listYakOutboundReportTownOptions,
  importYakOutboundReport,
  downloadYakOutboundReportTemplate,
  exportYakOutboundReport
} from "@/api/dataModel/yakOutboundReport"
import { blobValidate } from "@/utils/ruoyi"
import { saveAs } from "file-saver"

const COUNT_FIELDS = [
  { prop: "farmerHouseholdCount", labelKey: "formFarmerHouseholdCount", unitKey: "unitHousehold", section: "farmer" },
  { prop: "farmerPopulationCount", labelKey: "formFarmerPopulationCount", unitKey: "unitPerson", section: "farmer" },
  { prop: "yakOutboundCount", labelKey: "formYakOutboundCount", unitKey: "unitHead", section: "outbound" },
  { prop: "cattleOutboundCount", labelKey: "formCattleOutboundCount", unitKey: "unitHead", section: "outbound" },
  { prop: "sheepOutboundCount", labelKey: "formSheepOutboundCount", unitKey: "unitSheep", section: "outbound" },
  { prop: "goatOutboundCount", labelKey: "formGoatOutboundCount", unitKey: "unitSheep", section: "outbound" },
  { prop: "horseMuleOutboundCount", labelKey: "formHorseMuleOutboundCount", unitKey: "unitHorse", section: "outbound" },
  { prop: "donkeyOutboundCount", labelKey: "formDonkeyOutboundCount", unitKey: "unitHead", section: "outbound" },
  { prop: "selfConsumptionCattleCount", labelKey: "formSelfConsumptionCattleCount", unitKey: "unitHead", section: "selfConsumption" },
  { prop: "selfConsumptionSheepCount", labelKey: "formSelfConsumptionSheepCount", unitKey: "unitSheep", section: "selfConsumption" },
  { prop: "selfConsumptionGoatCount", labelKey: "formSelfConsumptionGoatCount", unitKey: "unitSheep", section: "selfConsumption" }
]

const VIEW_FIELDS = [
  { prop: "farmerHouseholdCount", labelKey: "formFarmerHouseholdCount" },
  { prop: "farmerPopulationCount", labelKey: "formFarmerPopulationCount" },
  { prop: "yakOutboundCount", labelKey: "formYakOutboundCount" },
  { prop: "selfConsumptionCattleCount", labelKey: "formSelfConsumptionCattleCount" }
]

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

function createEmptyForm() {
  const form = {
    id: undefined,
    statYear: undefined,
    statMonth: undefined,
    townDeptId: undefined,
    remark: undefined
  }
  COUNT_FIELDS.forEach((field) => {
    form[field.prop] = 0
  })
  return form
}

function normalizeCountFields(data) {
  const row = Object.assign(createEmptyForm(), data || {})
  COUNT_FIELDS.forEach((field) => {
    const val = row[field.prop]
    row[field.prop] = val == null || val === "" ? 0 : val
  })
  return row
}

export default {
  name: "YakOutboundReport",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "yakOutboundReport",
      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: [],
      viewRow: {},
      importForm: {
        statYear: undefined,
        statMonth: undefined
      },
      exportForm: {
        statYear: undefined,
        statMonth: undefined
      },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        statYear: undefined,
        statMonth: undefined,
        townDeptId: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    },
    farmerCountFields() {
      return COUNT_FIELDS.filter((field) => field.section === "farmer")
    },
    outboundCountFields() {
      return COUNT_FIELDS.filter((field) => field.section === "outbound")
    },
    selfConsumptionCountFields() {
      return COUNT_FIELDS.filter((field) => field.section === "selfConsumption")
    },
    viewFields() {
      return VIEW_FIELDS
    },
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    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" }
        ],
        townDeptId: [{ required: true, message: this.dmT("ruleTownRequired"), trigger: "change" }],
        count: [{ validator: this.validateOptionalCount, 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() {
      listYakOutboundReportYearOptions().then((res) => {
        this.yearOptions = Array.isArray(res.data) ? res.data : []
      })
      listYakOutboundReportMonthOptions().then((res) => {
        if (Array.isArray(res.data) && res.data.length) {
          this.monthOptions = res.data
        }
      })
      listYakOutboundReportTownOptions().then((res) => {
        this.townOptions = Array.isArray(res.data) ? res.data : []
      })
    },
    formatStatMonth(month) {
      if (month == null || month === "") {
        return this.dash
      }
      return this.dmT("statMonthLabel", { month })
    },
    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()
    },
    formatCount(val) {
      if (val == null || val === "") {
        return this.dash
      }
      return val
    },
    validateOptionalCount(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      if (!Number.isInteger(value) || value < 0) {
        callback(new Error(this.dmT("ruleCountNonNegative")))
        return
      }
      callback()
    },
    buildListQuery() {
      const q = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      if (this.queryParams.statYear != null) {
        q.statYear = this.queryParams.statYear
      }
      if (this.queryParams.statMonth != null) {
        q.statMonth = this.queryParams.statMonth
      }
      if (this.queryParams.townDeptId != null) {
        q.townDeptId = this.queryParams.townDeptId
      }
      return q
    },
    buildPayload() {
      const remarkText = this.form.remark != null ? String(this.form.remark).trim() : ""
      const payload = {
        statYear: this.form.statYear,
        statMonth: this.form.statMonth,
        townDeptId: this.form.townDeptId,
        remark: remarkText !== "" ? remarkText : undefined
      }
      COUNT_FIELDS.forEach((field) => {
        payload[field.prop] = this.form[field.prop]
      })
      return payload
    },
    getList() {
      this.loading = true
      listYakOutboundReport(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.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      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()
        }
      })
    },
    handleEdit(row) {
      getYakOutboundReport(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.form = normalizeCountFields(data)
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleEditFromView() {
      this.handleEdit(this.viewRow)
    },
    handleView(row) {
      getYakOutboundReport(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dmT("confirmDelete"))
        .then(() => delYakOutboundReport(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
          updateYakOutboundReport(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addYakOutboundReport(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 = `yak_outbound_report_template_${new Date().getTime()}.xlsx`
      this.$modal.loading("正在下载模板，请稍候")
      downloadYakOutboundReportTemplate()
        .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.exportOpen = true
      this.$nextTick(() => {
        if (this.$refs.exportFormRef) {
          this.$refs.exportFormRef.clearValidate()
        }
      })
    },
    resetExport() {
      this.exporting = false
      this.exportForm.statYear = undefined
      this.exportForm.statMonth = 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"))
        exportYakOutboundReport(statYear, statMonth)
          .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"))
        importYakOutboundReport(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>
.yor-section-title {
  margin: 4px 0 12px;
  padding-left: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  border-left: 3px solid #409eff;
}

.yor-import-tip {
  margin: 0 0 12px;
  font-size: 12px;
  color: #909399;
  line-height: 1.6;
}

.dm-input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;
}
.dm-input-with-unit__input {
  flex: 1;
  width: 0;
}
.dm-input-with-unit__input ::v-deep.el-input-number {
  width: 100%;
}
.dm-input-with-unit__suffix {
  flex-shrink: 0;
  margin-left: 8px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}
</style>
