<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form ref="searchForm" :inline="true" :model="search" size="mini">
          <el-form-item :label="$t(key('batch_no'))" prop="batch">
            <el-input
              v-model="search.batch"
              :placeholder="$t(key('enter_batch_no'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('semi_finished_id'))" prop="item_id">
            <el-input
              v-model="search.item_id"
              :placeholder="$t(key('enter_semi_finished_id'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('workingsubclass'))" prop="workingsubclass">
            <el-select
              v-model="search.workingsubclass"
              :placeholder="$t(key('select_workingsubclass'))"
              clearable
              filterable
              style="width:200px"
              @focus="loadProcessOptions"
            >
              <el-option
                v-for="item in processOptions"
                :key="item.code || item.name"
                :label="item.name || item.code"
                :value="item.code || item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('finish_time'))" prop="start_time">
            <el-date-picker
              v-model="search.start_time"
              type="daterange"
              range-separator="-"
              :start-placeholder="$t(key('start_time'))"
              :end-placeholder="$t(key('end_time'))"
              value-format="yyyy-MM-dd"
              style="width:330px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" :disabled="loading" @click="onSearch">
              {{ $t(key('query')) }}
            </el-button>
            <el-button icon="el-icon-refresh" :disabled="loading" @click="onReset">
              {{ $t(key('reset')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <page-table
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="[]"
      :row-buttons="[]"
      :pagination="pagination"
      :table-attrs="{ size: 'mini', rowKey: 'id', highlightCurrentRow: true }"
      auto-height
      @page-change="onPageChange"
    >
      <template #col-last_status="{ row }">
        <el-tag :type="Number(row.last_status) === 0 ? 'danger' : 'success'" size="mini">
          {{ Number(row.last_status) === 0 ? $t(key('finished')) : $t(key('status_unused')) }}
        </el-tag>
      </template>
      <template #empty>
        <el-empty :description="$t('暂无数据')" :image-size="80" />
      </template>
    </page-table>
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { i18nMixin } from '@/composables/useI18n'
import PageTable from '@/components/page-table'
import { getWipDataList } from '@/api/planning-production/material-monitoring'
import { getWorkingsubclassAll } from '@/api/production-master-data/process-step'

export default {
  name: 'planning-production-material-monitoring',
  components: { PageTable },
  mixins: [i18nMixin('page.planning_production.production_monitoring.material_monitoring')],
  data () {
    return {
      loading: false,
      search: {
        batch: '',
        item_id: '',
        workingsubclass: '',
        start_time: []
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      processOptions: []
    }
  },
  computed: {
    columns () {
      return useTableColumns([
        { prop: 'batch', label: this.key('batch_no'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'item_id', label: this.key('semi_finished_id'), minWidth: 160, showOverflowTooltip: true },
        { prop: 'item_code', label: this.key('semi_product_code'), minWidth: 170, showOverflowTooltip: true },
        { prop: 'item_quantity', label: this.key('output_quantity'), minWidth: 120 },
        { prop: 'workingsubclass', label: this.key('workingsubclass'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'device_code', label: this.key('production_device'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'last_status', label: this.key('last_status'), width: 120, slot: 'last_status' },
        { prop: 'finish_time', label: this.key('finish_time'), minWidth: 170, showOverflowTooltip: true }
      ], {
        selectionWidth: 0,
        indexWidth: 55
      })
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    normalizePayload (res) {
      if (res && res.code !== undefined && res.data !== undefined) return res.data
      return res || {}
    },
    normalizeList (res) {
      const payload = this.normalizePayload(res)
      if (Array.isArray(payload)) return payload
      if (Array.isArray(payload.data)) return payload.data
      if (payload.data && Array.isArray(payload.data.data)) return payload.data.data
      return []
    },
    normalizePage (res) {
      const payload = this.normalizePayload(res)
      if (Array.isArray(payload)) return { data: payload, count: payload.length }
      if (payload.data && !Array.isArray(payload.data)) {
        return {
          data: Array.isArray(payload.data.data) ? payload.data.data : [],
          count: Number(payload.data.count || 0)
        }
      }
      return {
        data: Array.isArray(payload.data) ? payload.data : [],
        count: Number(payload.count || 0)
      }
    },
    searchParams () {
      const params = {
        batch: this.search.batch || undefined,
        item_id: this.search.item_id || undefined,
        workingsubclass: this.search.workingsubclass || undefined
      }
      if (Array.isArray(this.search.start_time) && this.search.start_time.length === 2) {
        params.start_time = [
          `${this.search.start_time[0]} 00:00:00`,
          `${this.search.start_time[1]} 23:59:59`
        ]
      }
      return params
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getWipDataList({
          ...this.searchParams(),
          page_no: this.pagination.current,
          page_size: this.pagination.size
        })
        const payload = this.normalizePage(res)
        this.tableData = payload.data
        this.pagination.total = payload.count
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = {
        batch: '',
        item_id: '',
        workingsubclass: '',
        start_time: []
      }
      this.onSearch()
    },
    onPageChange (pagination) {
      this.pagination = pagination
      this.fetchData()
    },
    async loadProcessOptions () {
      if (this.processOptions.length) return
      const res = await getWorkingsubclassAll({})
      this.processOptions = this.normalizeList(res)
    }
  }
}
</script>
