<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :title="dialogTitle"
    width="1000px"
    append-to-body
    :close-on-click-modal="false"
    @open="onOpen"
    @close="onClose"
  >
    <page-table
      ref="pageTable"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="toolbarButtons"
      :row-buttons="rowButtons"
      :pagination="pagination"
      height="420px"
      @page-change="onPageChange"
    >
      <template #col-itemType="{ row }">
        <span>{{ typeText(row.type) }}</span>
      </template>
    </page-table>

    <page-dialog-form
      ref="itemForm"
      :visible.sync="formVisible"
      :title="formTitle"
      width="760px"
      :form-cols="formCols"
      :form-data="formData"
      :rules="rules"
      label-width="120px"
      :submitting="submitting"
      :confirm-text="key('confirm')"
      :cancel-text="key('cancel')"
      @submit="onSubmit"
      @close="resetForm"
    />

    <template #footer>
      <el-button size="small" @click="visibleProxy = false">{{ $t(key('cancel')) }}</el-button>
      <el-button type="primary" size="small" @click="visibleProxy = false">{{ $t(key('confirm')) }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { useTableButtons } from '@/composables/useTableButtons'
import { i18nMixin } from '@/composables/useI18n'
import { confirmMixin } from '@/composables/useConfirmHandle'
import {
  fetchSettingItemList,
  createSettingItem,
  editSettingItem,
  deleteSettingItem
} from '@/api/quality-management/first-article-inspection-configuration'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'

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

export default {
  name: 'SettingItemsDialog',
  components: { PageTable, PageDialogForm },
  mixins: [i18nMixin('page.quality_management.first_article_inspection_configuration'), confirmMixin],
  props: {
    visible: { type: Boolean, default: false },
    settingRow: { type: Object, default: null }
  },
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      pagination: { current: 1, size: 10, total: 0 },
      formVisible: false,
      formTitle: '',
      handleType: 'create',
      editId: '',
      formData: this.emptyForm(),
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      rules: {
        code: [{ required: true, message: this.key('project_code_required'), trigger: 'blur' }],
        name: [{ required: true, message: this.key('project_name_required'), trigger: 'blur' }],
        type: [{ required: true, message: this.key('inspection_check_type_required'), trigger: 'change' }]
      }
    }
  },
  computed: {
    visibleProxy: {
      get () { return this.visible },
      set (val) { this.$emit('update:visible', val) }
    },
    dialogTitle () {
      const name = this.settingRow && this.settingRow.workingsubclass_name ? this.settingRow.workingsubclass_name : ''
      return name ? `${this.$t(this.key('configure_item_title'))}（${name}）` : this.$t(this.key('configure_item_title'))
    },
    typeOptions () {
      return [
        { label: this.$t(this.key('enumeration')), value: '1' },
        { label: this.$t(this.key('numeric')), value: '2' },
        { label: this.$t(this.key('limit')), value: '3' }
      ]
    },
    formCols () {
      const cols = [
        [
          { type: 'input', prop: 'code', label: this.key('project_code'), placeholder: this.key('please_project_code'), clearable: true, style: { width: '90%' } },
          { type: 'input', prop: 'name', label: this.key('project_name'), placeholder: this.key('please_project_name'), clearable: true, style: { width: '90%' } }
        ],
        [
          { type: 'input', prop: 'method', label: this.key('process_requirement'), placeholder: this.key('please_process_requirement'), clearable: true, style: { width: '90%' } },
          { type: 'select', prop: 'type', label: this.key('inspection_check_type'), placeholder: this.key('please_select_inspection_type'), options: this.typeOptions, clearable: true, style: { width: '90%' }, onChange: this.onTypeChange }
        ]
      ]

      if (String(this.formData.type) === '1') {
        cols.push([
          { type: 'input', prop: 'standard', label: this.key('judgment_standard'), placeholder: this.key('please_enter'), disabled: true, style: { width: '90%' } },
          { type: 'input', prop: 'unit', label: this.key('unit'), placeholder: this.key('please_enter_unit'), clearable: true, style: { width: '90%' } }
        ])
      } else if (String(this.formData.type) === '2') {
        cols.push([
          { type: 'input', prop: 'lower', label: this.key('lower_limit'), placeholder: this.key('please_enter_lower_limit'), clearable: true, style: { width: '90%' } },
          { type: 'input', prop: 'ceiling', label: this.key('upper_limit'), placeholder: this.key('please_enter_upper_limit'), clearable: true, style: { width: '90%' } }
        ])
        cols.push([
          { type: 'input', prop: 'unit', label: this.key('unit'), placeholder: this.key('please_enter_unit'), clearable: true, style: { width: '90%' } }
        ])
      } else if (String(this.formData.type) === '3') {
        cols.push([
          { type: 'select', prop: 'standard', label: this.key('judgment_standard'), placeholder: this.key('please_select'), options: [{ label: this.$t(this.key('upper_limit_label')), value: '上限' }, { label: this.$t(this.key('lower_limit_label')), value: '下限' }], clearable: true, style: { width: '90%' } },
          { type: 'input', prop: 'numeric', label: this.key('numeric'), placeholder: this.key('please_enter_numeric_value'), clearable: true, style: { width: '90%' } }
        ])
        cols.push([
          { type: 'input', prop: 'unit', label: this.key('unit'), placeholder: this.key('please_enter_unit'), clearable: true, style: { width: '90%' } }
        ])
      }

      if (this.formData.type) {
        cols.push([
          { type: 'input', prop: 'tools', label: this.key('inspection_tool'), placeholder: this.key('please_enter_inspection_tool'), clearable: true, style: { width: '90%' } },
          { type: 'input', prop: 'quantity', label: this.key('inspection_quantity'), placeholder: this.key('please_enter_inspection_quantity'), clearable: true, style: { width: '90%' } }
        ])
      }
      return cols
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'code', label: this.key('project_code'), minWidth: 120, showOverflowTooltip: true },
      { prop: 'name', label: this.key('project_name'), minWidth: 120, showOverflowTooltip: true },
      { prop: 'method', label: this.key('process_requirement'), minWidth: 150, showOverflowTooltip: true },
      { prop: 'type', label: this.key('judgment_type'), minWidth: 110, slot: 'itemType' },
      { prop: 'standard', label: this.key('judgment_standard'), minWidth: 140, showOverflowTooltip: true },
      { prop: 'unit', label: this.key('unit'), minWidth: 90, showOverflowTooltip: true },
      { prop: 'tools', label: this.key('inspection_tool'), minWidth: 130, showOverflowTooltip: true },
      { prop: 'quantity', label: this.key('inspection_quantity'), minWidth: 120, showOverflowTooltip: true },
      { prop: '_actions', label: this.key('operation'), width: 140, fixed: 'right' }
    ], { selectionWidth: 0 })
    const btns = useTableButtons({
      toolbar: [{ key: 'add_item', label: this.key('add_item'), icon: 'el-icon-plus', type: 'primary', auth: '/quality_control/first_inspection/setting/update', onClick: this.openAdd }],
      row: [
        { key: 'edit', label: this.key('edit'), icon: 'el-icon-edit', auth: '/quality_control/first_inspection/setting/update', onClick: this.openEdit },
        { key: 'delete', label: this.key('delete'), icon: 'el-icon-delete', color: 'danger', auth: '/quality_control/first_inspection/setting/delete', onClick: this.handleDelete }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
  },
  methods: {
    emptyForm () {
      return {
        quality_process_setting_id: undefined,
        code: '',
        name: '',
        method: '',
        type: '',
        standard: '',
        lower: '',
        ceiling: '',
        numeric: '',
        unit: '',
        tools: '',
        quantity: ''
      }
    },
    typeText (type) {
      const map = { 1: 'enumeration', 2: 'numeric', 3: 'limit' }
      return this.$t(this.key(map[Number(type)] || 'unknown'))
    },
    onOpen () {
      this.pagination.current = 1
      this.fetchData()
    },
    onClose () {
      this.tableData = []
      this.resetForm()
      this.$emit('saved')
    },
    async fetchData () {
      if (!this.settingRow || !this.settingRow.id) return
      this.loading = true
      try {
        const res = await fetchSettingItemList({
          page_no: this.pagination.current,
          page_size: this.pagination.size,
          quality_process_setting_id: this.settingRow.id
        })
        const { list, total } = readList(res)
        this.tableData = list
        this.pagination.total = total
      } finally {
        this.loading = false
      }
    },
    onPageChange (page) {
      this.pagination.current = page.current
      this.pagination.size = page.size
      this.fetchData()
    },
    openAdd () {
      this.handleType = 'create'
      this.formTitle = this.key('add_item_title')
      this.resetForm()
      this.formData.quality_process_setting_id = this.settingRow && this.settingRow.id
      this.formVisible = true
    },
    openEdit (row) {
      const range = String(row.type) === '2' && row.standard ? String(row.standard).split('~') : []
      this.handleType = 'edit'
      this.editId = row.id
      this.formTitle = this.key('edit_item_title')
      this.formData = {
        ...this.emptyForm(),
        ...row,
        quality_process_setting_id: this.settingRow && this.settingRow.id,
        type: row.type === undefined || row.type === null ? '' : String(row.type),
        lower: range[0] || '',
        ceiling: range[1] || '',
        numeric: row.numeric || ''
      }
      this.formVisible = true
    },
    resetForm () {
      this.formData = this.emptyForm()
      this.editId = ''
    },
    onTypeChange (value) {
      if (String(value) === '1') {
        this.formData.standard = 'GOOD:NG'
        this.formData.lower = ''
        this.formData.ceiling = ''
        this.formData.numeric = ''
      } else if (String(value) === '2') {
        this.formData.standard = ''
        this.formData.numeric = ''
      } else if (String(value) === '3') {
        this.formData.standard = ''
        this.formData.lower = ''
        this.formData.ceiling = ''
      }
    },
    buildSubmitData () {
      const data = { ...this.formData, quality_process_setting_id: this.settingRow && this.settingRow.id }
      if (String(data.type) === '2') data.standard = `${data.lower || ''}~${data.ceiling || ''}`
      if (String(data.type) === '1') data.standard = 'GOOD:NG'
      delete data.lower
      delete data.ceiling
      return data
    },
    async onSubmit () {
      this.submitting = true
      try {
        const data = this.buildSubmitData()
        if (this.handleType === 'create') {
          await createSettingItem(data)
        } else {
          await editSettingItem({ ...data, id: this.editId })
        }
        this.$message.success(this.$t(this.key('operation_success')))
        this.formVisible = false
        this.fetchData()
      } finally {
        this.submitting = false
      }
    },
    async handleDelete (row) {
      const cancelled = await this.$confirmAction({
        message: this.key('delete_confirm'),
        title: this.key('tip'),
        confirmButtonText: this.key('confirm'),
        cancelButtonText: this.key('cancel'),
        closeOnClickModal: false
      }, () => deleteSettingItem({ id: row.id }))
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.fetchData()
    }
  }
}
</script>
