<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('result_param_code'))">
            <el-input
              v-model="search.result_param_code"
              :placeholder="$t(key('enter_result_param_code'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('result_param_name'))">
            <el-input
              v-model="search.result_param_name"
              :placeholder="$t(key('enter_result_param_name'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('scada_node_code'))">
            <el-input
              v-model="search.scada_node_code"
              :placeholder="$t(key('enter_scada_node_code'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('scada_node_name'))">
            <el-input
              v-model="search.scada_node_name"
              :placeholder="$t(key('enter_scada_node_name'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </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"
    >
      <template #col-category="{ row }">
        <span>{{ categoryText(row.category) }}</span>
      </template>
    </page-table>

    <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 { getOptionalParamsList } from '@/api/production-master-data/optional-params'
import { getWorkingsubclassAll } from '@/api/production-master-data/process-step'
import { getQueryCodes } from '@/api/scada-manage/edge-manager'
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: {
        result_param_code: undefined,
        result_param_name: undefined,
        scada_node_code: undefined,
        scada_node_name: undefined
      },
      pagination: { current: 1, size: 10, total: 0 },
      workingSubclassOptions: [],
      workingSubclassRawData: [],
      resultParamOptions: [],
      scadaNodeOptions: [],
      formData: {
        working_subclass_id: undefined,
        category: undefined,
        result_param_code: undefined,
        scada_node_code: undefined,
        result_param_type: 1
      },
      rules: {
        working_subclass_id: [
          { required: true, message: this.key('select_working_subclass'), trigger: 'change' }
        ],
        category: [
          { required: true, message: this.key('select_data_type'), trigger: 'change' }
        ],
        result_param_code: [
          { required: true, message: this.key('select_result_param'), trigger: 'change' }
        ],
        scada_node_code: [
          { required: true, message: this.key('select_scada_node'), trigger: 'change' }
        ],
        result_param_type: [
          { required: true, message: this.key('select_data_type'), trigger: 'change' }
        ]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formCols: []
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'working_subclass', label: this.key('working_subclass'), minWidth: 140 },
      { prop: 'result_param_name', label: this.key('result_param_name'), minWidth: 160 },
      { prop: 'result_param_code', label: this.key('result_param_code'), minWidth: 160 },
      { prop: 'scada_node_name', label: this.key('scada_node_name'), minWidth: 160 },
      { prop: 'scada_node_code', label: this.key('scada_node_code'), minWidth: 160 },
      { prop: 'category', label: this.key('category'), minWidth: 140, slot: 'category' },
      { prop: 'create_time', label: this.key('create_time'), minWidth: 160 },
      { prop: 'update_data', label: this.key('update_data'), minWidth: 160 },
      { 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/matetial_model/bom/create',
          onClick: this.openAdd
        }
      ],
      row: [
        {
          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.formCols = this.makeFormCols()
    this.loadWorkingSubclassOptions()
    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 data = this.normalizeResponse(res)
        this.tableData = data.list.map((row, index) => this.normalizeRow(row, index))
        this.pagination.total = data.total
      } finally {
        this.loading = false
      }
    },
    normalizeResponse (res) {
      if (Array.isArray(res)) {
        return { list: res, total: res.length }
      }

      const containers = [
        res,
        res && res.data,
        res && res.data && res.data.data
      ].filter(Boolean)

      for (const item of containers) {
        if (Array.isArray(item)) {
          return {
            list: item,
            total: this.getTotal(res, item.length)
          }
        }
        const list = item.data || item.list || item.rows || item.records || item.results || item.items
        if (Array.isArray(list)) {
          return {
            list,
            total: this.getTotal(item, this.getTotal(res, list.length))
          }
        }
      }

      return { list: [], total: 0 }
    },
    getTotal (source, fallback) {
      if (!source) return fallback
      const total = source.count ?? source.total ?? source.total_count ?? source.record_count
      const value = Number(total)
      return Number.isNaN(value) ? fallback : value
    },
    firstValue (row, keys, defaultValue = '') {
      if (!row) return defaultValue
      for (const key of keys) {
        const value = row[key]
        if (value !== undefined && value !== null && value !== '') {
          return value
        }
      }
      return defaultValue
    },
    makeFormCols () {
      return [
        [
          {
            type: 'select',
            prop: 'working_subclass_id',
            label: this.key('working_subclass'),
            placeholder: this.key('select_working_subclass'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: this.workingSubclassOptions,
            onChange: this.onWorkingSubclassChange
          }
        ],
        [
          {
            type: 'select',
            prop: 'category',
            label: this.key('category'),
            placeholder: this.key('select_data_type'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: [
              { label: this.$t(this.key('process_inspection')), value: 'PROCESS_INSPECTION' },
              { label: this.$t(this.key('result_data')), value: 'RESULT_DATA' }
            ]
          }
        ],
        [
          {
            type: 'select',
            prop: 'result_param_code',
            label: this.key('result_param'),
            placeholder: this.key('select_result_param'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: this.resultParamOptions
          }
        ],
        [
          {
            type: 'select',
            prop: 'scada_node_code',
            label: this.key('scada_node'),
            placeholder: this.key('select_scada_node'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: this.scadaNodeOptions
          }
        ],
        [
          {
            type: 'select',
            prop: 'result_param_type',
            label: this.key('result_param_type'),
            placeholder: this.key('select_data_type'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: [
              { label: this.$t(this.key('measurement_type')), value: 1 },
              { label: this.$t(this.key('count_type')), value: 2 }
            ]
          }
        ]
      ]
    },
    normalizeList (res) {
      return this.normalizeResponse(res).list
    },
    categoryText (value) {
      const map = {
        PROCESS_INSPECTION: this.key('process_inspection'),
        RESULT_DATA: this.key('result_data')
      }
      return map[value] ? this.$t(map[value]) : (value || '')
    },
    async loadWorkingSubclassOptions () {
      try {
        const res = await getWorkingsubclassAll()
        const list = this.normalizeList(res)
        this.workingSubclassRawData = list
        this.workingSubclassOptions = list.map(item => ({
          label: item.name || item.working_subclass_name || item.code,
          value: item.id
        }))
        this.formCols = this.makeFormCols()
      } catch (e) {
        this.formCols = this.makeFormCols()
      }
    },
    findWorkingSubclassById (id) {
      return this.workingSubclassRawData.find(item => item.id === id)
    },
    async onWorkingSubclassChange (value) {
      this.formData.result_param_code = undefined
      this.formData.scada_node_code = undefined
      this.resultParamOptions = []
      this.scadaNodeOptions = []
      const workingSubclass = this.findWorkingSubclassById(value)
      if (!workingSubclass) {
        this.formCols = this.makeFormCols()
        return
      }
      const code = workingSubclass.code || workingSubclass.working_subclass
      await Promise.all([
        this.loadResultParamOptions(value),
        this.loadScadaNodeOptions(code)
      ])
      this.formCols = this.makeFormCols()
    },
    async loadResultParamOptions (workingsubclassId) {
      try {
        const res = await getOptionalParamsList({
          workingsubclass_id: workingsubclassId,
          page_no: 1,
          page_size: 10000
        })
        this.resultParamOptions = this.normalizeList(res).map(item => ({
          label: item.name || item.result_param_name || item.code,
          value: item.code || item.result_param_code
        }))
      } catch (e) {
        this.resultParamOptions = []
      }
    },
    normalizeScadaNodeList (res, workingSubclassCode) {
      const data = res && res.data ? res.data : res
      if (Array.isArray(data)) return data
      if (data && Array.isArray(data[workingSubclassCode])) return data[workingSubclassCode]
      if (data && Array.isArray(data.data)) return data.data
      return []
    },
    async loadScadaNodeOptions (workingSubclassCode) {
      try {
        const res = await getQueryCodes(workingSubclassCode)
        const list = this.normalizeScadaNodeList(res, workingSubclassCode)
        this.scadaNodeOptions = list.map(item => ({
          label: item.name || item.scada_node_name || item.code,
          value: item.code || item.scada_node_code
        }))
      } catch (e) {
        this.scadaNodeOptions = []
      }
    },
    normalizeRow (row) {
      return {
        ...row,
        id: this.firstValue(row, ['id', 'binding_scada_node_id', 'config_id']),
        working_subclass: this.firstValue(row, ['working_subclass', 'working_subclass_code', 'workingsubclass_code']),
        working_subclass_id: this.firstValue(row, ['working_subclass_id', 'workingsubclass_id']),
        result_param_name: this.firstValue(row, ['result_param_name', 'param_name', 'name']),
        result_param_code: this.firstValue(row, ['result_param_code', 'param_code', 'code']),
        scada_node_name: this.firstValue(row, ['scada_node_name', 'node_name']),
        scada_node_code: this.firstValue(row, ['scada_node_code', 'node_code']),
        category: this.firstValue(row, ['category', 'data_category']),
        create_time: this.firstValue(row, ['create_time', 'created_at']),
        update_data: this.firstValue(row, ['update_data', 'update_time', 'updated_at'])
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = {
        result_param_code: undefined,
        result_param_name: undefined,
        scada_node_code: undefined,
        scada_node_name: undefined
      }
      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 = {
        working_subclass_id: undefined,
        category: undefined,
        result_param_code: undefined,
        scada_node_code: undefined,
        result_param_type: 1
      }
      this.resultParamOptions = []
      this.scadaNodeOptions = []
      this.formCols = this.makeFormCols()
      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
      })
    },
    async openEdit (row) {
      if (!this.workingSubclassRawData.length) {
        await this.loadWorkingSubclassOptions()
      }
      const record = this.normalizeRow(row)
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_title')
      this.editId = record.id
      const workingSubclassId = record.working_subclass_id || this.getWorkingSubclassIdByCode(record.working_subclass)
      this.formData = {
        working_subclass_id: workingSubclassId,
        category: record.category,
        result_param_code: record.result_param_code,
        scada_node_code: record.scada_node_code,
        result_param_type: record.result_param_type || 1
      }
      this.prepareEditOptions(workingSubclassId, record).finally(() => {
        this.dialogVisible = true
      })
    },
    getWorkingSubclassIdByCode (code) {
      const target = this.workingSubclassRawData.find(item => item.code === code || item.working_subclass === code)
      return target && target.id
    },
    async prepareEditOptions (workingSubclassId, record) {
      const workingSubclass = this.findWorkingSubclassById(workingSubclassId)
      if (workingSubclass) {
        await Promise.all([
          this.loadResultParamOptions(workingSubclassId),
          this.loadScadaNodeOptions(workingSubclass.code || workingSubclass.working_subclass)
        ])
      }
      if (record.result_param_code && !this.resultParamOptions.some(item => item.value === record.result_param_code)) {
        this.resultParamOptions.push({ label: record.result_param_name || record.result_param_code, value: record.result_param_code })
      }
      if (record.scada_node_code && !this.scadaNodeOptions.some(item => item.value === record.scada_node_code)) {
        this.scadaNodeOptions.push({ label: record.scada_node_name || record.scada_node_code, value: record.scada_node_code })
      }
      this.formCols = this.makeFormCols()
    },
    buildSubmitData () {
      const workingSubclass = this.findWorkingSubclassById(this.formData.working_subclass_id)
      const workingSubclassCode = workingSubclass && (workingSubclass.code || workingSubclass.working_subclass)
      const scadaNode = this.scadaNodeOptions.find(item => item.value === this.formData.scada_node_code)
      return {
        ...this.formData,
        working_subclass: workingSubclassCode,
        scada_node_name: scadaNode ? scadaNode.label : undefined
      }
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        const submitData = this.buildSubmitData()
        if (this.handleType === 'create') {
          await createDataCollectionConfig(submitData)
        } else {
          await editDataCollectionConfig({ ...submitData, 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>
