<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('code'))">
            <el-input
              v-model="search.code"
              :placeholder="$t(key('enter_code'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('name'))">
            <el-input
              v-model="search.name"
              :placeholder="$t(key('enter_name'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('scada_node'))">
            <el-input
              v-model="search.scada_node"
              :placeholder="$t(key('enter_scada_node'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('status'))">
            <el-select
              v-model="search.status"
              :placeholder="$t(key('select_status'))"
              clearable
              style="width:140px"
            >
              <el-option :value="1" :label="$t(key('enable'))" />
              <el-option :value="0" :label="$t(key('disable'))" />
            </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/data-collection-configuration"
      :help-text="$t(ckey('help'))"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    />

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :width="'50%'"
      :form-cols="formCols"
      :form-data="formData"
      :rules="rules"
      :label-width="'120px'"
      :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 {
  getDataCollectionConfigList,
  createDataCollectionConfig,
  editDataCollectionConfig,
  deleteDataCollectionConfig
} from '@/api/production-master-data/data-collection-configuration'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'

export default {
  name: 'production-master-data-data-collection-configuration',
  components: { PageTable, PageDialogForm },
  mixins: [
    i18nMixin('page.production_master_data.spc_configuration.data_collection_configuration'),
    confirmMixin
  ],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: { code: '', name: '', scada_node: '', status: '' },
      pagination: { current: 1, size: 10, total: 0 },
      formData: {
        code: '',
        name: '',
        scada_node: '',
        collect_type: '',
        interval: 1,
        status: 1,
        remark: ''
      },
      rules: {
        code: [
          { required: true, message: this.key('enter_code'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('remark_length'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('enter_name'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('remark_length'), trigger: 'blur' }
        ],
        scada_node: [
          { required: true, message: this.key('enter_scada_node'), trigger: 'blur' }
        ],
        collect_type: [
          { required: true, message: this.key('select_collect_type'), trigger: 'change' }
        ],
        interval: [
          { required: true, message: this.key('enter_interval'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.key('select_status'), trigger: 'change' }
        ]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formCols: [
        [
          {
            type: 'input',
            prop: 'code',
            label: this.key('code'),
            placeholder: this.key('enter_code'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'name',
            label: this.key('name'),
            placeholder: this.key('enter_name'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'scada_node',
            label: this.key('scada_node'),
            placeholder: this.key('enter_scada_node'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'select',
            prop: 'collect_type',
            label: this.key('collect_type'),
            placeholder: this.key('select_collect_type'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: [
              { label: this.key('real_time'), value: 'real_time' },
              { label: this.key('periodic'), value: 'periodic' },
              { label: this.key('trigger'), value: 'trigger' }
            ]
          }
        ],
        [
          {
            type: 'input',
            prop: 'interval',
            inputType: 'number',
            label: this.key('interval'),
            placeholder: this.key('enter_interval'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'select',
            prop: 'status',
            label: this.key('status'),
            placeholder: this.key('select_status'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: [
              { label: this.key('enable'), value: 1 },
              { label: this.key('disable'), value: 0 }
            ]
          }
        ],
        [
          {
            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%' }
          }
        ]
      ]
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'sort', label: this.key('sort'), width: 80 },
      { prop: 'code', label: this.key('code'), minWidth: 120 },
      { prop: 'name', label: this.key('name'), minWidth: 140 },
      { prop: 'scada_node', label: this.key('scada_node'), minWidth: 140 },
      { prop: 'collect_type_name', label: this.key('collect_type'), minWidth: 120 },
      { prop: 'interval', label: this.key('interval'), width: 100 },
      { prop: 'status_name', label: this.key('status'), width: 100, slot: true },
      { prop: 'remark', label: this.key('remark'), minWidth: 120 },
      { prop: '_actions', label: this.key('operation'), width: 160, fixed: 'right' }
    ])
    const btns = useTableButtons({
      toolbar: [
        {
          key: 'add',
          label: this.key('add'),
          icon: 'el-icon-plus',
          type: 'primary',
          auth: '/production_configuration/spc_configuration/binding_scada_node/create',
          onClick: this.openAdd
        }
      ],
      row: [
        {
          key: 'edit',
          label: this.key('edit'),
          icon: 'el-icon-edit',
          auth: '/production_configuration/spc_configuration/binding_scada_node/edit',
          onClick: this.openEdit
        },
        {
          key: 'delete',
          label: this.key('delete'),
          icon: 'el-icon-delete',
          color: 'danger',
          auth: '/production_configuration/spc_configuration/binding_scada_node/delete',
          onClick: this.handleDelete
        }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    async fetchData () {
      this.loading = true
      try {
        const res = await getDataCollectionConfigList({
          ...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: '', scada_node: '', status: '' }
      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: '',
        scada_node: '',
        collect_type: '',
        interval: 1,
        status: 1,
        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,
        scada_node: row.scada_node || '',
        collect_type: row.collect_type || '',
        interval: row.interval || 1,
        status: typeof row.status === 'number' ? row.status : 1,
        remark: row.remark || ''
      }
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createDataCollectionConfig(this.formData)
        } else {
          await editDataCollectionConfig({ ...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')
        },
        () => deleteDataCollectionConfig({ 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;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
