<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="pastureId">
          <template slot="label">{{ dmT("queryPasture") }}</template>
          <el-select
            v-model="queryParams.pastureId"
            :placeholder="dmCommon('pleaseSelect')"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in pastureOptions"
              :key="item.id"
              :label="item.pastureName"
              :value="item.id"
            />
          </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:yakDiseaseWarning:sync']"
            type="warning"
            plain
            icon="el-icon-refresh"
            size="mini"
            :loading="syncing"
            @click="handleSync"
          >{{ dmT("btnSync") }}</el-button>
        </el-form-item>
      </el-form>
      <div v-if="lastSyncHint" class="yak-warning__sync-hint">{{ lastSyncHint }}</div>
    </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('colYakNo')" prop="yakNo" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colPastureName')" prop="pastureName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <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:yakDiseaseWarning: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-descriptions v-if="viewRow.id" :column="1" border size="small">
        <el-descriptions-item :label="dmT('viewYakNo')">
          <span>{{ viewRow.yakNo || dash }}</span>
          <el-button
            v-if="viewRow.yakAssetId"
            type="text"
            size="mini"
            class="yak-warning__asset-link"
            @click="openYakAsset(viewRow.yakAssetId)"
          >{{ dmT("actionViewAsset") }}</el-button>
        </el-descriptions-item>
        <el-descriptions-item :label="dmT('viewAlertTime')">{{ viewRow.alertTime || dash }}</el-descriptions-item>
        <el-descriptions-item :label="dmT('viewPastureName')">{{ viewRow.pastureName || dash }}</el-descriptions-item>
        <el-descriptions-item :label="dmT('viewAlertMessage')">
          <span class="yak-warning__message-text">{{ viewRow.alertMessage || dash }}</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="viewRow.warningType != null" :label="dmT('viewWarningType')">
          {{ warningTypeText(viewRow.warningType) }}
        </el-descriptions-item>
        <el-descriptions-item v-if="viewRow.measuredValue" :label="dmT('viewMeasuredValue')">{{ viewRow.measuredValue }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.referenceRange" :label="dmT('viewReferenceRange')">{{ viewRow.referenceRange }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.deviceNo" :label="dmT('viewDeviceNo')">{{ viewRow.deviceNo }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.collectTime" :label="dmT('viewCollectTime')">{{ viewRow.collectTime }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.dataSource" :label="dmT('viewDataSource')">{{ viewRow.dataSource }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.lastSyncTime" :label="dmT('viewLastSyncTime')">{{ viewRow.lastSyncTime }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.createTime" :label="dmT('viewCreateTime')">{{ viewRow.createTime }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.updateTime" :label="dmT('viewUpdateTime')">{{ viewRow.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewOpen = false">{{ dmCommon("close") }}</el-button>
      </div>
    </el-dialog>

    <yak-asset-detail-drawer :visible.sync="assetDrawerOpen" :asset-id="assetDrawerId" />
  </div>
</template>

<script>
import dataModelLocaleMixin from "@/mixins/dataModelLocaleMixin"
import { listPasture } from "@/api/dataModel/pasture"
import {
  listYakDiseaseWarning,
  getYakDiseaseWarning,
  syncYakDiseaseWarning
} from "@/api/dataModel/yakDiseaseWarning"
import YakAssetDetailDrawer from "@/views/livestockFinance/yakAsset/detailDrawer"

export default {
  name: "DataModelYakDiseaseWarning",
  components: { YakAssetDetailDrawer },
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "yakDiseaseWarning",
      loading: false,
      syncing: false,
      tableList: [],
      total: 0,
      queryDateRange: null,
      pastureOptions: [],
      lastSyncHint: "",
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        startDate: undefined,
        endDate: undefined,
        pastureId: undefined
      },
      viewOpen: false,
      viewRow: {},
      assetDrawerOpen: false,
      assetDrawerId: undefined
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    }
  },
  created() {
    this.loadPastureOptions()
    this.getList()
  },
  methods: {
    loadPastureOptions() {
      listPasture({ pageNum: 1, pageSize: 500 })
        .then((res) => {
          this.pastureOptions = res.rows || []
        })
        .catch(() => {
          this.pastureOptions = []
        })
    },
    getList() {
      if (!this.checkQueryDateRange()) {
        return
      }
      this.syncDateRangeToQuery()
      this.loading = true
      listYakDiseaseWarning(this.queryParams)
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    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
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryDateRange = null
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        startDate: undefined,
        endDate: undefined,
        pastureId: undefined
      }
      this.$nextTick(() => {
        if (this.$refs.queryForm) {
          this.$refs.queryForm.resetFields()
        }
      })
      this.getList()
    },
    handleView(row) {
      getYakDiseaseWarning(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    openYakAsset(assetId) {
      this.assetDrawerId = assetId
      this.assetDrawerOpen = true
    },
    handleSync() {
      this.runSyncWithLoading(() => syncYakDiseaseWarning())
        .then((res) => {
          const data = res.data || {}
          this.$modal.msgSuccess(
            this.dmT("syncSummary", {
              insert: data.insertCount != null ? data.insertCount : 0,
              update: data.updateCount != null ? data.updateCount : 0,
              fail: data.failCount != null ? data.failCount : 0
            })
          )
          if (data.syncTime) {
            this.lastSyncHint = this.dmT("syncTimeHint", { time: this.parseTime(data.syncTime) })
          }
          this.getList()
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
.yak-warning__sync-hint {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.yak-warning__message-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}

.yak-warning__asset-link {
  margin-left: 8px;
}
</style>
