<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('keyword'))">
            <el-input
              v-model="search.keyword"
              :placeholder="$t(key('enter_keyword'))"
              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"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    />

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="40%"
      :form-cols="formCols"
      :form-data="formData"
      :rules="rules"
      label-width="130px"
      :submitting="submitting"
      :confirm-text="key('confirm')"
      :cancel-text="key('cancel')"
      @submit="onDialogSubmit"
      @close="onDialogClose"
    />
  </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 PageDialogForm from '@/components/page-dialog-form'
import { getList, createItem, editItem, deleteItem, createExportTask } from '@/api/equipment-management/replacement-logs'

export default {
  name: 'equipment-management-replacement-logs',
  components: { PageTable, PageDialogForm },
  mixins: [i18nMixin('page.equipment_management.consumables_management.replacement_logs'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: {
        keyword: ''
      },
      pagination: { current: 1, size: 10, total: 0 },
      formData: {
        device_consumables_item_id: '',
        device_id: '',
        replace_user: '',
        replace_time: '',
        replace_reason: '',
        replace_duration: '',
        remark: ''
      },
      rules: {
        device_consumables_item_id: [{ required: true, message: this.key('enter_consumables_item_id'), trigger: 'blur' }],
        device_id: [{ required: true, message: this.key('enter_device_id'), trigger: 'blur' }]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formCols: [
        [
          {
            type: 'input',
            prop: 'device_consumables_item_id',
            label: this.key('consumables_item_id'),
            placeholder: this.key('enter_consumables_item_id'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'device_id',
            label: this.key('device_id'),
            placeholder: this.key('enter_device_id'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'replace_user',
            label: this.key('replace_user'),
            placeholder: this.key('enter_replace_user'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'replace_time',
            label: this.key('replace_time'),
            placeholder: this.key('enter_replace_time'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'replace_reason',
            label: this.key('replace_reason'),
            placeholder: this.key('enter_replace_reason'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'replace_duration',
            label: this.key('replace_duration'),
            placeholder: this.key('enter_replace_duration'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'remark',
            label: this.key('remark'),
            placeholder: this.key('enter_remark'),
            inputType: 'textarea',
            autosize: { minRows: 2, maxRows: 6 },
            clearable: true,
            style: { width: '90%' }
          }
        ]
      ]
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'device_consumables_item_name', label: this.key('consumables_item'), minWidth: 140 },
      { prop: 'device_name', label: this.key('device_name'), minWidth: 140 },
      { prop: 'replace_user', label: this.key('replace_user'), minWidth: 140 },
      { prop: 'replace_time', label: this.key('replace_time'), minWidth: 140 },
      { prop: 'replace_reason', label: this.key('replace_reason'), minWidth: 140 },
      { prop: 'replace_duration', label: this.key('replace_duration'), minWidth: 140 },
      { 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: '/device_management/device_consumables/device_consumables_replace_log/create', onClick: this.openAdd },
        { key: 'export', label: this.key('export'), icon: 'el-icon-download', auth: '/device_management/device_consumables/device_consumables_replace_log/export', onClick: this.handleExport }
      ],
      row: [
        { key: 'edit', label: this.key('edit'), icon: 'el-icon-edit', auth: '/device_management/device_consumables/device_consumables_replace_log/edit', onClick: this.openEdit },
        { key: 'delete', label: this.key('delete'), icon: 'el-icon-delete', color: 'danger', auth: '/device_management/device_consumables/device_consumables_replace_log/delete', onClick: this.handleDelete }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    normalizeResponse (res) {
      const data = res && res.data !== undefined ? res.data : res
      if (Array.isArray(data)) return { list: data, total: data.length }
      if (data && Array.isArray(data.data)) return { list: data.data, total: Number(data.count || data.total || data.data.length) }
      if (data && data.data && Array.isArray(data.data.data)) return { list: data.data.data, total: Number(data.data.count || data.data.total || data.data.data.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 = {
        keyword: ''
      }
      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
    },
    resetForm () {
      this.formData = {
        device_consumables_item_id: '',
        device_id: '',
        replace_user: '',
        replace_time: '',
        replace_reason: '',
        replace_duration: '',
        remark: ''
      }
      this.editId = ''
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_title')
      this.$nextTick(() => {
        this.$refs.dialogForm && this.$refs.dialogForm.reset()
        this.resetForm()
        this.dialogVisible = true
      })
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_title')
      this.editId = row.id
      this.formData = {
        device_consumables_item_id: row.device_consumables_item_id || '',
        device_id: row.device_id || '',
        replace_user: row.replace_user || '',
        replace_time: row.replace_time || '',
        replace_reason: row.replace_reason || '',
        replace_duration: row.replace_duration || '',
        remark: row.remark || ''
      }
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      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 handleExport () {
      const cancelled = await this.$confirmAction(
        { message: this.key('confirm_export'), title: this.key('tip') },
        () => createExportTask({ ...this.search })
      )
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
    }
  }
}
</script>

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