<template>
  <d2-container>
    <template #header>
      <el-form :inline="true" size="mini">
        <el-form-item :label="$t(key('working_subclass'))" v-if="showProcessFilter">
          <el-select v-model="search.working_subclass" clearable filterable style="width:200px" :placeholder="$t(key('select_working_subclass'))">
            <el-option v-for="item in workingSubclassOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t(key('data_category'))" v-if="showCategoryFilter">
          <el-select v-model="search.categoryName" clearable style="width:180px" :placeholder="$t(key('select_data_category'))">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="$t(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>
    </template>

    <page-table
      :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="520px"
      :form-cols="formCols"
      :form-data="formData"
      :rules="rules"
      :submitting="submitting"
      :confirm-text="key('confirm')"
      :cancel-text="key('cancel')"
      @submit="onDialogSubmit"
    />
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { useTableButtons } from '@/composables/useTableButtons'
import { i18nMixin } from '@/composables/useI18n'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'
import { getQueryNode, addNode, updateNode, removeNode } from '@/api/scada-manage/edge-manager'
import { getWorkingsubclassAll } from '@/api/production-master-data/process-step'
import { getWorkshopPointAll } from '@/api/scada-manage/workshop-point'

export default {
  name: 'scada-node-config-page',
  components: { PageTable, PageDialogForm },
  mixins: [i18nMixin('page.scada_manage.basic_configuration.ems_configure')],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      workingSubclassOptions: [],
      search: { working_subclass: '', categoryName: 'ENVIRONMENTAL_DATA' },
      pagination: { current: 1, size: 10, total: 0 },
      dialogVisible: false,
      dialogTitle: '',
      handleType: 'create',
      editRow: null,
      showProcessFilter: false,
      showCategoryFilter: false,
      categoryOptions: [{ value: 'ENVIRONMENTAL_DATA', label: 'page.scada_manage.basic_configuration.ems_configure.environmental_data' }],
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formData: { code: '', name: '', type: 'varchar', category: 'ENVIRONMENTAL_DATA', working_subclass: '', data_length: 1, unit: '', note: '' },
      rules: {
        code: [{ required: true, message: this.key('enter_code'), trigger: 'blur' }],
        name: [{ required: true, message: this.key('enter_name'), trigger: 'blur' }],
        type: [{ required: true, message: this.key('select_type'), trigger: 'change' }],
        category: [{ required: true, message: this.key('select_data_category'), trigger: 'change' }],
        working_subclass: [{ required: true, message: this.key('select_working_subclass'), trigger: 'change' }]
      },
      formCols: []
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'id', label: this.key('sort'), width: 80 },
      { prop: 'code', label: this.key('code'), minWidth: 130 },
      { prop: 'name', label: this.key('name'), minWidth: 140 },
      { prop: 'type', label: this.key('type'), width: 100 },
      { prop: 'categoryName', label: this.key('data_category'), minWidth: 140 },
      { prop: 'worksubclass_name', label: this.key('working_subclass'), minWidth: 150 },
      { prop: 'data_length', label: this.key('data_length'), width: 100 },
      { prop: 'unit', label: this.key('unit'), width: 100 },
      { prop: 'create_time', label: this.key('create_time'), minWidth: 160 },
      { prop: 'note', label: this.key('remark'), minWidth: 160 },
      { prop: '_actions', label: this.key('operation'), width: 160, fixed: 'right' }
    ], { selectionWidth: 0 })
    const buttons = useTableButtons({
      toolbar: [{ key: 'add', label: this.key('add'), icon: 'el-icon-plus', type: 'primary', auth: '/scada_manage/basic_configuration/scadaconfigure/add', onClick: this.openAdd }],
      row: [
        { key: 'edit', label: this.key('edit'), icon: 'el-icon-edit', auth: '/scada_manage/basic_configuration/scadaconfigure/edit', onClick: this.openEdit },
        { key: 'delete', label: this.key('delete'), icon: 'el-icon-delete', color: 'danger', auth: '/scada_manage/basic_configuration/scadaconfigure/delete', onClick: this.handleDelete }
      ]
    }, this.$permission)
    this.toolbarButtons = buttons.toolbarButtons
    this.rowButtons = buttons.rowButtons
    this.formCols = this.makeFormCols()
    this.loadOptions()
    this.fetchData()
  },
  methods: {
    makeFormCols () {
      return [
        [{ type: 'input', prop: 'code', label: this.key('code'), placeholder: this.key('enter_code'), disabled: this.handleType === 'edit' }],
        [{ type: 'input', prop: 'name', label: this.key('name'), placeholder: this.key('enter_name') }],
        [{ type: 'select', prop: 'type', label: this.key('type'), placeholder: this.key('select_type'), options: ['varchar', 'text', 'int', 'bigint', 'double', 'real', 'float', 'jsonb', 'bool'].map(v => ({ label: v, value: v })), disabled: this.handleType === 'edit' }],
        [{ type: 'select', prop: 'category', label: this.key('data_category'), placeholder: this.key('select_data_category'), options: this.categoryOptions.map(item => ({ ...item, label: this.$t(item.label) })), disabled: this.handleType === 'edit' }],
        [{ type: 'select', prop: 'working_subclass', label: this.key('working_subclass'), placeholder: this.key('select_working_subclass'), options: this.workingSubclassOptions, disabled: this.handleType === 'edit' }],
        [{ type: 'input', prop: 'data_length', label: this.key('data_length'), placeholder: this.key('enter_data_length') }],
        [{ type: 'input', prop: 'unit', label: this.key('unit'), placeholder: this.key('enter_unit') }],
        [{ type: 'input', prop: 'note', label: this.key('remark'), placeholder: this.key('enter_remark'), inputType: 'textarea', autosize: { minRows: 2, maxRows: 4 } }]
      ]
    },
    async loadOptions () {
      try {
        const loader = true ? getWorkshopPointAll : getWorkingsubclassAll
        const res = await loader()
        const list = Array.isArray(res) ? res : (res.data || [])
        this.workingSubclassOptions = list.map(item => ({ label: item.name || item.code, value: item.code }))
        this.formCols = this.makeFormCols()
      } catch (e) {}
    },
    categoryText (category) {
      const item = this.categoryOptions.find(opt => opt.value === category)
      return item ? this.$t(item.label) : category
    },
    workingSubclassText (code) {
      const item = this.workingSubclassOptions.find(opt => opt.value === code)
      return item ? item.label : code
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getQueryNode({ currentPage: this.pagination.current, pageSize: this.pagination.size, ...this.search })
        const list = Array.isArray(res) ? res : (res.data || [])
        this.tableData = list.map(item => ({ ...item, categoryName: this.categoryText(item.category), worksubclass_name: this.workingSubclassText(item.working_subclass) }))
        this.pagination.total = Array.isArray(res) ? res.length : (res.total || res.count || 0)
      } finally { this.loading = false }
    },
    onSearch () { this.pagination.current = 1; this.fetchData() },
    onReset () { this.search = { working_subclass: '', categoryName: 'ENVIRONMENTAL_DATA' }; this.onSearch() },
    onPageChange (page) { this.pagination.current = page.current; this.pagination.size = page.size; this.fetchData() },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_title')
      this.formData = { code: '', name: '', type: 'varchar', category: 'ENVIRONMENTAL_DATA', working_subclass: '', data_length: 1, unit: '', note: '' }
      this.formCols = this.makeFormCols()
      this.dialogVisible = true
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_title')
      this.editRow = row
      this.formData = { code: row.code, name: row.name, type: row.type, category: row.category || 'ENVIRONMENTAL_DATA', working_subclass: row.working_subclass, data_length: row.data_length, unit: row.unit, note: row.note }
      this.formCols = this.makeFormCols()
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await addNode({ action: 'add_node', node_data: JSON.stringify([this.formData]) })
        } else {
          await updateNode({ id: this.editRow.id, name: this.formData.name, note: this.formData.note, unit: this.formData.unit, data_length: this.formData.data_length, action: 'update_node' })
        }
        this.$message.success(this.$t(this.key('operation_success')))
        this.dialogVisible = false
        this.fetchData()
      } finally { this.submitting = false }
    },
    handleDelete (row) {
      this.$confirm(this.$t(this.key('confirm_delete')), this.$t(this.key('tip')), { type: 'warning' }).then(async () => {
        await removeNode({ action: 'remove_node', code: row.code, working_subclass: row.working_subclass })
        this.$message.success(this.$t(this.key('operation_success')))
        this.fetchData()
      }).catch(() => {})
    }
  }
}
</script>
