<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('device_code'))">
            <el-input v-model="search.code" :placeholder="$t(key('enter_device_code'))" clearable style="width:180px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('device_name'))">
            <el-input v-model="search.name" :placeholder="$t(key('enter_device_name'))" clearable style="width:180px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('device_category'))">
            <el-select v-model="search.device_category_id" :placeholder="$t(key('select_device_category'))" clearable filterable style="width:180px" @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('area'))">
            <el-select v-model="search.area_id" :placeholder="$t(key('select_area'))" clearable filterable style="width:180px" @focus="loadAreas" @change="onSearchAreaChange">
              <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('production_line'))">
            <el-select v-model="search.line_id" :placeholder="$t(key('select_production_line'))" clearable filterable style="width:180px" @focus="loadSearchLines">
              <el-option v-for="item in searchLineOptions" :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" @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"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    />

    <el-dialog
      :title="$t(dialogTitle)"
      :visible.sync="dialogVisible"
      width="60%"
      :close-on-click-modal="false"
      destroy-on-close
      @close="onDialogClose"
    >
      <el-form ref="form" class="equipment-form" :model="formData" :rules="rules" label-width="130px" size="mini">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item :label="$t(key('device_code'))" prop="code">
              <el-input v-model="formData.code" :placeholder="$t(key('enter_device_code'))" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('ip'))" prop="ip">
              <el-input v-model="formData.ip" :placeholder="$t(key('enter_ip'))" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('device_name'))" prop="name">
              <el-input v-model="formData.name" :placeholder="$t(key('enter_device_name'))" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('manufacturer'))" prop="manufacturer">
              <el-input v-model="formData.manufacturer" :placeholder="$t(key('enter_manufacturer'))" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('device_category'))" prop="device_category_id">
              <el-select v-model="formData.device_category_id" :placeholder="$t(key('select_device_category'))" clearable filterable style="width:100%" @focus="loadDeviceCategories">
                <el-option v-for="item in deviceCategoryOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('fixed_asset_code'))" prop="fixed_asset_code">
              <el-input v-model="formData.fixed_asset_code" :placeholder="$t(key('enter_fixed_asset_code'))" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('design_ppm'))" prop="design_ppm">
              <el-input v-model="formData.design_ppm" :placeholder="$t(key('enter_design_ppm'))" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('entry_time'))" prop="entry_time">
              <el-date-picker v-model="formData.entry_time" type="date" value-format="yyyy-MM-dd" :placeholder="$t(key('select_entry_time'))" clearable style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('area'))" prop="area_id">
              <el-select v-model="formData.area_id" :placeholder="$t(key('select_area'))" clearable filterable style="width:100%" @focus="loadAreas" @change="onFormAreaChange">
                <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t(key('production_line'))" prop="line_id">
              <el-select v-model="formData.line_id" :placeholder="$t(key('select_production_line'))" clearable filterable style="width:100%" @focus="loadFormLines">
                <el-option v-for="item in formLineOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t(key('remark'))" prop="remark">
              <el-input v-model="formData.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" :placeholder="$t(key('enter_remark'))" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">{{ $t(key('cancel')) }}</el-button>
        <el-button type="primary" :loading="submitting" @click="onDialogSubmit">{{ $t(key('confirm')) }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t(key('device_data_import'))"
      :visible.sync="importVisible"
      width="70%"
      append-to-body
      :close-on-click-modal="false"
      @close="resetImport"
    >
      <el-alert :title="$t(key('import_warning'))" :closable="false" type="warning" show-icon />
      <el-form label-width="130px" class="import-form">
        <el-form-item :label="$t(key('import_table'))">
          <el-upload
            action=""
            :multiple="false"
            :auto-upload="false"
            :show-file-list="true"
            :file-list="importFileList"
            accept=".xls,.xlsx"
            :on-change="onImportFileChange"
          >
            <el-button slot="trigger" size="mini" type="success">{{ $t(key('select_file')) }}</el-button>
            <el-button style="margin-left:10px" size="mini" type="primary" :loading="importTemplateLoading" @click.stop="downloadTemplate">
              {{ $t(key('download_template')) }}
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t(key('preview'))">
          <el-table v-loading="importTableLoading" :data="importRows" border height="360">
            <el-table-column prop="code" :label="$t(key('device_code'))" min-width="120" />
            <el-table-column prop="name" :label="$t(key('device_name'))" min-width="120" />
            <el-table-column prop="device_category_name" :label="$t(key('device_category'))" min-width="120" />
            <el-table-column prop="line_name" :label="$t(key('production_line'))" min-width="120" />
            <el-table-column prop="ip" :label="$t(key('ip'))" min-width="120" />
            <el-table-column prop="design_ppm" :label="$t(key('design_ppm'))" min-width="100" />
            <el-table-column prop="manufacturer" :label="$t(key('manufacturer'))" min-width="120" />
            <el-table-column prop="fixed_asset_code" :label="$t(key('fixed_asset_code'))" min-width="140" />
            <el-table-column prop="entry_time" :label="$t(key('entry_time'))" min-width="120" />
            <el-table-column prop="remark" :label="$t(key('remark'))" min-width="160" show-overflow-tooltip />
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="importVisible = false">{{ $t(key('cancel')) }}</el-button>
        <el-button type="primary" :loading="importSubmitting" @click="submitImport">{{ $t(key('confirm')) }}</el-button>
      </div>
    </el-dialog>
  </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 PageTable from '@/components/page-table'
import {
  getList,
  createItem,
  editItem,
  deleteItem,
  batchDeleteItems,
  getImportTemplate,
  importData,
  createExportTask
} from '@/api/equipment-management/equipment-registry'
import { getEquipmentCategoryALL } from '@/api/equipment-management/equipment-category'
import { getFactoryAreaALL } from '@/api/production-master-data/factory-area'
import { getProductionLineALL } from '@/api/production-master-data/production-line'
import { downloadRename, readExcel } from '@/utils/file'

export default {
  name: 'equipment-management-equipment-registry',
  components: { PageTable },
  mixins: [i18nMixin('page.equipment_management.equipment_model.equipment_registry'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: { code: '', name: '', device_category_id: '', area_id: '', line_id: '' },
      pagination: { current: 1, size: 10, total: 0 },
      formData: this.emptyForm(),
      deviceCategoryOptions: [],
      areaOptions: [],
      searchLineOptions: [],
      formLineOptions: [],
      importVisible: false,
      importFileList: [],
      importRows: [],
      importTableLoading: false,
      importTemplateLoading: false,
      importSubmitting: false,
      rules: {
        code: [
          { required: true, message: this.key('enter_device_code'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('length_1_100'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('enter_device_name'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('length_1_100'), trigger: 'blur' }
        ],
        device_category_id: [{ required: true, message: this.key('select_device_category'), trigger: 'change' }],
        area_id: [{ required: true, message: this.key('select_area'), trigger: 'change' }],
        line_id: [{ required: true, message: this.key('select_production_line'), trigger: 'change' }],
        design_ppm: [{ required: true, message: this.key('enter_design_ppm'), trigger: 'blur' }]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: []
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'code', label: this.key('device_code'), minWidth: 130 },
      { prop: 'name', label: this.key('device_name'), minWidth: 130 },
      { prop: 'device_category_name', label: this.key('device_category'), minWidth: 130 },
      { prop: 'design_ppm', label: this.key('design_ppm'), minWidth: 110 },
      { prop: 'area_name', label: this.key('area'), minWidth: 120 },
      { prop: 'line_name', label: this.key('production_line'), minWidth: 120 },
      { prop: 'ip', label: this.key('ip'), minWidth: 120 },
      { prop: 'manufacturer', label: this.key('manufacturer'), minWidth: 130 },
      { prop: 'fixed_asset_code', label: this.key('fixed_asset_code'), minWidth: 150 },
      { prop: 'entry_time', label: this.key('entry_time'), minWidth: 120 },
      { prop: 'remark', label: this.key('remark'), minWidth: 160 },
      { prop: 'create_time', label: this.key('create_time'), minWidth: 160 },
      { prop: '_actions', label: this.key('operation'), width: 170, fixed: 'right' }
    ])
    const btns = useTableButtons({
      toolbar: [
        { key: 'add', label: this.key('add'), icon: 'el-icon-plus', type: 'primary', auth: '/production_configuration/device_model/device_management/create', onClick: this.openAdd },
        { key: 'batchDelete', label: this.key('batch_delete'), icon: 'el-icon-delete', type: 'danger', auth: '/production_configuration/device_model/device_management/batch-delete', needSelection: true, onClick: this.handleBatchDelete },
        { key: 'import', label: this.key('import'), icon: 'el-icon-upload2', type: 'success', auth: '/production_configuration/device_model/device_management/import', onClick: this.openImport },
        { key: 'export', label: this.key('export'), icon: 'el-icon-download', auth: '/production_configuration/device_model/device_management/export', onClick: this.handleExport }
      ],
      row: [
        { key: 'edit', label: this.key('edit'), icon: 'el-icon-edit', auth: '/production_configuration/device_model/device_management/edit', onClick: this.openEdit },
        { key: 'delete', label: this.key('delete'), icon: 'el-icon-delete', color: 'danger', auth: '/production_configuration/device_model/device_management/delete', onClick: this.handleDelete }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    emptyForm () {
      return {
        code: '',
        name: '',
        ip: '',
        manufacturer: '',
        device_category_id: '',
        fixed_asset_code: '',
        design_ppm: '',
        area_id: '',
        line_id: '',
        entry_time: '',
        remark: ''
      }
    },
    normalizeResponse (res) {
      const getTotal = (source, fallback) => {
        if (!source) return fallback
        const total = source.count ?? source.total ?? source.total_count ?? source.record_count
        const value = Number(total)
        return Number.isNaN(value) ? fallback : value
      }
      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: getTotal(res, item.length) }
        const list = item.data || item.list || item.rows || item.records || item.items
        if (Array.isArray(list)) return { list, total: getTotal(item, getTotal(res, list.length)) }
      }
      return { list: [], total: 0 }
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getList({ ...this.search, page_no: this.pagination.current, page_size: this.pagination.size })
        const data = this.normalizeResponse(res)
        this.tableData = data.list
        this.pagination.total = data.total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { code: '', name: '', device_category_id: '', area_id: '', line_id: '' }
      this.searchLineOptions = []
      this.onSearch()
    },
    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
      const res = await getEquipmentCategoryALL()
      this.deviceCategoryOptions = this.normalizeResponse(res).list.map(item => ({ label: item.name, value: item.id, code: item.code }))
    },
    async loadAreas () {
      if (this.areaOptions.length) return
      const res = await getFactoryAreaALL()
      this.areaOptions = this.normalizeResponse(res).list.map(item => ({ label: item.name, value: item.area_id || item.id }))
    },
    async loadLines (areaId) {
      if (!areaId) {
        this.$message.warning(this.$t(this.key('select_factory_first')))
        return []
      }
      const res = await getProductionLineALL({ area_id: areaId })
      return this.normalizeResponse(res).list.map(item => ({ label: item.name, value: item.id }))
    },
    async loadSearchLines () {
      this.searchLineOptions = await this.loadLines(this.search.area_id)
    },
    async loadFormLines () {
      this.formLineOptions = await this.loadLines(this.formData.area_id)
    },
    onSearchAreaChange () {
      this.search.line_id = ''
      this.searchLineOptions = []
    },
    onFormAreaChange () {
      this.formData.line_id = ''
      this.formLineOptions = []
    },
    resetForm () {
      this.formData = this.emptyForm()
      this.editId = ''
      this.formLineOptions = []
      this.$nextTick(() => this.$refs.form && this.$refs.form.clearValidate())
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_title')
      this.resetForm()
      this.loadDeviceCategories()
      this.loadAreas()
      this.dialogVisible = true
    },
    async openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_title')
      this.editId = row.id
      this.formData = { ...this.emptyForm(), ...row }
      await Promise.all([this.loadDeviceCategories(), this.loadAreas()])
      if (this.formData.area_id) this.formLineOptions = await this.loadLines(this.formData.area_id)
      this.dialogVisible = true
    },
    onDialogSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        this.submitting = true
        try {
          if (this.handleType === 'create') await createItem(this.formData)
          else await editItem({ ...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) {
      const cancelled = await this.$confirmAction({ message: this.key('confirm_delete'), title: this.key('tip') }, () => deleteItem({ id: [row.id] }))
      if (cancelled) return
      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(item => item.id)
      const cancelled = await this.$confirmAction({ message: this.key('confirm_batch_delete'), title: this.key('tip') }, () => batchDeleteItems({ id: ids }))
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.fetchData()
    },
    openImport () {
      this.resetImport()
      this.importVisible = true
    },
    resetImport () {
      this.importFileList = []
      this.importRows = []
    },
    async downloadTemplate () {
      this.importTemplateLoading = true
      try {
        const res = await getImportTemplate({})
        downloadRename(res, 'xlsx', this.$t(this.key('import_template_name')))
      } finally {
        this.importTemplateLoading = false
      }
    },
    getImportValue (row, names) {
      for (const name of names) {
        if (row[name] !== undefined && row[name] !== null) return row[name]
      }
      return ''
    },
    async onImportFileChange (file) {
      if (!file || !/\.(xls|xlsx)$/i.test(file.name)) {
        this.$message.error(this.$t(this.key('import_file_format_error')))
        this.importFileList = []
        return
      }
      this.importFileList = [file]
      this.importTableLoading = true
      try {
        const rows = await readExcel(file.raw)
        const required = ['设备编码', '设备名称', 'IP', '设备类别', '产线', '设计PPM', '厂商', '设备固定资产编码', '进场时间', '备注']
        const first = rows[0] || {}
        const missing = required.find(name => !Object.prototype.hasOwnProperty.call(first, name))
        if (missing) {
          this.$message.error(this.$t(this.key('import_missing_column'), { name: missing }))
          this.importRows = []
          return
        }
        this.importRows = rows.map(row => ({
          code: this.getImportValue(row, ['设备编码']),
          name: this.getImportValue(row, ['设备名称']),
          ip: this.getImportValue(row, ['IP']),
          device_category_name: this.getImportValue(row, ['设备类别']),
          line_name: this.getImportValue(row, ['产线']),
          design_ppm: this.getImportValue(row, ['设计PPM']),
          manufacturer: this.getImportValue(row, ['厂商']),
          fixed_asset_code: this.getImportValue(row, ['设备固定资产编码']),
          entry_time: this.getImportValue(row, ['进场时间']),
          remark: this.getImportValue(row, ['备注'])
        }))
      } finally {
        this.importTableLoading = false
      }
    },
    async submitImport () {
      if (!this.importRows.length) {
        this.$message.error(this.$t(this.key('import_no_data')))
        return
      }
      this.importSubmitting = true
      try {
        await importData({ import_data: JSON.stringify(this.importRows) })
        this.$message.success(this.$t(this.key('operation_success')))
        this.importVisible = false
        this.fetchData()
      } finally {
        this.importSubmitting = false
      }
    },
    async handleExport () {
      const cancelled = await this.$confirmAction({ message: this.key('confirm_export'), title: this.key('tip') }, () => createExportTask({ ...this.search, action: 'download' }))
      if (cancelled) return
      this.$message.success(this.$t(this.key('create_download_task_success')))
      if (this.$router && this.$router.push) {
        this.$router.push({ name: 'task' }).catch(() => {})
      }
    }
  }
}
</script>

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