<template>
  <el-drawer
    :title="lfT('detailTitle')"
    :visible.sync="drawerVisible"
    size="88%"
    append-to-body
    destroy-on-close
    @close="handleClose"
  >
    <div v-loading="loading" class="yak-detail">
      <el-card v-if="asset" shadow="never" class="yak-detail__summary">
        <el-row :gutter="16">
          <el-col :span="6"><span class="yak-detail__label">{{ lfT("fieldYakNo") }}：</span>{{ asset.yakNo || dash }}</el-col>
          <el-col :span="6"><span class="yak-detail__label">{{ lfT("fieldPastureName") }}：</span>{{ asset.pastureName || dash }}</el-col>
          <el-col :span="6"><span class="yak-detail__label">{{ lfT("fieldAssetStatus") }}：</span>{{ assetStatusLabel(asset.assetStatus) }}</el-col>
          <el-col :span="3"><span class="yak-detail__label">{{ lfT("fieldGender") }}：</span>{{ asset.gender || dash }}</el-col>
          <el-col :span="3"><span class="yak-detail__label">{{ lfT("fieldAgeMonths") }}：</span>{{ formatAgeMonths(asset.ageMonths) }}</el-col>
        </el-row>
        <el-row v-if="asset.earTagNumber" :gutter="16" class="yak-detail__summary-extra">
          <el-col :span="6"><span class="yak-detail__label">{{ lfT("fieldEarTagNumber") }}：</span>{{ asset.earTagNumber }}</el-col>
        </el-row>
        <div v-if="asset.lastSyncTime" class="yak-detail__sync-hint">{{ lfT("syncTimeHint", { time: parseTime(asset.lastSyncTime) }) }}</div>
      </el-card>

      <el-card shadow="never" class="yak-detail__block">
        <div slot="header">{{ lfT("sectionBasic") }}</div>
        <el-descriptions v-if="asset" :column="3" border size="small">
          <el-descriptions-item :label="lfT('fieldYakNo')">{{ asset.yakNo || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldEarTagNumber')">{{ asset.earTagNumber || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldPastureName')">{{ asset.pastureName || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldBatchNo')">{{ asset.batchNo || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldEnclosureName')">{{ asset.enclosureName || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldEntryCycle')">{{ asset.entryCycle || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldGender')">{{ asset.gender || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldCattleVariety')">{{ asset.cattleVariety || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldBirthDate')">{{ asset.birthDate || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldAgeMonths')">{{ formatAgeMonths(asset.ageMonths) }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldEntryDate')">{{ asset.entryDate || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldEntryWeight')">{{ formatWithUnit(asset.entryWeightKg, lfCommon('unitKg')) }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldSource')">{{ asset.source || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldBreedingMethod')">{{ asset.breedingMethod || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldAssetStatus')">{{ assetStatusLabel(asset.assetStatus) }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldStatusChangeDate')">{{ asset.statusChangeDate || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldStatusChangeReason')">{{ asset.statusChangeReason || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldPenLocation')">{{ asset.penLocation || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldExpectedOutDate')">{{ asset.expectedOutDate || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldSupplementPlan')">{{ asset.supplementPlan || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldRegistrant')">{{ asset.registrant || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldLastSyncTime')">{{ asset.lastSyncTime ? parseTime(asset.lastSyncTime) : dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldRemark')" :span="3">{{ asset.remark || dash }}</el-descriptions-item>
          <el-descriptions-item v-if="asset.cattlePicture" :label="lfT('fieldCattlePicture')" :span="3">
            <el-image
              :src="asset.cattlePicture"
              fit="contain"
              class="yak-detail__picture"
              :preview-src-list="[asset.cattlePicture]"
            />
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card shadow="never" class="yak-detail__block">
        <div slot="header">{{ lfT("sectionPedigree") }}</div>
        <el-descriptions v-if="asset" :column="2" border size="small">
          <el-descriptions-item :label="lfT('fieldYakNo')">{{ asset.yakNo || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldFatherYakNo')">
            <el-button v-if="asset.fatherYakNo" type="text" @click="jumpPedigree(asset.fatherYakNo)">{{ asset.fatherYakNo }}</el-button>
            <span v-else>{{ dash }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldMotherYakNo')">
            <el-button v-if="asset.motherYakNo" type="text" @click="jumpPedigree(asset.motherYakNo)">{{ asset.motherYakNo }}</el-button>
            <span v-else>{{ dash }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card shadow="never" class="yak-detail__block">
        <div slot="header">{{ lfT("sectionPhysio") }}</div>
        <el-descriptions v-if="asset" :column="3" border size="small">
          <el-descriptions-item :label="lfT('fieldRealtimeTemp')">{{ formatWithUnit(asset.realtimeTemp, lfCommon('unitCelsius')) }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldRealtimeSteps')">{{ formatWithUnit(asset.realtimeSteps, lfCommon('unitStep')) }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldEnvTemp')">{{ formatWithUnit(asset.envTemp, lfCommon('unitCelsius')) }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldLocation')" :span="2">{{ asset.location || dash }}</el-descriptions-item>
          <el-descriptions-item :label="lfT('fieldPhysioCollectTime')">{{ asset.physioCollectTime ? parseTime(asset.physioCollectTime) : dash }}</el-descriptions-item>
        </el-descriptions>
        <p class="yak-detail__chart-title">{{ lfT("sectionPhysioChart") }}</p>
        <div ref="physioChart" class="yak-detail__chart" />
      </el-card>

      <el-card shadow="never" class="yak-detail__block">
        <div slot="header" class="yak-detail__growth-header">
          <span>{{ lfT("sectionGrowth") }}</span>
          <span class="yak-detail__growth-tools">
            <el-radio-group v-model="growthMode" size="mini" @change="onGrowthModeChange">
              <el-radio-button label="list">{{ lfT("growthModeList") }}</el-radio-button>
              <el-radio-button label="chart">{{ lfT("growthModeChart") }}</el-radio-button>
            </el-radio-group>
            <el-select
              v-if="growthMode === 'chart'"
              v-model="growthMetric"
              size="mini"
              style="width: 110px; margin-left: 8px"
              @change="loadGrowthChart"
            >
              <el-option v-for="m in growthMetricOptions" :key="m.value" :label="m.label" :value="m.value" />
            </el-select>
          </span>
        </div>
        <el-table v-show="growthMode === 'list'" :data="displayGrowthRecords" border size="small" max-height="280">
          <el-table-column :label="lfT('colDayAge')" prop="dayAge" align="center" width="80" />
          <el-table-column :label="lfT('colWeight')" align="center" width="90">
            <template slot-scope="scope">{{ formatWithUnit(scope.row.weightKg, lfCommon('unitKg')) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colHeight')" align="center" width="90">
            <template slot-scope="scope">{{ formatWithUnit(scope.row.heightCm, lfCommon('unitCm')) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colChest')" align="center" width="90">
            <template slot-scope="scope">{{ formatWithUnit(scope.row.chestCm, lfCommon('unitCm')) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colLength')" align="center" width="90">
            <template slot-scope="scope">{{ formatWithUnit(scope.row.lengthCm, lfCommon('unitCm')) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colCollectTime')" align="center" min-width="150">
            <template slot-scope="scope">{{ scope.row.collectTime ? parseTime(scope.row.collectTime) : dash }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colDataKind')" align="center" width="80">
            <template slot-scope="scope">{{ dataKindLabel(scope.row.dataKind) }}</template>
          </el-table-column>
        </el-table>
        <div v-show="growthMode === 'chart'" ref="growthChart" class="yak-detail__chart" />
      </el-card>

      <el-card shadow="never" class="yak-detail__block">
        <div slot="header">{{ lfT("sectionReproduction") }}</div>
        <el-table :data="reproductionRecords" border size="small" max-height="240">
          <el-table-column :label="lfT('colDayAge')" prop="dayAge" align="center"  />
          <el-table-column :label="lfT('colParity')" prop="parity" align="center" />
          <el-table-column :label="lfT('colCalvingInterval')" align="center" >
            <template slot-scope="scope">{{ formatWithUnit(scope.row.calvingIntervalDays, lfCommon('unitDay')) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colCalfCount')" align="center" >
            <template slot-scope="scope">{{ formatWithUnit(scope.row.calfCount, lfCommon('unitHead')) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colCalfSurvivalRate')" align="center" >
            <template slot-scope="scope">{{ formatRate(scope.row.calfSurvivalRate) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colCalfBirthWeight')" align="center" >
            <template slot-scope="scope">{{ formatWithUnit(scope.row.calfBirthWeightKg, lfCommon('unitKg')) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colDystocia')" align="center" >
            <template slot-scope="scope">{{ dystociaLabel(scope.row.dystociaFlag) }}</template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card shadow="never" class="yak-detail__block">
        <div slot="header">{{ lfT("sectionFeeding") }}</div>
        <el-table :data="feedingRecords" border size="small" max-height="240">
          <el-table-column :label="lfT('colStartDayAge')" prop="startDayAge" align="center" width="90" />
          <el-table-column :label="lfT('colEndDayAge')" prop="endDayAge" align="center" width="90" />
          <el-table-column :label="lfT('colDailySupplement')" align="center" width="110">
            <template slot-scope="scope">{{ formatWithUnit(scope.row.dailySupplementKg, lfCommon('unitKg')) }}</template>
          </el-table-column>
          <el-table-column :label="lfT('colFeedType')" prop="feedType" align="center" min-width="120" :show-overflow-tooltip="true" />
        </el-table>
      </el-card>

      <el-card shadow="never" class="yak-detail__block">
        <div slot="header">{{ lfT("sectionPen") }}</div>
        <el-table :data="penTableRows" border size="small">
          <el-table-column :label="lfT('colEnclosureName')" prop="enclosureName" align="center" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column :label="lfT('colPenLocation')" prop="penLocation" align="center" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column :label="lfT('fieldYakNo')" prop="yakNo" align="center" min-width="120" />
        </el-table>
      </el-card>

      <el-card shadow="never" class="yak-detail__block">
        <div slot="header">{{ lfT("sectionBatch") }}</div>
        <el-table :data="batchTableRows" border size="small">
          <el-table-column :label="lfT('fieldBatchNo')" prop="batchNo" align="center" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column :label="lfT('colEntryCycle')" prop="entryCycle" align="center" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column :label="lfT('fieldYakNo')" prop="yakNo" align="center" min-width="120" />
        </el-table>
      </el-card>
    </div>
  </el-drawer>
</template>

<script>
import * as echarts from "echarts"
require("echarts/theme/macarons")
import livestockFinanceLocaleMixin from "@/mixins/livestockFinanceLocaleMixin"
import { getYakAsset, getYakAssetByNo, getYakPhysioChart, getYakGrowthChart } from "@/api/livestockFinance/yakAsset"

export default {
  name: "YakAssetDetailDrawer",
  mixins: [livestockFinanceLocaleMixin],
  props: {
    visible: { type: Boolean, default: false },
    assetId: { type: [Number, String], default: undefined }
  },
  data() {
    return {
      lfNs: "yakAsset",
      loading: false,
      asset: null,
      growthRecords: [],
      reproductionRecords: [],
      feedingRecords: [],
      growthMode: "list",
      growthMetric: "weight",
      physioChartInst: null,
      growthChartInst: null
    }
  },
  computed: {
    drawerVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit("update:visible", val)
      }
    },
    dash() {
      return this.lfCommon("dash")
    },
    growthMetricOptions() {
      return [
        { value: "weight", label: this.lfT("metricWeight") },
        { value: "height", label: this.lfT("metricHeight") },
        { value: "chest", label: this.lfT("metricChest") },
        { value: "length", label: this.lfT("metricLength") }
      ]
    },
    penTableRows() {
      if (!this.asset) {
        return []
      }
      return [{
        enclosureName: this.asset.enclosureName,
        penLocation: this.asset.penLocation,
        yakNo: this.asset.yakNo
      }]
    },
    batchTableRows() {
      if (!this.asset) {
        return []
      }
      return [{
        batchNo: this.asset.batchNo,
        entryCycle: this.asset.entryCycle,
        yakNo: this.asset.yakNo
      }]
    },
    displayGrowthRecords() {
      return (this.growthRecords || []).filter((row) => this.hasDayAge(row))
    }
  },
  watch: {
    visible(val) {
      if (val && this.assetId) {
        this.loadDetail(this.assetId)
      }
    },
    assetId(id) {
      if (this.visible && id) {
        this.loadDetail(id)
      }
    }
  },
  beforeDestroy() {
    this.disposeCharts()
    window.removeEventListener("resize", this.resizeCharts)
  },
  methods: {
    assetStatusLabel(status) {
      if (status == null || status < 1 || status > 4) {
        return this.dash
      }
      return this.lfT("status" + status)
    },
    dataKindLabel(kind) {
      if (kind === 1) {
        return this.lfT("dataKindActual")
      }
      if (kind === 2) {
        return this.lfT("dataKindForecast")
      }
      return this.dash
    },
    dystociaLabel(flag) {
      if (flag === "1") {
        return this.lfCommon("yes")
      }
      if (flag === "0") {
        return this.lfCommon("no")
      }
      return this.dash
    },
    formatAgeMonths(val) {
      if (val == null || val === "") {
        return this.dash
      }
      return `${val}${this.lfCommon("unitMonth")}`
    },
    formatWithUnit(val, unit) {
      if (val == null || val === "") {
        return this.dash
      }
      return `${val}${unit}`
    },
    formatRate(val) {
      if (val == null || val === "") {
        return this.dash
      }
      const n = Number(val)
      if (isNaN(n)) {
        return this.dash
      }
      return `${(n * 100).toFixed(2)}%`
    },
    loadDetail(id) {
      this.loading = true
      this.growthMode = "list"
      getYakAsset(id)
        .then((res) => {
          const data = res.data || {}
          this.asset = data.asset || null
          this.growthRecords = data.growthRecords || []
          this.reproductionRecords = data.reproductionRecords || []
          this.feedingRecords = data.feedingRecords || []
          this.$nextTick(() => {
            this.loadPhysioChart()
            window.addEventListener("resize", this.resizeCharts)
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    jumpPedigree(yakNo) {
      getYakAssetByNo(yakNo)
        .then((res) => {
          const data = res.data || {}
          const asset = data.asset
          if (!asset || !asset.id) {
            this.$modal.msgWarning(this.lfT("pedigreeNotFound", { no: yakNo }))
            return
          }
          this.loadDetail(asset.id)
        })
        .catch(() => {
          this.$modal.msgWarning(this.lfT("pedigreeNotFound", { no: yakNo }))
        })
    },
    loadPhysioChart() {
      if (!this.asset || !this.asset.id) {
        return
      }
      getYakPhysioChart(this.asset.id, { days: 30 }).then((res) => {
        const list = res.data || []
        this.renderPhysioChart(list)
      })
    },
    loadGrowthChart() {
      if (!this.asset || !this.asset.id || this.growthMode !== "chart") {
        return
      }
      getYakGrowthChart(this.asset.id, { metric: this.growthMetric }).then((res) => {
        this.renderGrowthChart(res.data || {})
      })
    },
    onGrowthModeChange(mode) {
      if (mode === "chart") {
        this.$nextTick(() => this.loadGrowthChart())
      }
    },
    hasDayAge(item) {
      return item && item.dayAge != null && item.dayAge !== ""
    },
    chartPointsToSeries(points) {
      const sorted = (points || [])
        .filter((p) => this.hasDayAge(p))
        .slice()
        .sort((a, b) => a.dayAge - b.dayAge)
      return {
        x: sorted.map((p) => String(p.dayAge)),
        y: sorted.map((p) => (p.value != null ? Number(p.value) : null))
      }
    },
    renderPhysioChart(list) {
      const dom = this.$refs.physioChart
      if (!dom) {
        return
      }
      if (this.physioChartInst) {
        this.physioChartInst.dispose()
      }
      const sorted = (list || []).slice().sort((a, b) => new Date(a.collectTime) - new Date(b.collectTime))
      const times = sorted.map((p) => (p.collectTime ? this.parseTime(p.collectTime, "{m}-{d} {h}:{i}") : ""))
      this.physioChartInst = echarts.init(dom, "macarons")
      this.physioChartInst.setOption({
        tooltip: { trigger: "axis" },
        legend: { data: [this.lfT("chartBodyTemp"), this.lfT("chartSteps"), this.lfT("chartEnvTemp")] },
        grid: { left: "3%", right: "4%", bottom: "12%", top: 40, containLabel: true },
        xAxis: { type: "category", boundaryGap: false, data: times },
        yAxis: [
          { type: "value", name: this.lfCommon("unitCelsius"), position: "left" },
          { type: "value", name: this.lfCommon("unitStep"), position: "right" }
        ],
        series: [
          {
            name: this.lfT("chartBodyTemp"),
            type: "line",
            smooth: true,
            data: sorted.map((p) => (p.bodyTemp != null ? Number(p.bodyTemp) : null))
          },
          {
            name: this.lfT("chartSteps"),
            type: "line",
            smooth: true,
            yAxisIndex: 1,
            data: sorted.map((p) => (p.steps != null ? p.steps : null))
          },
          {
            name: this.lfT("chartEnvTemp"),
            type: "line",
            smooth: true,
            data: sorted.map((p) => (p.envTemp != null ? Number(p.envTemp) : null))
          }
        ]
      })
    },
    renderGrowthChart(data) {
      const dom = this.$refs.growthChart
      if (!dom) {
        return
      }
      if (this.growthChartInst) {
        this.growthChartInst.dispose()
      }
      const actual = this.chartPointsToSeries(data.actual)
      const forecast = this.chartPointsToSeries(data.forecast)
      const xSet = new Set([...actual.x, ...forecast.x])
      const xAxis = Array.from(xSet).sort((a, b) => Number(a) - Number(b))
      const mapSeries = (series, xs) => {
        const map = {}
        series.x.forEach((k, i) => {
          map[k] = series.y[i]
        })
        return xs.map((k) => (map[k] != null ? map[k] : null))
      }
      this.growthChartInst = echarts.init(dom, "macarons")
      this.growthChartInst.setOption({
        tooltip: { trigger: "axis" },
        legend: { data: [this.lfT("seriesActual"), this.lfT("seriesForecast")] },
        grid: { left: "3%", right: "4%", bottom: "12%", top: 40, containLabel: true },
        xAxis: { type: "category", name: this.lfCommon("unitDay"), data: xAxis },
        yAxis: { type: "value" },
        series: [
          {
            name: this.lfT("seriesActual"),
            type: "line",
            smooth: true,
            data: mapSeries(actual, xAxis),
            itemStyle: { color: "#409EFF" }
          },
          {
            name: this.lfT("seriesForecast"),
            type: "line",
            smooth: true,
            lineStyle: { type: "dashed" },
            data: mapSeries(forecast, xAxis),
            itemStyle: { color: "#E6A23C" }
          }
        ]
      })
    },
    resizeCharts() {
      this.physioChartInst && this.physioChartInst.resize()
      this.growthChartInst && this.growthChartInst.resize()
    },
    disposeCharts() {
      if (this.physioChartInst) {
        this.physioChartInst.dispose()
        this.physioChartInst = null
      }
      if (this.growthChartInst) {
        this.growthChartInst.dispose()
        this.growthChartInst = null
      }
    },
    handleClose() {
      this.disposeCharts()
      window.removeEventListener("resize", this.resizeCharts)
      this.asset = null
      this.growthRecords = []
      this.reproductionRecords = []
      this.feedingRecords = []
    }
  }
}
</script>

<style scoped>
.yak-detail__summary {
  margin-bottom: 12px;
}
.yak-detail__label {
  color: #909399;
}
.yak-detail__summary-extra {
  margin-top: 8px;
}
.yak-detail__picture {
  width: 120px;
  height: 120px;
}
.yak-detail__sync-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
.yak-detail__block {
  margin-bottom: 12px;
}
.yak-detail__chart-title {
  margin: 12px 0 8px;
  font-size: 13px;
  color: #606266;
}
.yak-detail__chart {
  width: 100%;
  height: 320px;
}
.yak-detail__growth-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.yak-detail__growth-tools {
  font-weight: normal;
}
</style>
