<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" :model="search" size="mini">
          <el-form-item :label="$t(key('device_name'))">
            <el-select v-model="search.device_code" :placeholder="$t(key('please_select_device_name'))" clearable filterable style="width:220px">
              <el-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('consumables_item_code'))">
            <el-input v-model.trim="search.device_consumables_item_code" :placeholder="$t(key('enter_consumables_item_code'))" clearable style="width:220px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('consumables_item_name'))">
            <el-input v-model.trim="search.device_consumables_item_name" :placeholder="$t(key('enter_consumables_item_name'))" clearable style="width:220px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('create_time'))">
            <el-date-picker v-model="search.create_time" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :start-placeholder="$t(key('start_time'))" :end-placeholder="$t(key('end_time'))" style="width:330px" />
          </el-form-item>
          <el-form-item :label="$t(key('replace_time'))">
            <el-date-picker v-model="search.replace_time" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :start-placeholder="$t(key('start_time'))" :end-placeholder="$t(key('end_time'))" style="width:330px" />
          </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" />

    <page-dialog-form ref="dialogForm" :visible.sync="dialogVisible" :title="dialogTitle" width="560px" :form-cols="formCols" :form-data="formData" :rules="rules" label-width="140px" :submitting="submitting" :confirm-text="key('confirm')" :cancel-text="key('cancel')" @submit="onDialogSubmit" @close="resetForm" />
  </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 { getAll as getDeviceAll } from '@/api/equipment-management/equipment-registry'
import { getList, editItem, createExportTask } from '@/api/equipment-management/replacement-logs'

function readPageData (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 }
}
function toOptions (list) {
  return (Array.isArray(list) ? list : []).map(item => ({ label: item.name, value: item.code, raw: item }))
}

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: [],
      search: { device_code: '', device_consumables_item_code: '', device_consumables_item_name: '', create_time: [], replace_time: [] },
      pagination: { current: 1, size: 10, total: 0 },
      deviceOptions: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      formData: { replace_user: '', replace_time: '', replace_reason: '', replacement_time: 0, remark: '' },
      columns: [],
      toolbarButtons: [],
      rowButtons: []
    }
  },
  computed: {
    replaceReasonOptions () {
      return [
        { label: this.$t(this.key('abnormal_damage')), value: this.$t(this.key('abnormal_damage')) },
        { label: this.$t(this.key('normal_wear')), value: this.$t(this.key('normal_wear')) },
        { label: this.$t(this.key('overdue_life')), value: this.$t(this.key('overdue_life')) }
      ]
    },
    formCols () {
      return [
        [{ type: 'input', prop: 'replace_user', label: this.key('replace_user'), placeholder: this.key('enter_replace_user'), style: { width: '100%' } }],
        [{ type: 'date-picker', prop: 'replace_time', label: this.key('replace_time'), placeholder: this.key('enter_replace_time'), style: { width: '100%' } }],
        [{ type: 'select', prop: 'replace_reason', label: this.key('replace_reason'), placeholder: this.key('enter_replace_reason'), options: this.replaceReasonOptions, style: { width: '100%' } }],
        [{ type: 'input-number', prop: 'replacement_time', label: this.key('replacement_time'), min: 0, style: { width: '100%' } }],
        [{ type: 'input', prop: 'remark', label: this.key('remark'), placeholder: this.key('enter_remark'), inputType: 'textarea', autosize: { minRows: 2, maxRows: 6 }, style: { width: '100%' } }]
      ]
    },
    rules () {
      return {
        replace_user: [{ required: true, message: this.key('enter_replace_user'), trigger: 'blur' }],
        replace_time: [{ required: true, message: this.key('enter_replace_time'), trigger: 'change' }],
        replace_reason: [{ required: true, message: this.key('enter_replace_reason'), trigger: 'change' }],
        replacement_time: [{ required: true, message: this.key('enter_replacement_time'), trigger: 'blur' }]
      }
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'id', label: this.key('id'), width: 80 },
      { prop: 'device_name', label: this.key('related_device'), minWidth: 150 },
      { prop: 'device_consumables_item_code', label: this.key('device_consumables_item_code'), minWidth: 150 },
      { prop: 'device_consumables_item_name', label: this.key('device_consumables_item_name'), minWidth: 150 },
      { prop: 'device_consumables_category_name', label: this.key('device_consumables_category_name'), minWidth: 150 },
      { prop: 'standard_service_life', label: this.key('standard_service_life'), minWidth: 130 },
      { prop: 'warning_service_life', label: this.key('warning_service_life'), minWidth: 130 },
      { prop: 'replace_lifetime', label: this.key('replace_lifetime'), minWidth: 130 },
      { prop: 'replace_user', label: this.key('replace_user'), minWidth: 120 },
      { prop: 'replace_time', label: this.key('replace_time'), minWidth: 160 },
      { prop: 'replace_reason', label: this.key('replace_reason'), minWidth: 130 },
      { prop: 'replacement_time', label: this.key('replacement_time'), minWidth: 130 },
      { prop: 'remark', label: this.key('remark'), minWidth: 140, showOverflowTooltip: true },
      { prop: 'create_time', label: this.key('create_time'), minWidth: 160 },
      { prop: '_actions', label: this.key('operation'), width: 100, fixed: 'right' }
    ], { selectionWidth: 0 })
    const btns = useTableButtons({
      toolbar: [
        { key: 'export', label: this.key('export'), icon: 'el-icon-download', type: 'primary', 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 }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.initOptions()
    this.fetchData()
  },
  methods: {
    async initOptions () {
      const res = await getDeviceAll({})
      this.deviceOptions = toOptions((res && res.data) || res)
    },
    buildSearchParams () {
      const params = { ...this.search }
      if (!Array.isArray(params.create_time) || !params.create_time.length) delete params.create_time
      if (!Array.isArray(params.replace_time) || !params.replace_time.length) delete params.replace_time
      return params
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getList({ ...this.buildSearchParams(), page_no: this.pagination.current, page_size: this.pagination.size })
        const page = readPageData(res)
        this.tableData = page.list
        this.pagination.total = page.total
      } finally { this.loading = false }
    },
    onSearch () { this.pagination.current = 1; this.fetchData() },
    onReset () { this.search = { device_code: '', device_consumables_item_code: '', device_consumables_item_name: '', create_time: [], replace_time: [] }; this.pagination.current = 1; this.fetchData() },
    onPageChange (page) { this.pagination.current = page.current; this.pagination.size = page.size; this.fetchData() },
    resetForm () { this.formData = { replace_user: '', replace_time: '', replace_reason: '', replacement_time: 0, remark: '' }; this.editId = '' },
    openEdit (row) {
      this.dialogTitle = this.key('edit_title')
      this.editId = row.id
      this.formData = { replace_user: row.replace_user || '', replace_time: row.replace_time || '', replace_reason: row.replace_reason || '', replacement_time: Number(row.replacement_time || 0), remark: row.remark || '' }
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        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 }
    },
    async handleExport () {
      const cancelled = await this.$confirmAction({ message: this.key('confirm_export'), title: this.key('tip'), confirmButtonText: this.key('confirm'), cancelButtonText: this.key('cancel') }, () => createExportTask({ ...this.buildSearchParams(), action: 'download' }))
      if (cancelled) return
      this.$message.success(this.$t(this.key('create_download_task_success')))
    }
  }
}
</script>

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