<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="keyword">
          <template slot="label">{{ dmT("queryKeyword") }}</template>
          <el-input
            v-model="queryParams.keyword"
            :placeholder="dmT('queryKeywordPh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="utilizationType">
          <template slot="label">{{ dmT("queryUtilizationType") }}</template>
          <el-select v-model="queryParams.utilizationType" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 130px">
            <el-option v-for="item in utilizationTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="degradationLevel">
          <template slot="label">{{ dmT("queryDegradationLevel") }}</template>
          <el-select v-model="queryParams.degradationLevel" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 120px">
            <el-option v-for="item in degradationLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </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:grassland:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dmCommon("add") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:grassland:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!ids.length"
            @click="handleDeleteBatch"
          >{{ dmCommon("delete") }}</el-button>
          <!-- <el-button
            v-hasPermi="['dataModel:grassland:export']"
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >{{ dmCommon("export") }}</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" fixed="left" />
        <el-table-column :label="dmT('colGrasslandName')" prop="grasslandName" align="center" min-width="100" fixed="left" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colAreaMu')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.areaMu, dmT('unitMu')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colGrazingBanArea')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.grazingBanArea, dmT('unitMu')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colGrassBalanceArea')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.grassBalanceArea, dmT('unitMu')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colDegradationLevel')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ degradationLabel(scope.row.degradationLevel) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colUtilizationType')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ utilizationLabel(scope.row.utilizationType) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colGrassYieldPerMu')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.grassYieldPerMu, dmT('unitKgPerMu')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colUtilizationRate')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ formatUtilizationRate(scope.row.utilizationRate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colBanStart')" prop="grazingBanStartDate" align="center" width="110" />
        <el-table-column :label="dmT('colBanEnd')" prop="grazingBanEndDate" align="center" width="110" />
        <el-table-column :label="dmT('colRotationPlots')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.rotationPlotCount, dmT('unitBlock')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colRotationGrazingDays')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.rotationGrazingDays, dmT('unitDay')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colRotationCycle')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.rotationCycleDays, dmT('unitDay')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmCommon('colCreate')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime) : $t("dataModel.status.dash") }}</span>
          </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:grassland:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:grassland:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:grassland: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="900px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="130px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="grasslandName" :rules="formRules.grasslandName">
              <template slot="label">{{ dmT("formGrasslandName") }}</template>
              <el-input v-model="form.grasslandName" :placeholder="dmT('phGrasslandName')" maxlength="10" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="areaMu" :rules="formRules.areaMu">
              <template slot="label">{{ dmT("formAreaMu") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.areaMu" :min="0" :precision="2" :step="0.1" controls-position="right" 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 prop="grazingBanArea" :rules="formRules.optionalPositiveArea">
              <template slot="label">{{ dmT("formGrazingBanArea") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.grazingBanArea" :min="0" :precision="2" :step="0.1" controls-position="right" 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 prop="grassBalanceArea" :rules="formRules.optionalPositiveArea">
              <template slot="label">{{ dmT("formGrassBalanceArea") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.grassBalanceArea" :min="0" :precision="2" :step="0.1" controls-position="right" 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 prop="degradationLevel">
              <template slot="label">{{ dmT("formDegradationLevel") }}</template>
              <el-select v-model="form.degradationLevel" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 100%">
                <el-option v-for="item in degradationLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="utilizationType">
              <template slot="label">{{ dmT("formUtilizationType") }}</template>
              <el-select v-model="form.utilizationType" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 100%">
                <el-option v-for="item in utilizationTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="grassYieldPerMu" :rules="formRules.optionalPositiveNumber">
              <template slot="label">{{ dmT("formGrassYieldPerMu") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.grassYieldPerMu" :min="0" :precision="2" :step="1" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitKgPerMu") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="utilizationRate" :rules="formRules.utilizationRate">
              <template slot="label">{{ dmT("formUtilizationRate") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.utilizationRate" :min="0" :max="1" :precision="4" :step="0.01" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitRatio") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="grazingBanStartDate" :rules="formRules.grazingBanDate">
              <template slot="label">{{ dmT("formBanStart") }}</template>
              <el-date-picker
                v-model="form.grazingBanStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="dmCommon('pleaseSelect')"
                style="width: 100%"
                @change="onBanDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="grazingBanEndDate" :rules="formRules.grazingBanDate">
              <template slot="label">{{ dmT("formBanEnd") }}</template>
              <el-date-picker
                v-model="form.grazingBanEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="dmCommon('pleaseSelect')"
                style="width: 100%"
                @change="onBanDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="rotationPlotCount" :rules="formRules.rotationPlotCount">
              <template slot="label">{{ dmT("formRotationPlots") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.rotationPlotCount" :min="1" :precision="0" :step="1" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitBlock") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="rotationGrazingDays" :rules="formRules.rotationGrazingDays">
              <template slot="label">{{ dmT("formRotationGrazingDays") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.rotationGrazingDays" :min="1" :precision="0" :step="1" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitDay") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="rotationCycleDays" :rules="formRules.rotationCycleDays">
              <template slot="label">{{ dmT("formRotationCycle") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number v-model="form.rotationCycleDays" :min="1" :precision="0" :step="1" controls-position="right" class="dm-input-with-unit__input" />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitDay") }}</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="100" 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="900px" append-to-body>
      <el-form class="dm-view-form" label-width="130px" size="small">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item :label="dmT('formGrasslandName')">
              <span>{{ viewRow.grasslandName || $t("dataModel.status.dash") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formAreaMu')">
              <span>{{ formatWithUnit(viewRow.areaMu, dmT('unitMu')) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formGrazingBanArea')">
              <span>{{ formatWithUnit(viewRow.grazingBanArea, dmT('unitMu')) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formGrassBalanceArea')">
              <span>{{ formatWithUnit(viewRow.grassBalanceArea, dmT('unitMu')) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formDegradationLevel')">
              <span>{{ degradationLabel(viewRow.degradationLevel) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formUtilizationType')">
              <span>{{ utilizationLabel(viewRow.utilizationType) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formGrassYieldPerMu')">
              <span>{{ formatWithUnit(viewRow.grassYieldPerMu, dmT('unitKgPerMu')) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formUtilizationRate')">
              <span>{{ formatUtilizationRate(viewRow.utilizationRate) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formBanStart')">
              <span>{{ viewRow.grazingBanStartDate || $t("dataModel.status.dash") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formBanEnd')">
              <span>{{ viewRow.grazingBanEndDate || $t("dataModel.status.dash") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formRotationPlots')">
              <span>{{ formatWithUnit(viewRow.rotationPlotCount, dmT('unitBlock')) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formRotationGrazingDays')">
              <span>{{ formatWithUnit(viewRow.rotationGrazingDays, dmT('unitDay')) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('formRotationCycle')">
              <span>{{ formatWithUnit(viewRow.rotationCycleDays, dmT('unitDay')) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="dmT('formRemark')">
              <span>{{ viewRow.remark || $t("dataModel.status.dash") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('viewCreateBy')">
              <span>{{ viewRow.createBy || $t("dataModel.status.dash") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmCommon('colCreate')">
              <span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : $t("dataModel.status.dash") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('viewUpdateBy')">
              <span>{{ viewRow.updateBy || $t("dataModel.status.dash") }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="dmT('viewUpdateTime')">
              <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : $t("dataModel.status.dash") }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">{{ dmCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataModelLocaleMixin from "@/mixins/dataModelLocaleMixin"
import {
  listGrassland,
  getGrassland,
  addGrassland,
  updateGrassland,
  delGrassland
} from "@/api/dataModel/grassland"

export default {
  name: "Grassland",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "grassland",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      ids: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined,
        utilizationType: undefined,
        degradationLevel: undefined
      },
      form: {}
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    degradationLevelOptions() {
      return [1, 2, 3, 4, 5].map((v) => ({ value: v, label: this.dmT("degradation" + v) }))
    },
    utilizationTypeOptions() {
      return [1, 2, 3].map((v) => ({ value: v, label: this.dmT("utilization" + v) }))
    },
    formRules() {
      return {
        grasslandName: [
          { required: true, message: this.dmT("ruleNameRequired"), trigger: "blur" },
          { min: 1, max: 10, message: this.dmT("ruleNameLen"), trigger: "blur" }
        ],
        areaMu: [
          { required: true, message: this.dmT("ruleAreaRequired"), trigger: "blur" },
          { validator: this.validatePositiveNumber, message: this.dmT("ruleAreaPositive"), trigger: "blur" }
        ],
        optionalPositiveArea: [
          { validator: this.validatePositiveNumber, message: this.dmT("ruleOptionalAreaPositive"), trigger: "blur" }
        ],
        optionalPositiveNumber: [
          { validator: this.validatePositiveNumber, message: this.dmT("ruleYieldPositive"), trigger: "blur" }
        ],
        utilizationRate: [{ validator: this.validateUtilizationRate, trigger: "blur" }],
        grazingBanDate: [{ validator: this.validateBanDatePair, trigger: "change" }],
        rotationPlotCount: [
          { validator: this.validateMinIntOne, message: this.dmT("ruleRotationPlotsMin"), trigger: "blur" }
        ],
        rotationGrazingDays: [
          { validator: this.validateMinIntOne, message: this.dmT("ruleRotationGrazingMin"), trigger: "blur" }
        ],
        rotationCycleDays: [
          { validator: this.validateMinIntOne, message: this.dmT("ruleRotationCycleMin"), trigger: "blur" }
        ],
        remark: [{ max: 100, message: this.dmCommon("ruleLen100"), trigger: "blur" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    degradationLabel(v) {
      if (v == null || v === "") {
        return this.$t("dataModel.status.dash")
      }
      return this.dmT("degradation" + v) || v
    },
    utilizationLabel(v) {
      if (v == null || v === "") {
        return this.$t("dataModel.status.dash")
      }
      return this.dmT("utilization" + v) || v
    },
    formatWithUnit(val, unit) {
      if (val == null || val === "") {
        return this.$t("dataModel.status.dash")
      }
      return `${val}${unit}`
    },
    formatUtilizationRate(rate) {
      if (rate == null || rate === "") {
        return this.$t("dataModel.status.dash")
      }
      const n = Number(rate)
      if (isNaN(n)) {
        return this.$t("dataModel.status.dash")
      }
      return `${(n * 100).toFixed(2)}%`
    },
    validatePositiveNumber(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      const n = Number(value)
      if (isNaN(n) || n <= 0) {
        callback(new Error(rule.message))
        return
      }
      callback()
    },
    validateUtilizationRate(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      const n = Number(value)
      if (isNaN(n) || n < 0 || n > 1) {
        callback(new Error(this.dmT("ruleRateRange")))
        return
      }
      callback()
    },
    validateMinIntOne(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      const n = Number(value)
      if (!Number.isInteger(n) || n < 1) {
        callback(new Error(rule.message || this.dmT("ruleRotationPlotsMin")))
        return
      }
      callback()
    },
    validateBanDatePair(rule, value, callback) {
      const start = this.form.grazingBanStartDate
      const end = this.form.grazingBanEndDate
      if (!start && !end) {
        callback()
        return
      }
      if (!start || !end) {
        callback(new Error(this.dmT("ruleBanDatePair")))
        return
      }
      if (end < start) {
        callback(new Error(this.dmT("ruleBanDateOrder")))
        return
      }
      callback()
    },
    onBanDateChange() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField("grazingBanStartDate")
          this.$refs.form.validateField("grazingBanEndDate")
        }
      })
    },
    getList() {
      this.loading = true
      listGrassland(this.queryParams)
        .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.keyword = undefined
      this.queryParams.utilizationType = undefined
      this.queryParams.degradationLevel = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        grasslandName: undefined,
        areaMu: undefined,
        grazingBanArea: undefined,
        grassBalanceArea: undefined,
        degradationLevel: undefined,
        utilizationType: undefined,
        grassYieldPerMu: undefined,
        utilizationRate: undefined,
        grazingBanStartDate: undefined,
        grazingBanEndDate: undefined,
        rotationPlotCount: undefined,
        rotationGrazingDays: undefined,
        rotationCycleDays: undefined,
        remark: undefined
      }
    },
    toNumberFields(data) {
      const toNum = (val) => (val != null && val !== "" ? Number(val) : undefined)
      return {
        areaMu: toNum(data.areaMu),
        grazingBanArea: toNum(data.grazingBanArea),
        grassBalanceArea: toNum(data.grassBalanceArea),
        grassYieldPerMu: toNum(data.grassYieldPerMu),
        utilizationRate: toNum(data.utilizationRate),
        rotationPlotCount: toNum(data.rotationPlotCount),
        rotationGrazingDays: toNum(data.rotationGrazingDays),
        rotationCycleDays: toNum(data.rotationCycleDays)
      }
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => this.resetForm("form"))
    },
    handleEdit(row) {
      getGrassland(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.form = {
          id: data.id,
          grasslandName: data.grasslandName,
          degradationLevel: data.degradationLevel,
          utilizationType: data.utilizationType,
          grazingBanStartDate: data.grazingBanStartDate,
          grazingBanEndDate: data.grazingBanEndDate,
          remark: data.remark,
          ...this.toNumberFields(data)
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getGrassland(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("dataModel.grassland.confirmDelete", { id: row.id }))
        .then(() => delGrassland(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleDeleteBatch() {
      if (!this.ids.length) {
        return
      }
      this.$modal
        .confirm(this.dmT("confirmDeleteBatch"))
        .then(() => delGrassland(this.ids.join(",")))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleExport() {
      this.download(
        "dataModel/grassland/export",
        { ...this.queryParams },
        `grassland_${new Date().getTime()}.xlsx`
      )
    },
    emptyToUndef(val) {
      return val == null || val === "" ? undefined : val
    },
    buildPayload() {
      return {
        grasslandName: this.form.grasslandName,
        areaMu: this.form.areaMu,
        grazingBanArea: this.emptyToUndef(this.form.grazingBanArea),
        grassBalanceArea: this.emptyToUndef(this.form.grassBalanceArea),
        degradationLevel: this.emptyToUndef(this.form.degradationLevel),
        utilizationType: this.emptyToUndef(this.form.utilizationType),
        grassYieldPerMu: this.emptyToUndef(this.form.grassYieldPerMu),
        utilizationRate: this.emptyToUndef(this.form.utilizationRate),
        grazingBanStartDate: this.emptyToUndef(this.form.grazingBanStartDate),
        grazingBanEndDate: this.emptyToUndef(this.form.grazingBanEndDate),
        rotationPlotCount: this.emptyToUndef(this.form.rotationPlotCount),
        rotationGrazingDays: this.emptyToUndef(this.form.rotationGrazingDays),
        rotationCycleDays: this.emptyToUndef(this.form.rotationCycleDays),
        remark: this.form.remark || undefined
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateGrassland(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addGrassland(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
.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>
