<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('project_name'))">
            <el-input
              v-model="search.project_name"
              :placeholder="$t(key('please_enter'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('batch_no'))">
            <el-input
              v-model="search.batch_no"
              :placeholder="$t(key('please_enter'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onSearch">
              {{ $t(key('search')) }}
            </el-button>
            <el-button icon="el-icon-refresh" @click="onReset">
              {{ $t(key('reset')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <div ref="chart" class="spc-chart-panel" />

    <page-table
      ref="pageTable"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="toolbarButtons"
      :row-buttons="rowButtons"
      :pagination="pagination"
      help-url="/help/quality-management/xbar-s"
      :help-text="$t(ckey('help'))"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    />

  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { useTableButtons } from '@/composables/useTableButtons'
import { i18nMixin } from '@/composables/useI18n'
import { confirmMixin } from '@/composables/useConfirmHandle'
import { getSpcConfigAll, getNodeSubgroupSamplesData } from '@/api/quality-management/spc-sample-report'
import * as echarts from 'echarts'
import PageTable from '@/components/page-table'

function readList (res) {
  if (Array.isArray(res)) return { list: res, total: res.length }
  const data = res && res.data ? res.data : res
  if (Array.isArray(data)) return { list: data, total: data.length }
  const list = (data && (data.list || data.rows || data.records || data.data)) || []
  const total = data && (data.total || data.count || list.length)
  return { list: Array.isArray(list) ? list : [], total: Number(total) || 0 }
}

export default {
  name: 'quality-management-xbar-s',
  components: { PageTable },
  mixins: [i18nMixin('page.quality_management.xbar_s'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: {"project_name":"","batch_no":""},
      pagination: { current: 1, size: 10, total: 0 },
      formData: {},
      rules: {

      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formCols: [

      ],
      chart: null
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'subgroup_id', label: this.key('subgroup_id'), minWidth: 130 },
      { prop: 'sampling_time', label: this.key('sampling_time'), minWidth: 170 },
      { prop: 'sample_value', label: this.key('sample_value'), minWidth: 130 },
      { prop: 'batch_no', label: this.key('batch_no'), minWidth: 130 },
      { prop: 'result', label: this.key('result'), minWidth: 130 },
      { prop: 'remark', label: this.key('remark'), minWidth: 130 }
    ])
    const btns = useTableButtons({
      toolbar: [],
      row: []
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.loadSpcConfig()
    this.fetchData()
  },
  mounted () {
    this.chart = echarts.init(this.$refs.chart)
  },
  beforeDestroy () {
    if (this.chart) this.chart.dispose()
  },
  methods: {
    async loadSpcConfig () {
      try {
        await getSpcConfigAll({})
      } catch (error) {
        // 配置列表失败不阻断报表查询。
      }
    },
    async fetchData () {
      this.loading = true
      try {
        const params = {
          ...this.search,
          page_no: this.pagination.current,
          page_size: this.pagination.size,
          page: this.pagination.current,
          size: this.pagination.size
        }
        const res = await getNodeSubgroupSamplesData({ chart_type: 'XBar-S', ...params })
        const { list, total } = readList(res)
        this.tableData = list
        this.pagination.total = total
        this.renderChart(list)
      } finally {
        this.loading = false
      }
    },
    renderChart (rows) {
      if (!this.chart) return
      const labels = rows.map((row, index) => row.sampling_time || row.create_time || String(index + 1))
      const values = rows.map(row => Number(row.sample_value || row.value || row.result || 0))
      this.chart.setOption({
        tooltip: { trigger: 'axis' },
        grid: { left: 48, right: 24, top: 32, bottom: 40 },
        xAxis: { type: 'category', data: labels },
        yAxis: { type: 'value' },
        series: [{ type: 'line', smooth: true, data: values }]
      })
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = {"project_name":"","batch_no":""}
      this.pagination.current = 1
      this.fetchData()
    },
    onPageChange (page) {
      this.pagination.current = page.current
      this.pagination.size = page.size
      this.fetchData()
    },
    onSelect (rows) {
      this.selectedRows = rows
    }
  }
}
</script>

<style scoped>
.search-bar {
  padding: 10px 0;
}
.spc-chart-panel {
  height: 320px;
  margin-bottom: 12px;
  border: 1px solid #ebeef5;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
