<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('material_code'))">
            <el-input
              v-model="search.code"
              :placeholder="$t(key('enter_material_code'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('material_name'))">
            <el-input
              v-model="search.name"
              :placeholder="$t(key('enter_material_name'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('material_category'))">
            <el-select
              v-model="search.bom_source_category_id"
              :placeholder="$t(key('select_material_category'))"
              clearable
              filterable
              style="width:200px"
            >
              <el-option
                v-for="item in categoryOptions"
                :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"
      help-url="/help/material-master"
      :help-text="$t(ckey('help'))"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    >
      <template #col-remark="{ row }">
        <el-popover
          v-if="row.remark && row.remark.length > 20"
          placement="top-start"
          width="300"
          trigger="hover"
          :content="row.remark"
        >
          <span slot="reference" style="cursor: pointer;">{{ row.remark.substr(0, 20) }}...</span>
        </el-popover>
        <span v-else>{{ row.remark }}</span>
      </template>
    </page-table>

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :width="'35%'"
      :form-cols="dialogFormCols"
      :form-data="formData"
      :rules="rules"
      :label-width="'100px'"
      :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 {
  getMaterialMasterList,
  createMaterialMaster,
  editMaterialMaster,
  deleteMaterialMaster,
  batchDeleteMaterialMaster
} from '@/api/production-master-data/material-master'
import { getMaterialCategoryAll } from '@/api/production-master-data/material-category'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'

export default {
  name: 'production-master-data-material-master',
  components: { PageTable, PageDialogForm },
  mixins: [i18nMixin('page.production_master_data.material_model.material_master'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: { code: '', name: '', bom_source_category_id: '' },
      pagination: { current: 1, size: 10, total: 0 },
      categoryOptions: [],
      formData: { code: '', name: '', bom_source_category_id: '', unit_id: '', remark: '' },
      rules: {
        code: [
          { required: true, message: this.key('enter_material_code'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('remark_length'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('enter_material_name'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('remark_length'), trigger: 'blur' }
        ],
        bom_source_category_id: [
          { required: true, message: this.key('select_material_category'), trigger: 'change' }
        ]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      // 表单基础结构，单位字段预留（待 unit 模块迁移后接入下拉数据源）
      baseFormCols: [
        [
          {
            type: 'input',
            prop: 'code',
            label: this.key('material_code'),
            placeholder: this.key('enter_material_code'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'name',
            label: this.key('material_name'),
            placeholder: this.key('enter_material_name'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'select',
            prop: 'bom_source_category_id',
            label: this.key('material_category'),
            placeholder: this.key('select_material_category'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: []
          }
        ],
        [
          {
            type: 'input',
            prop: 'unit_id',
            label: this.key('unit'),
            placeholder: this.key('select_unit'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'remark',
            inputType: 'textarea',
            autosize: { minRows: 2, maxRows: 6 },
            label: this.key('remark'),
            placeholder: this.key('enter_remark'),
            clearable: true,
            style: { width: '90%' }
          }
        ]
      ]
    }
  },
  computed: {
    // 类别下拉数据通过 computed 注入，避免 JSON.parse(JSON.stringify) 深拷贝
    dialogFormCols () {
      return this.baseFormCols.map(row => row.map(item => {
        if (item.prop === 'bom_source_category_id') {
          return { ...item, options: this.categoryOptions }
        }
        return item
      }))
    }
  },
  created () {
    this.initCategoryOptions()
    this.columns = useTableColumns([
      { prop: 'sort', label: this.key('sort'), width: 80 },
      { prop: 'code', label: this.key('material_code'), minWidth: 120 },
      { prop: 'name', label: this.key('material_name'), minWidth: 140 },
      { prop: 'bom_source_category_name', label: this.key('material_category'), minWidth: 120 },
      { prop: 'unit_name', label: this.key('unit'), minWidth: 100 },
      { prop: 'remark', label: this.key('remark'), minWidth: 160, slot: true },
      { prop: 'username', label: this.key('create_user'), minWidth: 100 },
      { prop: 'create_time', label: this.key('create_time'), minWidth: 160 },
      { 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/matetial_model/matetial_management/create',
          onClick: this.openAdd
        },
        {
          key: 'batch_delete',
          label: this.key('batch_delete'),
          icon: 'el-icon-delete',
          color: 'danger',
          auth: '/system_settings/matetial_model/matetial_management/batch-delete',
          onClick: this.handleBatchDelete
        }
      ],
      row: [
        {
          key: 'edit',
          label: this.key('edit'),
          icon: 'el-icon-edit',
          auth: '/production_configuration/matetial_model/matetial_management/edit',
          onClick: this.openEdit
        },
        {
          key: 'delete',
          label: this.key('delete'),
          icon: 'el-icon-delete',
          color: 'danger',
          auth: '/production_configuration/matetial_model/matetial_management/delete',
          onClick: this.handleDelete
        }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    async initCategoryOptions () {
      try {
        const res = await getMaterialCategoryAll()
        const data = Array.isArray(res) ? res : (res.data || [])
        this.categoryOptions = data.map(item => ({ value: item.id, label: item.name }))
      } catch { /* 类别下拉加载失败时，下拉为空即可，不影响主流程 */ }
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getMaterialMasterList({
          ...this.search,
          page_no: this.pagination.current,
          page_size: this.pagination.size
        })
        const list = Array.isArray(res) ? res : (res.data || [])
        const total = Array.isArray(res) ? res.length : (res.count || 0)
        this.tableData = list
        this.pagination.total = total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { code: '', name: '', bom_source_category_id: '' }
      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 = { code: '', name: '', bom_source_category_id: '', unit_id: '', 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 = {
        code: row.code,
        name: row.name,
        bom_source_category_id: row.bom_source_category_id,
        unit_id: row.unit_id,
        remark: row.remark || ''
      }
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createMaterialMaster(this.formData)
        } else {
          await editMaterialMaster({ ...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')
        },
        () => deleteMaterialMaster({ 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 <= 0) {
        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')
        },
        () => batchDeleteMaterialMaster({ id: ids })
      )
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.fetchData()
    }
  }
}
</script>

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