<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('bom_version_code'))">
            <el-input v-model.trim="search.code" :placeholder="$t(key('enter_bom_version_code'))" clearable style="width:220px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('bom_version_name'))">
            <el-input v-model.trim="search.name" :placeholder="$t(key('enter_bom_version_name'))" clearable style="width:220px" @keyup.enter.native="onSearch" />
          </el-form-item>
          <el-form-item :label="$t(key('product_model_name'))">
            <el-select v-model="search.product_model_id" :placeholder="$t(key('select_product_model_name'))" clearable filterable style="width:220px">
              <el-option v-for="item in productOptions" :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('query')) }}</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">
      <template #col-status="{ row }">
        <span v-if="String(row.status) === '1'" class="status-on"><i class="el-icon-circle-check" /> {{ $t(key('enable')) }}</span>
        <span v-else class="status-off"><i class="el-icon-circle-close" /> {{ $t(key('disable')) }}</span>
      </template>
      <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="38%" :form-cols="dialogFormCols" :form-data="formData" :rules="rules" label-width="120px" :submitting="submitting" :confirm-text="key('confirm')" :cancel-text="key('cancel')" @submit="onDialogSubmit" @close="onDialogClose" />

    <bom-relationship :visible.sync="relationshipVisible" :bom="currentBom" @saved="fetchData" />
  </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 BomRelationship from './components/BomRelationship'
import { getProductBatteryAll } from '@/api/production-master-data/product-management'
import { getBomList, createBom, editBom, deleteBom } from '@/api/production-master-data/bill-of-materials'

function readPageData (res) {
  const data = res && res.data ? res.data : res
  if (!data) return { list: [], total: 0 }
  if (Array.isArray(data)) return { list: data, total: data.length }
  return { list: data.data || data.list || [], total: Number(data.count || data.total || 0) }
}

export default {
  name: 'production-master-data-bill-of-materials',
  components: { PageTable, PageDialogForm, BomRelationship },
  mixins: [i18nMixin('page.production_master_data.material_model.bill_of_materials'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      productOptions: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      relationshipVisible: false,
      currentBom: {},
      search: { code: '', name: '', product_model_id: '' },
      pagination: { current: 1, size: 10, total: 0 },
      formData: this.defaultFormData(),
      rules: {
        code: [
          { required: true, message: this.key('enter_bom_code'), trigger: 'blur' },
          { min: 1, max: 45, message: this.key('length_1_45'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('enter_bom_name'), trigger: 'blur' },
          { min: 1, max: 45, message: this.key('length_1_45'), trigger: 'blur' }
        ],
        product_model_id: [{ required: true, message: this.key('select_product_model'), trigger: 'change' }]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      baseFormCols: [
        [{ type: 'input', prop: 'code', label: this.key('bom_version_code'), placeholder: this.key('enter_bom_version_code'), clearable: true, style: { width: '90%' } }],
        [{ type: 'input', prop: 'name', label: this.key('bom_version_name'), placeholder: this.key('enter_bom_version_name'), clearable: true, style: { width: '90%' } }],
        [{ type: 'select', prop: 'product_model_id', label: this.key('product_model_name'), placeholder: this.key('select_product_model_name'), clearable: true, filterable: true, style: { width: '90%' }, options: [] }],
        [{ type: 'select', prop: 'status', label: this.key('status'), placeholder: this.key('select_status'), clearable: true, style: { width: '90%' }, options: [{ label: this.$t(this.key('disable')), value: '0' }, { label: this.$t(this.key('enable')), value: '1' }] }],
        [{ 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: {
    dialogFormCols () {
      return this.baseFormCols.map(row => row.map(item => {
        if (item.prop === 'product_model_id') return { ...item, options: this.productOptions }
        return item
      }))
    }
  },
  created () {
    this.loadProductOptions()
    this.columns = useTableColumns([
      { prop: 'code', label: this.key('bom_version_code'), minWidth: 140 },
      { prop: 'name', label: this.key('bom_version_name'), minWidth: 160 },
      { prop: 'product_model_name', label: this.key('product_model_name'), minWidth: 160 },
      { prop: 'status', label: this.key('status'), slot: 'status', width: 110 },
      { prop: 'username', label: this.key('create_user'), minWidth: 100 },
      { prop: 'create_time', label: this.key('create_time'), minWidth: 160 },
      { prop: 'remark', label: this.key('remark'), slot: 'remark', minWidth: 160 },
      { prop: '_actions', label: this.key('operation'), width: 230, fixed: 'right' }
    ])
    const btns = useTableButtons({
      toolbar: [{ key: 'add', label: this.key('add'), icon: 'el-icon-plus', type: 'primary', auth: '/production_configuration/matetial_model/bom/create', onClick: this.openAdd }],
      row: [
        { key: 'set_bom', label: this.key('set_bom'), icon: 'el-icon-setting', auth: '/production_configuration/matetial_model/bom/edit_bom_relationship', onClick: this.openRelationship },
        { key: 'edit', label: this.key('edit'), icon: 'el-icon-edit', auth: '/production_configuration/matetial_model/bom/edit', onClick: this.openEdit },
        { key: 'delete', label: this.key('delete'), icon: 'el-icon-delete', color: 'danger', auth: '/production_configuration/matetial_model/bom/delete', onClick: this.handleDelete }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    defaultFormData () {
      return { code: '', name: '', product_model_id: '', status: '1', remark: '' }
    },
    async loadProductOptions () {
      const res = await getProductBatteryAll({})
      const list = (res && res.data) || res || []
      this.productOptions = list.map(item => ({ label: item.name, value: item.product_model_id || item.id }))
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getBomList({ ...this.search, page_no: this.pagination.current, page_size: this.pagination.size })
        const { list, total } = readPageData(res)
        this.tableData = list
        this.pagination.total = total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { code: '', name: '', product_model_id: '' }
      this.pagination.current = 1
      this.fetchData()
    },
    onPageChange (page) {
      this.pagination.current = page.current
      this.pagination.size = page.size
      this.fetchData()
    },
    resetForm () {
      this.formData = this.defaultFormData()
      this.editId = ''
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_bom_info')
      this.$nextTick(() => {
        this.$refs.dialogForm && this.$refs.dialogForm.reset()
        this.resetForm()
        this.dialogVisible = true
      })
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_bom_info')
      this.editId = row.id
      this.formData = { code: row.code, name: row.name, product_model_id: row.product_model_id, status: String(row.status), remark: row.remark || '' }
      this.dialogVisible = true
    },
    openRelationship (row) {
      this.currentBom = { id: row.id, name: row.name }
      this.relationshipVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') await createBom(this.formData)
        else await editBom({ ...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_message'), title: this.key('prompt'), confirmButtonText: this.key('confirm'), cancelButtonText: this.key('cancel') }, () => deleteBom({ 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()
    }
  }
}
</script>

<style scoped>
.search-bar { padding: 10px 0; }
.status-on { color: #67C23A; }
.status-off { color: #909399; }
/deep/ .el-form-item--mini.el-form-item { margin-bottom: 4px; }
</style>
