<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('device_category'))">
            <el-select
              v-model="search.device_category_id"
              :placeholder="$t(key('select_device_category'))"
              clearable
              filterable
              :loading="deviceCategoryLoading"
              style="width:200px"
              @focus="loadDeviceCategories"
            >
              <el-option
                v-for="item in deviceCategoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('query_type'))">
            <el-select
              v-model="search.type"
              :placeholder="$t(key('select_query_type'))"
              clearable
              style="width:200px"
            >
              <el-option :label="$t(key('type_error'))" value="ERR" />
              <el-option :label="$t(key('type_ng'))" value="NG" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('ng_code'))">
            <el-input
              v-model="search.number"
              :placeholder="$t(key('enter_ng_code'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('ng_name'))">
            <el-input
              v-model="search.explain"
              :placeholder="$t(key('enter_ng_name'))"
              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>

    <page-table
      ref="pageTable"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="toolbarButtons"
      :row-buttons="rowButtons"
      :pagination="pagination"
      help-url="/help/product-ng-info"
      :help-text="$t(ckey('help'))"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    >
      <template #col-type="{ row }">
        <span>{{ typeText(row.type) }}</span>
      </template>
    </page-table>

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :width="'35%'"
      :form-cols="formCols"
      :form-data="formData"
      :rules="rules"
      :label-width="'120px'"
      :submitting="submitting"
      :confirm-text="key('confirm')"
      :cancel-text="key('cancel')"
      @submit="onDialogSubmit"
      @close="onDialogClose"
    />

    <product-ng-info-import-dialog
      :visible.sync="importVisible"
      @saved="onImportSaved"
    />
  </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 {
  getProductNgInfoList,
  createProductNgInfo,
  editProductNgInfo,
  deleteProductNgInfo,
  productNgInfoExportTask
} from '@/api/production-master-data/product-ng-info'
import { getDeviceCategoryAll } from '@/api/production-master-data/device-category'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'
import ProductNgInfoImportDialog from './components/ImportDialog/index.vue'

export default {
  name: 'production-master-data-product-ng-info',
  components: { PageTable, PageDialogForm, ProductNgInfoImportDialog },
  mixins: [i18nMixin('page.production_master_data.product_model.product_ng_info'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: null,
      handleType: 'create',
      importVisible: false,
      search: { device_category_id: '', type: '', number: '', explain: '' },
      pagination: { current: 1, size: 10, total: 0 },
      deviceCategoryLoading: false,
      deviceCategoryOptions: [],
      formData: { device_category_id: '', type: '', number: '', explain: '', note: '' },
      rules: {
        device_category_id: [
          { required: true, message: this.key('select_device_category'), trigger: 'change' }
        ],
        type: [
          { required: true, message: this.key('select_type'), trigger: 'change' }
        ],
        number: [
          { required: true, message: this.key('enter_ng_code'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('remark_length'), trigger: 'blur' }
        ],
        explain: [
          { required: true, message: this.key('enter_ng_name'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('remark_length'), trigger: 'blur' }
        ]
      },
      formCols: [],
      columns: [],
      toolbarButtons: [],
      rowButtons: []
    }
  },
  created () {
    this.formCols = [
      [
        {
          type: 'select',
          prop: 'device_category_id',
          label: this.key('device_category'),
          placeholder: this.key('select_device_category'),
          clearable: true,
          style: { width: '90%' },
          options: [],
          onFocus: this.onFormDeviceCategoryFocus
        }
      ],
      [
        {
          type: 'select',
          prop: 'type',
          label: this.key('type'),
          placeholder: this.key('select_type'),
          clearable: true,
          style: { width: '90%' },
          options: [
            { label: this.$t(this.key('type_error')), value: 'ERR' },
            { label: this.$t(this.key('type_ng')), value: 'NG' }
          ]
        }
      ],
      [
        {
          type: 'input',
          prop: 'number',
          label: this.key('ng_code'),
          placeholder: this.key('enter_ng_code'),
          clearable: true,
          style: { width: '90%' }
        }
      ],
      [
        {
          type: 'input',
          prop: 'explain',
          label: this.key('ng_name'),
          placeholder: this.key('enter_ng_name'),
          clearable: true,
          style: { width: '90%' }
        }
      ],
      [
        {
          type: 'input',
          inputType: 'textarea',
          prop: 'note',
          label: this.key('remark'),
          placeholder: this.key('enter_remark'),
          autosize: { minRows: 2, maxRows: 6 },
          clearable: true,
          style: { width: '90%' }
        }
      ]
    ]

    this.columns = useTableColumns([
      { prop: 'device_category_name', label: this.key('device_category'), minWidth: 140 },
      { prop: 'type', label: this.key('exception_ng_category'), minWidth: 120, slot: 'type' },
      { prop: 'number', label: this.key('ng_code'), minWidth: 140 },
      { prop: 'explain', label: this.key('ng_name'), minWidth: 140 },
      { prop: 'note', label: this.key('remark'), minWidth: 200 },
      { prop: '_actions', label: this.key('operation'), width: 180, fixed: 'right' }
    ])

    const btns = useTableButtons({
      toolbar: [
        {
          key: 'add',
          label: this.key('add'),
          icon: 'el-icon-plus',
          type: 'primary',
          auth: '/production_configuration/product_model/product_ng_info/create',
          onClick: this.openAdd
        },
        {
          key: 'batch-delete',
          label: this.key('batch_delete'),
          icon: 'el-icon-delete',
          type: 'danger',
          auth: '/production_configuration/product_model/product_ng_info/delete',
          onClick: this.handleBatchDelete
        },
        {
          key: 'import',
          label: this.key('import'),
          icon: 'el-icon-upload2',
          color: '#3CBA92',
          auth: '/production_configuration/product_model/product_ng_info/create',
          onClick: this.openImport
        },
        {
          key: 'export',
          label: this.key('export'),
          icon: 'el-icon-download',
          color: '#35C2EE',
          auth: '/production_configuration/product_model/product_ng_info/export',
          onClick: this.handleExport
        }
      ],
      row: [
        {
          key: 'edit',
          label: this.key('edit'),
          icon: 'el-icon-edit',
          auth: '/production_configuration/product_model/product_ng_info/edit',
          onClick: this.openEdit
        },
        {
          key: 'delete',
          label: this.key('delete'),
          icon: 'el-icon-delete',
          color: 'danger',
          auth: '/production_configuration/product_model/product_ng_info/delete',
          onClick: this.handleDelete
        }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.loadDeviceCategories().then(() => {
      this.fetchData()
    })
  },
  methods: {
    getTotal (source, fallback) {
      if (!source || typeof source !== 'object') return fallback
      const total = source.count ?? source.total ?? source.total_count ?? source.record_count ?? source.recordsTotal
      const value = Number(total)
      if (!Number.isNaN(value)) return value
      if (source.pagination) return this.getTotal(source.pagination, fallback)
      return fallback
    },
    normalizeResponse (res) {
      const containers = [res, res && res.data, res && res.data && res.data.data].filter(Boolean)
      for (const item of containers) {
        if (Array.isArray(item)) {
          return { list: item, total: this.getTotal(res, item.length) }
        }
        const list = item.data || item.list || item.rows || item.records || item.items
        if (Array.isArray(list)) {
          return { list, total: this.getTotal(item, this.getTotal(res, list.length)) }
        }
      }
      return { list: [], total: 0 }
    },
    normalizeRow (row) {
      const isObject = value => value && typeof value === 'object'
      const deviceCategory = isObject(row.DeviceCategory)
        ? row.DeviceCategory
        : (isObject(row.device_category)
          ? row.device_category
          : (isObject(row.category) ? row.category : {}))
      const option = this.deviceCategoryOptions.find(item => String(item.value) === String(row.device_category_id || deviceCategory.id || ''))
      return {
        ...row,
        device_category_id: row.device_category_id || deviceCategory.id || '',
        device_category_name: row.device_category_name || deviceCategory.name || row.category_name || (option && option.label) || (typeof row.device_category === 'string' ? row.device_category : '')
      }
    },
    normalizeOptions (res) {
      return this.normalizeResponse(res).list.map(item => ({
        label: item.name || item.label || item.code || item.id,
        value: item.id !== undefined ? item.id : item.value
      })).filter(item => item.value !== undefined && item.value !== null && item.value !== '')
    },
    typeText (type) {
      if (type === 'ERR') return this.$t(this.key('type_error'))
      if (type === 'NG') return this.$t(this.key('type_ng'))
      return type
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getProductNgInfoList({
          ...this.search,
          page_no: this.pagination.current,
          page_size: this.pagination.size
        })
        const data = this.normalizeResponse(res)
        this.tableData = data.list.map(this.normalizeRow)
        this.pagination.total = data.total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { device_category_id: '', type: '', number: '', explain: '' }
      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
    },
    async loadDeviceCategories () {
      if (this.deviceCategoryOptions.length) return
      this.deviceCategoryLoading = true
      try {
        const res = await getDeviceCategoryAll({})
        this.deviceCategoryOptions = this.normalizeOptions(res)
        this.searchFormDeviceCategoryUpdate()
      } catch {
        this.$message.error(this.$t(this.key('load_device_category_failed')))
      } finally {
        this.deviceCategoryLoading = false
      }
    },
    searchFormDeviceCategoryUpdate () {
      const catCol = this.formCols[0] && this.formCols[0][0]
      if (catCol && catCol.type === 'select') {
        catCol.options = this.deviceCategoryOptions
      }
    },
    onFormDeviceCategoryFocus () {
      this.loadDeviceCategories()
    },
    resetForm () {
      this.formData = { device_category_id: '', type: '', number: '', explain: '', note: '' }
      this.editId = null
      this.searchFormDeviceCategoryUpdate()
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_exception_ng_category')
      this.loadDeviceCategories().then(() => {
        if (!this.deviceCategoryOptions.length) return
        this.$nextTick(() => {
          this.$refs.dialogForm && this.$refs.dialogForm.reset()
          this.resetForm()
          this.dialogVisible = true
        })
      })
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_exception_ng_category')
      this.editId = row.id
      this.formData = {
        device_category_id: row.device_category_id || '',
        type: row.type || '',
        number: row.number || '',
        explain: row.explain || '',
        note: row.note || ''
      }
      this.loadDeviceCategories().then(() => {
        if (!this.deviceCategoryOptions.length) return
        this.dialogVisible = true
      })
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createProductNgInfo(this.formData)
        } else {
          await editProductNgInfo({ ...this.formData, id: this.editId })
        }
        this.$message.success(this.$t(this.key('operation_success')))
        this.dialogVisible = false
        this.fetchData()
      } finally {
        this.submitting = false
      }
    },
    onDialogClose () {
      this.resetForm()
    },
    async handleDelete (row) {
      await this.$confirmAction(
        {
          message: this.key('confirm_delete'),
          title: this.key('prompt')
        },
        () => deleteProductNgInfo({ id: [row.id] })
      )
      this.$message.success(this.$t(this.key('operation_success')))
      this.pagination.current = Math.min(
        this.pagination.current,
        Math.ceil((this.pagination.total - 1) / this.pagination.size) || 1
      )
      this.fetchData()
    },
    async handleBatchDelete () {
      if (!this.selectedRows.length) {
        this.$message.error(this.$t(this.key('please_select_data')))
        return
      }
      const ids = this.selectedRows.map(r => r.id)
      await this.$confirmAction(
        {
          message: this.key('confirm_batch_delete'),
          title: this.key('prompt')
        },
        () => deleteProductNgInfo({ id: ids })
      )
      this.$message.success(this.$t(this.key('operation_success')))
      this.fetchData()
    },
    openImport () {
      this.importVisible = true
    },
    onImportSaved () {
      this.fetchData()
    },
    async handleExport () {
      try {
        await this.$confirm(
          this.$t(this.key('export_confirm_tip')),
          this.$t(this.key('prompt')),
          { confirmButtonText: this.$t(this.key('confirm')), cancelButtonText: this.$t(this.key('cancel')), type: 'warning', center: true }
        )
      } catch {
        this.$message({ type: 'info', message: this.$t(this.key('operation_cancelled')) })
        return
      }
      try {
        await productNgInfoExportTask({
          ...this.search,
          action: 'download'
        })
        this.$message.success(this.$t(this.key('create_download_task_success')))
        this.$router.push({ name: 'task' })
      } catch { /* handled by interceptor */ }
    }
  }
}
</script>

<style scoped>
.search-bar {
  padding: 10px 0;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
