<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item>
          <template slot="label">{{ dmT("queryAlertDate") }}</template>
          <el-date-picker
            v-model="queryDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="-"
            :start-placeholder="dmT('queryDateRangePh')"
            :end-placeholder="dmT('queryDateRangeEndPh')"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item prop="dataSource">
          <template slot="label">{{ dmT("queryDataSource") }}</template>
          <el-select
            v-model="queryParams.dataSource"
            :placeholder="dmCommon('pleaseSelect')"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in dataSourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="subjectName">
          <template slot="label">{{ dmT("querySubjectName") }}</template>
          <el-input
            v-model="queryParams.subjectName"
            :placeholder="dmT('phSubjectName')"
            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-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('colAlertTime')" prop="alertTime" align="center" width="170" />
        <el-table-column :label="dmT('colDataSource')" align="center" min-width="110">
          <template slot-scope="scope">{{ dataSourceText(scope.row.dataSource) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colStatYear')" prop="statYear" align="center" width="90" />
        <el-table-column :label="dmT('colStatMonth')" align="center" width="80">
          <template slot-scope="scope">{{ formatStatMonth(scope.row.statMonth) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colTownName')" prop="townName" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colVillageName')" prop="villageName" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colSubjectName')" prop="subjectName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colApprovedCarryingCapacity')" align="center" min-width="130">
          <template slot-scope="scope">{{ formatDecimal(scope.row.approvedCarryingCapacity) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colYearEndStockSheepUnit')" align="center" min-width="130">
          <template slot-scope="scope">{{ formatDecimal(scope.row.yearEndStockSheepUnit) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colAlertMessage')" prop="alertMessage" align="center" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column :label="dmCommon('colOp')" align="center" class-name="small-padding fixed-width" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['dataModel:grassLivestockImbalanceWarning:query']"
              type="text"
              size="mini"
              @click="handleView(scope.row)"
            >{{ dmCommon("view") }}</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="dmT('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form class="dm-view-form gliw-form" label-width="160px" size="small">
        <div class="gliw-section-title">{{ dmT("sectionBasic") }}</div>
        <el-form-item :label="dmT('formAlertTime')"><span>{{ viewRow.alertTime || dash }}</span></el-form-item>
        <el-form-item :label="dmT('formDataSource')"><span>{{ dataSourceText(viewRow.dataSource) }}</span></el-form-item>
        <el-form-item :label="dmT('formSourceKey')"><span>{{ viewRow.sourceKey || dash }}</span></el-form-item>
        <el-form-item :label="dmT('formStatYear')"><span>{{ viewRow.statYear || dash }}</span></el-form-item>
        <el-form-item :label="dmT('formStatMonth')"><span>{{ formatStatMonth(viewRow.statMonth) }}</span></el-form-item>
        <el-form-item :label="dmT('formTown')"><span>{{ viewRow.townName || dash }}</span></el-form-item>
        <el-form-item :label="dmT('formVillage')"><span>{{ viewRow.villageName || dash }}</span></el-form-item>
        <el-form-item :label="dmT('formSubjectName')"><span>{{ viewRow.subjectName || dash }}</span></el-form-item>

        <div class="gliw-section-title">{{ dmT("sectionBalance") }}</div>
        <el-form-item :label="dmT('formApprovedCarryingCapacity')">
          <span>{{ formatWithUnit(formatDecimal(viewRow.approvedCarryingCapacity), "unitSheepUnit") }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formYearEndStockSheepUnit')">
          <span>{{ formatWithUnit(formatDecimal(viewRow.yearEndStockSheepUnit), "unitSheepUnit") }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formAlertMessage')">
          <span class="gliw-message-text">{{ viewRow.alertMessage || dash }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewOpen = false">{{ dmCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataModelLocaleMixin from "@/mixins/dataModelLocaleMixin"
import {
  listGrassLivestockImbalanceWarning,
  getGrassLivestockImbalanceWarning
} from "@/api/dataModel/grassLivestockImbalanceWarning"

const DATA_SOURCE_FAMILY_RANCH = "family_ranch"
const DATA_SOURCE_FARMER_HOUSEHOLD = "farmer_household"
const DATA_SOURCE_LARGE_LIVESTOCK_FARMER = "large_livestock_farmer"

export default {
  name: "GrassLivestockImbalanceWarning",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "grassLivestockImbalanceWarning",
      loading: false,
      tableList: [],
      total: 0,
      queryDateRange: null,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        startDate: undefined,
        endDate: undefined,
        dataSource: undefined,
        subjectName: undefined
      },
      viewOpen: false,
      viewRow: {}
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    },
    dataSourceOptions() {
      return [
        { value: DATA_SOURCE_FAMILY_RANCH, label: this.dmT("dataSourceFamilyRanch") },
        { value: DATA_SOURCE_FARMER_HOUSEHOLD, label: this.dmT("dataSourceFarmerHousehold") },
        { value: DATA_SOURCE_LARGE_LIVESTOCK_FARMER, label: this.dmT("dataSourceLargeLivestockFarmer") }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    dataSourceText(code) {
      if (!code) {
        return this.dash
      }
      const hit = this.dataSourceOptions.find((item) => item.value === code)
      return hit ? hit.label : code
    },
    formatStatMonth(month) {
      if (month == null || month === "") {
        return this.dash
      }
      return this.dmT("statMonthLabel", { month })
    },
    formatDecimal(val) {
      if (val == null || val === "") {
        return this.dash
      }
      const n = Number(val)
      if (!Number.isFinite(n)) {
        return this.dash
      }
      return String(val)
    },
    buildListQuery() {
      const q = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      if (this.queryParams.startDate) {
        q.startDate = this.queryParams.startDate
      }
      if (this.queryParams.endDate) {
        q.endDate = this.queryParams.endDate
      }
      if (this.queryParams.dataSource) {
        q.dataSource = this.queryParams.dataSource
      }
      if (this.queryParams.subjectName) {
        q.subjectName = this.queryParams.subjectName
      }
      return q
    },
    checkQueryDateRange() {
      if (this.queryDateRange && this.queryDateRange.length === 2) {
        const [start, end] = this.queryDateRange
        if (start && end && start > end) {
          this.$modal.msgWarning(this.dmT("dateRangeInvalid"))
          return false
        }
      }
      return true
    },
    syncDateRangeToQuery() {
      if (this.queryDateRange && this.queryDateRange.length === 2) {
        this.queryParams.startDate = this.queryDateRange[0]
        this.queryParams.endDate = this.queryDateRange[1]
      } else {
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
      }
    },
    getList() {
      if (!this.checkQueryDateRange()) {
        return
      }
      this.syncDateRangeToQuery()
      this.loading = true
      listGrassLivestockImbalanceWarning(this.buildListQuery())
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryDateRange = null
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        startDate: undefined,
        endDate: undefined,
        dataSource: undefined,
        subjectName: undefined
      }
      this.$nextTick(() => {
        if (this.$refs.queryForm) {
          this.$refs.queryForm.resetFields()
        }
      })
      this.getList()
    },
    handleView(row) {
      getGrassLivestockImbalanceWarning(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    }
  }
}
</script>

<style scoped>
.gliw-section-title {
  margin: 4px 0 12px;
  font-weight: 600;
  color: #303133;
}
.gliw-message-text {
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
