<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">{{ lfT("queryYakNo") }}</template>
          <el-input
            v-model="queryParams.keyword"
            :placeholder="lfT('queryYakNoPh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="assetStatus">
          <template slot="label">{{ lfT("queryAssetStatus") }}</template>
          <el-select v-model="queryParams.assetStatus" :placeholder="lfCommon('pleaseSelect')" clearable style="width: 140px">
            <el-option v-for="item in assetStatusOptions" :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">{{ lfCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ lfCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:yakAsset:sync']"
            type="warning"
            plain
            icon="el-icon-refresh"
            size="mini"
            :loading="syncing"
            @click="handleSync"
          >{{ lfT("btnSync") }}</el-button>
        </el-form-item>
      </el-form>
      <div v-if="lastSyncHint" class="yak-list__sync-hint">{{ lastSyncHint }}</div>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <el-table-column :label="lfT('colYakNo')" prop="yakNo" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="lfT('colPastureName')" prop="pastureName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="lfT('colGender')" prop="gender" align="center" width="70" />
        <el-table-column :label="lfT('colAgeMonths')" align="center" width="80">
          <template slot-scope="scope">{{ formatAgeMonths(scope.row.ageMonths) }}</template>
        </el-table-column>
        <el-table-column :label="lfT('colRealtimeTemp')" align="center" width="100">
          <template slot-scope="scope">{{ formatWithUnit(scope.row.realtimeTemp, lfCommon('unitCelsius')) }}</template>
        </el-table-column>
        <el-table-column :label="lfT('colRealtimeSteps')" align="center" width="100">
          <template slot-scope="scope">{{ formatWithUnit(scope.row.realtimeSteps, lfCommon('unitStep')) }}</template>
        </el-table-column>
        <el-table-column :label="lfT('colAssetStatus')" align="center" width="90">
          <template slot-scope="scope">
            <el-tag :type="assetStatusTagType(scope.row.assetStatus)" size="small">{{ assetStatusLabel(scope.row.assetStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="lfT('colStatusChangeDate')" prop="statusChangeDate" align="center" width="110" />
        <el-table-column :label="lfCommon('colOp')" align="center" width="80" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['dataModel:yakAsset:query']" type="text" size="mini" @click="handleView(scope.row)">{{ lfCommon("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>

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

<script>
import livestockFinanceLocaleMixin from "@/mixins/livestockFinanceLocaleMixin"
import { listYakAsset, syncYakAsset } from "@/api/livestockFinance/yakAsset"
import YakAssetDetailDrawer from "./detailDrawer"

export default {
  name: "YakAsset",
  components: { YakAssetDetailDrawer },
  mixins: [livestockFinanceLocaleMixin],
  data() {
    return {
      lfNs: "yakAsset",
      loading: false,
      syncing: false,
      total: 0,
      tableList: [],
      lastSyncHint: "",
      detailOpen: false,
      detailAssetId: undefined,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined,
        assetStatus: undefined
      }
    }
  },
  computed: {
    assetStatusOptions() {
      return Array.from({ length: 11 }, (_, i) => ({
        value: i + 1,
        label: this.lfT("status" + (i + 1))
      }))
    }
  },
  created() {
    this.getList()
  },
  methods: {
    assetStatusLabel(status) {
      if (status == null || status < 1 || status > 11) {
        return this.lfCommon("dash")
      }
      return this.lfT("status" + status)
    },
    assetStatusTagType(status) {
      if (status === 8 || status === 9 || status === 11) {
        return "danger"
      }
      if (status === 4 || status === 6) {
        return "warning"
      }
      if (status === 1 || status === 2) {
        return "success"
      }
      return "info"
    },
    formatAgeMonths(val) {
      if (val == null || val === "") {
        return this.lfCommon("dash")
      }
      return `${val}${this.lfCommon("unitMonth")}`
    },
    formatWithUnit(val, unit) {
      if (val == null || val === "") {
        return this.lfCommon("dash")
      }
      return `${val}${unit}`
    },
    getList() {
      this.loading = true
      listYakAsset(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.assetStatus = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleView(row) {
      this.detailAssetId = row.id
      this.detailOpen = true
    },
    handleSync() {
      this.runSyncWithLoading(() => syncYakAsset())
        .then((res) => {
          const data = res.data || {}
          const msg = this.lfT("syncSummary", {
            insert: data.insertCount != null ? data.insertCount : 0,
            update: data.updateCount != null ? data.updateCount : 0,
            fail: data.failCount != null ? data.failCount : 0
          })
          this.$modal.msgSuccess(msg)
          if (data.syncTime) {
            this.lastSyncHint = this.lfT("syncTimeHint", { time: this.parseTime(data.syncTime) })
          }
          this.getList()
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped>
.yak-list__sync-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
</style>
