<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="createDateRange">
          <template slot="label">{{ dmT("queryReserveDate") }}</template>
          <el-date-picker
            v-model="queryParams.createDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :range-separator="dmT('reserveRangeSeparator')"
            :start-placeholder="dmT('reserveRangeStartPh')"
            :end-placeholder="dmT('reserveRangeEndPh')"
            style="width: 260px"
          />
        </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:grasslandUsage:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dmCommon("add") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:grasslandUsage:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!ids.length"
            @click="handleDeleteBatch"
          >{{ dmCommon("delete") }}</el-button>
          <!-- <el-button
            v-hasPermi="['dataModel:grasslandUsage: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" />
        <el-table-column :label="dmT('colGrasslandName')" prop="grasslandName" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colUsageAreaMu')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.usageAreaMu, $t('dataModel.grassland.unitMu')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colPastureName')" prop="pastureName" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colUseStart')" prop="useStartDate" align="center" width="110" />
        <el-table-column :label="dmT('colUseEnd')" prop="useEndDate" align="center" width="110" />
        <el-table-column :label="dmT('colActualUseDays')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.actualUseDays, $t('dataModel.grassland.unitDay')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colGrazingHeadCount')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ formatWithUnit(scope.row.grazingHeadCount, dmT('unitHead')) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dmT('colGrazingMethod')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ grazingMethodLabel(scope.row.grazingMethod) }}</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:grasslandUsage:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:grasslandUsage:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:grasslandUsage: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="720px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="130px">
        <el-form-item prop="grasslandId" :rules="formRules.grasslandId">
          <template slot="label">{{ dmT("formGrassland") }}</template>
          <el-select
            v-model="form.grasslandId"
            filterable
            remote
            reserve-keyword
            :placeholder="dmT('phGrasslandSelect')"
            :remote-method="searchGrassland"
            :loading="grasslandLoading"
            style="width: 100%"
            @change="handleGrasslandChange"
            @focus="searchGrassland('')"
          >
            <el-option
              v-for="item in grasslandOptions"
              :key="item.id"
              :label="item.grasslandName"
              :value="item.id"
            />
          </el-select>
          <div v-if="selectedGrasslandAreaMu != null" class="form-hint">{{ grasslandAreaHintText }}</div>
        </el-form-item>
        <el-form-item prop="usageAreaMu" :rules="formRules.usageAreaMu">
          <template slot="label">{{ dmT("formUsageAreaMu") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.usageAreaMu"
              :min="0"
              :precision="2"
              :step="0.1"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ $t("dataModel.grassland.unitMu") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="pastureId" :rules="formRules.pastureId">
          <template slot="label">{{ dmT("formPasture") }}</template>
          <el-select
            v-model="form.pastureId"
            filterable
            remote
            reserve-keyword
            :placeholder="dmT('phPastureSelect')"
            :remote-method="searchPasture"
            :loading="pastureLoading"
            style="width: 100%"
            @focus="searchPasture('')"
          >
            <el-option
              v-for="item in pastureOptions"
              :key="item.id"
              :label="item.pastureName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="useDateRange" :rules="formRules.useDateRange">
          <template slot="label">{{ dmT("formUseDate") }}</template>
          <el-date-picker
            v-model="form.useDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :range-separator="dmT('useRangeSeparator')"
            :start-placeholder="dmT('useRangeStartPh')"
            :end-placeholder="dmT('useRangeEndPh')"
            style="width: 100%"
            @change="syncActualUseDays"
          />
        </el-form-item>
        <el-form-item prop="actualUseDays">
          <template slot="label">{{ dmT("formActualUseDays") }}</template>
          <div class="dm-input-with-unit">
            <el-input :value="displayActualUseDays" disabled class="dm-readonly-days" />
            <span class="dm-input-with-unit__suffix">{{ $t("dataModel.grassland.unitDay") }}</span>
          </div>
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item prop="grazingHeadCount" :rules="formRules.grazingHeadCount">
              <template slot="label">{{ dmT("formGrazingHeadCount") }}</template>
              <div class="dm-input-with-unit">
                <el-input-number
                  v-model="form.grazingHeadCount"
                  :min="1"
                  :precision="0"
                  :step="1"
                  controls-position="right"
                  class="dm-input-with-unit__input"
                />
                <span class="dm-input-with-unit__suffix">{{ dmT("unitHead") }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="grazingMethod" :rules="formRules.grazingMethod">
              <template slot="label">{{ dmT("formGrazingMethod") }}</template>
              <el-select v-model="form.grazingMethod" :placeholder="dmCommon('pleaseSelect')" style="width: 100%">
                <el-option v-for="item in grazingMethodOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </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="680px" append-to-body>
      <el-form label-width="130px" size="small">
        <el-form-item :label="dmT('formGrassland')">
          <span>{{ viewRow.grasslandName || $t('dataModel.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formUsageAreaMu')">
          <span>{{ formatWithUnit(viewRow.usageAreaMu, $t('dataModel.grassland.unitMu')) }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formPasture')">
          <span>{{ viewRow.pastureName || $t('dataModel.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formUseDate')">
          <span>{{ useDateRangeText(viewRow) }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formActualUseDays')">
          <span>{{ formatWithUnit(viewRow.actualUseDays, $t('dataModel.grassland.unitDay')) }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formGrazingHeadCount')">
          <span>{{ formatWithUnit(viewRow.grazingHeadCount, dmT('unitHead')) }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formGrazingMethod')">
          <span>{{ grazingMethodLabel(viewRow.grazingMethod) }}</span>
        </el-form-item>
        <el-form-item :label="dmT('viewCreateBy')">
          <span>{{ viewRow.createBy || $t('dataModel.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="dmCommon('colCreate')">
          <span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : $t('dataModel.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="dmT('viewUpdateBy')">
          <span>{{ viewRow.updateBy || $t('dataModel.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="dmT('viewUpdateTime')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : $t('dataModel.status.dash') }}</span>
        </el-form-item>
      </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 } from "@/api/dataModel/grassland"
import { listPasture } from "@/api/dataModel/pasture"
import {
  listGrasslandUsage,
  getGrasslandUsage,
  addGrasslandUsage,
  updateGrasslandUsage,
  delGrasslandUsage
} from "@/api/dataModel/grasslandUsage"

export default {
  name: "GrasslandUsage",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "grasslandUsage",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      ids: [],
      grasslandLoading: false,
      pastureLoading: false,
      grasslandOptions: [],
      pastureOptions: [],
      selectedGrasslandAreaMu: null,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined,
        createDateRange: null
      },
      form: {}
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    grazingMethodOptions() {
      return [1, 2, 3].map((value) => ({ label: this.dmT("grazing" + value), value }))
    },
    grasslandAreaHintText() {
      return this.dmT("grasslandAreaHint", { area: this.selectedGrasslandAreaMu })
    },
    displayActualUseDays() {
      const days = this.calcActualUseDays(this.form.useDateRange)
      return days != null ? String(days) : ""
    },
    formRules() {
      return {
        grasslandId: [{ required: true, message: this.dmT("ruleGrasslandRequired"), trigger: "change" }],
        pastureId: [{ required: true, message: this.dmT("rulePastureRequired"), trigger: "change" }],
        usageAreaMu: [
          { required: true, message: this.dmT("ruleUsageAreaRequired"), trigger: "blur" },
          { validator: this.validateUsageAreaMu, trigger: "blur" }
        ],
        useDateRange: [
          { required: true, message: this.dmT("ruleUseDateRequired"), trigger: "change" },
          { validator: this.validateUseDateRange, trigger: "change" }
        ],
        grazingHeadCount: [
          { required: true, message: this.dmT("ruleGrazingHeadRequired"), trigger: "blur" },
          { validator: this.validateGrazingHeadCount, trigger: "blur" }
        ],
        grazingMethod: [{ required: true, message: this.dmT("ruleGrazingMethodRequired"), trigger: "change" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    formatWithUnit(val, unit) {
      if (val == null || val === "") {
        return this.$t("dataModel.status.dash")
      }
      return `${val}${unit}`
    },
    grazingMethodLabel(val) {
      const item = this.grazingMethodOptions.find((o) => o.value === val)
      return item ? item.label : this.$t("dataModel.status.dash")
    },
    useDateRangeText(row) {
      if (!row || !row.useStartDate || !row.useEndDate) {
        return this.$t("dataModel.status.dash")
      }
      return `${row.useStartDate} ${this.dmT("useRangeSeparator")} ${row.useEndDate}`
    },
    calcActualUseDays(range) {
      if (!range || range.length !== 2 || !range[0] || !range[1]) {
        return null
      }
      const start = new Date(range[0].replace(/-/g, "/"))
      const end = new Date(range[1].replace(/-/g, "/"))
      const diff = Math.round((end.getTime() - start.getTime()) / 86400000)
      return diff + 1
    },
    syncActualUseDays() {
      this.form.actualUseDays = this.calcActualUseDays(this.form.useDateRange)
    },
    validateUsageAreaMu(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      if (Number(value) <= 0) {
        callback(new Error(this.dmT("ruleUsageAreaPositive")))
        return
      }
      if (this.selectedGrasslandAreaMu != null && Number(value) > Number(this.selectedGrasslandAreaMu)) {
        callback(new Error(this.dmT("ruleUsageAreaExceed", { area: this.selectedGrasslandAreaMu })))
        return
      }
      callback()
    },
    validateUseDateRange(rule, value, callback) {
      if (!value || value.length !== 2 || !value[0] || !value[1]) {
        callback(new Error(this.dmT("ruleUseDateRequired")))
        return
      }
      if (value[0] > value[1]) {
        callback(new Error(this.dmT("ruleUseEndBeforeStart")))
        return
      }
      callback()
    },
    validateGrazingHeadCount(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      if (!Number.isInteger(Number(value)) || Number(value) < 1) {
        callback(new Error(this.dmT("ruleGrazingHeadMin")))
        return
      }
      callback()
    },
    buildListQuery() {
      const q = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        keyword: this.queryParams.keyword
      }
      const range = this.queryParams.createDateRange
      if (range && range.length === 2) {
        if (range[0] > range[1]) {
          this.$modal.msgError(this.dmT("ruleReserveDateInvalid"))
          return null
        }
        q.startDate = range[0]
        q.endDate = range[1]
      }
      return q
    },
    getList() {
      const q = this.buildListQuery()
      if (!q) {
        return
      }
      this.loading = true
      listGrasslandUsage(q)
        .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.createDateRange = null
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        grasslandId: undefined,
        pastureId: undefined,
        usageAreaMu: undefined,
        useDateRange: null,
        actualUseDays: undefined,
        grazingHeadCount: undefined,
        grazingMethod: undefined
      }
      this.selectedGrasslandAreaMu = null
    },
    searchGrassland(query) {
      this.grasslandLoading = true
      listGrassland({ pageNum: 1, pageSize: 50, keyword: query || undefined })
        .then((res) => {
          this.grasslandOptions = res.rows || []
        })
        .finally(() => {
          this.grasslandLoading = false
        })
    },
    searchPasture(query) {
      this.pastureLoading = true
      listPasture({ pageNum: 1, pageSize: 50, keyword: query || undefined })
        .then((res) => {
          this.pastureOptions = res.rows || []
        })
        .finally(() => {
          this.pastureLoading = false
        })
    },
    handleGrasslandChange(id) {
      this.loadSelectedGrasslandArea(id)
      if (this.$refs.form) {
        this.$refs.form.validateField("usageAreaMu")
      }
    },
    loadSelectedGrasslandArea(grasslandId) {
      if (!grasslandId) {
        this.selectedGrasslandAreaMu = null
        return
      }
      const item = this.grasslandOptions.find((o) => o.id === grasslandId)
      if (item && item.areaMu != null) {
        this.selectedGrasslandAreaMu = item.areaMu
        return
      }
      getGrassland(grasslandId)
        .then((res) => {
          const g = res.data || {}
          this.ensureGrasslandOption(g.id, g.grasslandName, g.areaMu)
        })
        .catch(() => {})
    },
    ensureGrasslandOption(id, name, areaMu) {
      if (!id) {
        return
      }
      if (!this.grasslandOptions.some((o) => o.id === id)) {
        this.grasslandOptions.push({ id, grasslandName: name, areaMu })
      }
      this.selectedGrasslandAreaMu = areaMu != null ? areaMu : null
    },
    ensurePastureOption(id, name) {
      if (!id) {
        return
      }
      if (!this.pastureOptions.some((o) => o.id === id)) {
        this.pastureOptions.push({ id, pastureName: name })
      }
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.grasslandOptions = []
      this.pastureOptions = []
      this.open = true
      this.$nextTick(() => this.resetForm("form"))
    },
    handleEdit(row) {
      getGrasslandUsage(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.ensureGrasslandOption(data.grasslandId, data.grasslandName, data.grasslandAreaMu)
        this.ensurePastureOption(data.pastureId, data.pastureName)
        const useDateRange =
          data.useStartDate && data.useEndDate ? [data.useStartDate, data.useEndDate] : null
        this.form = {
          id: data.id,
          grasslandId: data.grasslandId,
          pastureId: data.pastureId,
          usageAreaMu: data.usageAreaMu,
          useDateRange,
          actualUseDays: data.actualUseDays,
          grazingHeadCount: data.grazingHeadCount,
          grazingMethod: data.grazingMethod
        }
        this.loadSelectedGrasslandArea(data.grasslandId)
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getGrasslandUsage(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dmT("confirmDelete", { id: row.id }))
        .then(() => delGrasslandUsage(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(() => delGrasslandUsage(this.ids.join(",")))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleExport() {
      const q = this.buildListQuery()
      if (!q) {
        return
      }
      this.download("dataModel/grasslandUsage/export", q, `grassland_usage_${new Date().getTime()}.xlsx`)
    },
    buildPayload() {
      this.syncActualUseDays()
      return {
        grasslandId: this.form.grasslandId,
        pastureId: this.form.pastureId,
        usageAreaMu: this.form.usageAreaMu,
        useStartDate: this.form.useDateRange[0],
        useEndDate: this.form.useDateRange[1],
        grazingHeadCount: this.form.grazingHeadCount,
        grazingMethod: this.form.grazingMethod
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateGrasslandUsage(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addGrasslandUsage(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;
}
.dm-readonly-days {
  flex: 1;
}
.form-hint {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}
</style>
