<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('process_unit_code'))">
            <el-input
              v-model="search.code"
              :placeholder="$t(key('enter_process_unit_code'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('process_unit_name'))">
            <el-input
              v-model="search.name"
              :placeholder="$t(key('enter_process_unit_name'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('device_category'))">
            <el-select
              v-model="search.device_category_id"
              :placeholder="$t(key('select_device_category'))"
              clearable
              filterable
              style="width:200px"
              @focus="loadDeviceCategoryOptions"
              @change="onSearch"
            >
              <el-option
                v-for="item in deviceCategoryOptions"
                :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('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/process-step"
      :help-text="$t(ckey('help'))"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    >
      <template #col-is_denglu_process="{ row }">
        <el-tag v-if="String(row.is_denglu_process) === '1'" size="mini">{{ $t(key('yes')) }}</el-tag>
        <el-tag v-else type="warning" size="mini">{{ $t(key('no')) }}</el-tag>
      </template>
    </page-table>

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :width="'35%'"
      :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"
    />

    <technology-flow-model
      :visible.sync="settingVisible"
      :title="settingTitle"
      :type="settingType"
      :code="settingCode"
      :width="settingWidth"
      :plugin-data="settingPluginData"
      @close="settingVisible = false"
      @submit="handleSettingSubmit"
    />

    <result-param
      :visible.sync="resultVisible"
      :title="resultTitle"
      :workingsubclass_id="currentRowId"
      @close="resultVisible = false"
    />
  </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 {
  getProcessStepList,
  createProcessStep,
  editProcessStep,
  deleteProcessStep,
  settingSubmit
} from '@/api/production-master-data/process-step'
import { getDeviceCategoryAll } from '@/api/production-master-data/device-category'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'
import TechnologyFlowModel from './components/technology-flow-model.vue'
import ResultParam from './components/result-param.vue'

export default {
  name: 'production-master-data-process-step',
  components: { PageTable, PageDialogForm, TechnologyFlowModel, ResultParam },
  mixins: [i18nMixin('page.production_master_data.process_model.process_step'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: { code: '', name: '', device_category_id: '' },
      pagination: { current: 1, size: 10, total: 0 },
      deviceCategoryOptions: [],
      formData: { code: '', name: '', device_category_id: '', is_denglu_process: '0', remark: '' },
      settingVisible: false,
      settingTitle: '',
      settingType: '',
      settingCode: '',
      settingWidth: '50%',
      settingPluginData: '',
      resultVisible: false,
      resultTitle: '',
      currentRowId: '',
      rules: {
        code: [
          { required: true, message: this.key('enter_process_unit_code'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('length_1_100'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('enter_process_unit_name'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('length_1_100'), trigger: 'blur' }
        ],
        device_category_id: [
          { required: true, message: this.key('select_device_category'), trigger: 'change' }
        ],
        is_denglu_process: [
          { required: true, message: this.key('select_login_process'), trigger: 'change' }
        ]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formCols: [
        [
          {
            type: 'input',
            prop: 'code',
            label: this.key('process_unit_code'),
            placeholder: this.key('enter_process_unit_code'),
            clearable: true,
            disabled: false,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'name',
            label: this.key('process_unit_name'),
            placeholder: this.key('enter_process_unit_name'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'select',
            prop: 'device_category_id',
            label: this.key('device_category'),
            placeholder: this.key('select_device_category'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: [],
            onFocus: this.loadDeviceCategoryOptions
          }
        ],
        [
          {
            type: 'select',
            prop: 'is_denglu_process',
            label: this.key('login_process'),
            placeholder: this.key('select_login_process'),
            clearable: false,
            filterable: true,
            style: { width: '90%' },
            options: [
              { label: this.$t(this.key('yes')), value: '1' },
              { label: this.$t(this.key('no')), value: '0' }
            ]
          }
        ],
        [
          {
            type: 'input',
            prop: 'remark',
            inputType: 'textarea',
            autosize: { minRows: 2, maxRows: 6 },
            label: this.key('remark'),
            placeholder: this.key('remark_required'),
            clearable: true,
            style: { width: '90%' }
          }
        ]
      ]
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'code', label: this.key('process_unit_code'), minWidth: 120 },
      { prop: 'name', label: this.key('process_unit_name'), minWidth: 120 },
      { prop: 'device_category_name', label: this.key('device_category'), minWidth: 120 },
      { prop: 'is_denglu_process', label: this.key('login_process'), width: 120, slot: 'is_denglu_process' },
      { prop: 'remark', label: this.key('remark') },
      { prop: '_actions', label: this.key('operation'), width: 350, fixed: 'right' }
    ])
    const btns = useTableButtons({
      toolbar: [
        {
          key: 'add',
          label: this.key('add'),
          icon: 'el-icon-plus',
          type: 'primary',
          auth: '/production_configuration/technology_model/technology_flow_workingsubclass/create',
          onClick: this.openAdd
        }
      ],
      row: [
        {
          key: 'edit',
          label: this.key('edit'),
          icon: 'el-icon-edit',
          auth: '/production_configuration/technology_model/technology_flow_workingsubclass/edit',
          onClick: this.openEdit
        },
        {
          key: 'setting',
          label: this.key('preset_setting'),
          icon: 'el-icon-setting',
          color: 'warning',
          auth: '/production_configuration/technology_model/technology_flow_workingsubclass/setting',
          onClick: this.openSetting,
          visible: row => !!row.setting_plugin || this.isFormationSettingRow(row)
        },
        {
          key: 'result',
          label: this.key('preset_result_param'),
          icon: 'el-icon-document',
          color: 'success',
          auth: '/production_configuration/technology_model/technology_flow_workingsubclass/result',
          onClick: this.openResult
        },
        {
          key: 'delete',
          label: this.key('delete'),
          icon: 'el-icon-delete',
          color: 'danger',
          auth: '/production_configuration/technology_model/technology_flow_workingsubclass/delete',
          onClick: this.handleDelete
        }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.loadDeviceCategoryOptions()
    this.fetchData()
  },
  methods: {
    normalizeResponse (res) {
      const 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
      }
      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: getTotal(res, item.length) }
        }
        const list = item.data || item.list || item.rows || item.records || item.items
        if (Array.isArray(list)) {
          return { list, total: getTotal(item, getTotal(res, list.length)) }
        }
      }
      return { list: [], total: 0 }
    },
    loadDeviceCategoryOptions () {
      if (this.deviceCategoryOptions.length > 0) return Promise.resolve()
      return getDeviceCategoryAll().then(res => {
        const list = this.normalizeResponse(res).list
        this.deviceCategoryOptions = list.map(item => ({
          label: item.name,
          value: item.id
        }))
        this.formCols[2][0].options = this.deviceCategoryOptions
      })
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getProcessStepList({
          ...this.search,
          page_no: this.pagination.current,
          page_size: this.pagination.size
        })
        const data = this.normalizeResponse(res)
        this.tableData = data.list
        this.pagination.total = data.total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { code: '', name: '', device_category_id: '' }
      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
    },
    isFormationSettingRow (row) {
      return ['FORMATION', 'YC', 'HC', 'IC', 'FORMATION_SS'].includes(row.device_category_code)
    },
    getSettingWidth (row) {
      if (row.setting_plugin_width) return `${row.setting_plugin_width}%`
      if (this.isFormationSettingRow(row) || row.setting_plugin === 'FormationPlugin') return '90%'
      if (['DvPlugin', 'OcvrPlugin', 'NonStandardProcessSettingPlugin'].includes(row.setting_plugin)) return '80%'
      return '35%'
    },
    resetForm () {
      this.formData = { code: '', name: '', device_category_id: '', is_denglu_process: '0', remark: '' }
      this.editId = ''
      this.$nextTick(() => {
        this.formCols[0][0].disabled = false
      })
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_process_unit')
      this.loadDeviceCategoryOptions().then(() => {
        this.$nextTick(() => {
          this.$refs.dialogForm && this.$refs.dialogForm.reset()
          this.resetForm()
          this.dialogVisible = true
        })
      })
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_process_unit')
      this.editId = row.id
      this.formData = {
        code: row.code,
        name: row.name,
        device_category_id: row.device_category_id || '',
        is_denglu_process: String(row.is_denglu_process || '0'),
        remark: row.remark || ''
      }
      this.$nextTick(() => {
        this.formCols[0][0].disabled = true
      })
      this.loadDeviceCategoryOptions().then(() => {
        this.dialogVisible = true
      })
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createProcessStep(this.formData)
        } else {
          await editProcessStep({ ...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('tips')
        },
        () => deleteProcessStep({ 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()
    },
    openSetting (row) {
      this.currentRowId = row.id
      this.settingTitle = `【${row.name}】${this.$t(this.key('preset_setting'))}`
      this.settingType = row.setting_plugin || (this.isFormationSettingRow(row) ? 'FormationPlugin' : '')
      this.settingCode = row.code
      this.settingWidth = this.getSettingWidth(row)
      this.settingPluginData = row.default_setting || {}
      this.settingVisible = true
    },
    async handleSettingSubmit (data) {
      await settingSubmit({
        id: this.currentRowId,
        default_setting: JSON.stringify(data)
      })
      this.$message.success(this.$t(this.key('operation_success')))
      this.settingVisible = false
      this.fetchData()
    },
    openResult (row) {
      this.currentRowId = row.id
      this.resultTitle = `【${row.name}】${this.$t(this.key('preset_result_param'))}`
      this.resultVisible = true
    }
  }
}
</script>

<style scoped>
.search-bar {
  padding: 10px 0;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
