<template>
  <el-dialog
    :title="$t(title)"
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="handleClose"
    width="80%"
  >
    <div class="search-content">
      <el-card class="box-card">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('name'))">
            <el-input
              v-model="searchForm.name"
              :placeholder="$t(key('enter_name'))"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t(key('param'))">
            <el-input
              v-model="searchForm.code"
              :placeholder="$t(key('enter_param'))"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onSearch">
              {{ $t(key('query')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-table
      ref="table"
      :data="tableData"
      border
      :loading="loading"
      max-height="450"
      style="width: 100%"
    >
      <el-table-column :label="$t(key('name'))" prop="name" width="200" show-overflow-tooltip />
      <el-table-column :label="$t(key('param'))" prop="code" width="150" show-overflow-tooltip />
      <el-table-column :label="$t(key('category'))" prop="field_type" width="120" />
      <el-table-column :label="$t(key('remark'))" prop="remark" show-overflow-tooltip />
      <el-table-column :label="$t(key('is_unique'))" width="100" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.is_only === 1" type="success" size="mini">{{ $t(key('yes')) }}</el-tag>
          <el-tag v-else type="info" size="mini">{{ $t(key('no')) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t(key('is_upload'))" width="100" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.is_upload === 1" type="success" size="mini">{{ $t(key('yes')) }}</el-tag>
          <el-tag v-else type="info" size="mini">{{ $t(key('no')) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t(key('operation'))" width="120" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
            {{ $t(key('edit')) }}
          </el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" style="color: #F56C6C" @click="handleDelete(row)">
            {{ $t(key('delete')) }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="pagination.current"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.size"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" @click="handleAdd">{{ $t(key('add_row')) }}</el-button>
      <el-button type="success" size="mini" icon="el-icon-download" @click="handleImport">{{ $t(key('import')) }}</el-button>
      <el-button size="mini" @click="handleClose">{{ $t(key('close')) }}</el-button>
    </div>

    <el-dialog
      :title="$t(dialogTitle)"
      :visible.sync="innerVisible"
      append-to-body
      width="600px"
      :before-close="handleInnerClose"
    >
      <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
        <el-form-item :label="$t(key('param'))" prop="code">
          <el-input v-model="formData.code" :placeholder="$t(key('enter_param'))" clearable />
        </el-form-item>
        <el-form-item :label="$t(key('name'))" prop="name">
          <el-input v-model="formData.name" :placeholder="$t(key('enter_name'))" clearable />
        </el-form-item>
        <el-form-item :label="$t(key('category'))" prop="field_type">
          <el-select v-model="formData.field_type" :placeholder="$t(key('select_type'))" style="width: 100%">
            <el-option label="FLOAT" value="FLOAT" />
            <el-option label="INT" value="INT" />
            <el-option label="VARCHAR" value="VARCHAR" />
            <el-option label="TEXT" value="TEXT" />
            <el-option label="TIMESTAMP" value="TIMESTAMP" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t(key('remark'))">
          <el-input v-model="formData.remark" type="textarea" :rows="2" :placeholder="$t(key('remark_required'))" />
        </el-form-item>
        <el-form-item :label="$t(key('is_unique'))">
          <el-radio-group v-model="formData.is_only">
            <el-radio :label="1">{{ $t(key('yes')) }}</el-radio>
            <el-radio :label="0">{{ $t(key('no')) }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t(key('is_upload'))">
          <el-radio-group v-model="formData.is_upload">
            <el-radio :label="1">{{ $t(key('yes')) }}</el-radio>
            <el-radio :label="0">{{ $t(key('no')) }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleInnerClose">{{ $t(key('cancel')) }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{ $t(key('confirm')) }}</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { i18nMixin } from '@/composables/useI18n'
import {
  getOptionalParamsList,
  createOptionalParams,
  editOptionalParams,
  deleteOptionalParams
} from '@/api/production-master-data/optional-params'

export default {
  name: 'ProcessStepResultParam',
  components: {},
  mixins: [i18nMixin('page.production_master_data.process_model.process_step')],
  props: {
    title: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    workingsubclass_id: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      loading: false,
      tableData: [],
      searchForm: { name: '', code: '' },
      pagination: { current: 1, size: 10, total: 0 },
      innerVisible: false,
      dialogTitle: '',
      formData: {
        id: '',
        code: '',
        name: '',
        field_type: '',
        remark: '',
        is_only: 0,
        is_upload: 0
      },
      rules: {
        code: [{ required: true, message: this.key('enter_param'), trigger: 'blur' }],
        name: [{ required: true, message: this.key('enter_name'), trigger: 'blur' }],
        field_type: [{ required: true, message: this.key('select_type'), trigger: 'change' }]
      }
    }
  },
  watch: {
    workingsubclass_id: {
      handler (val) {
        if (val) {
          this.fetchData()
        }
      },
      immediate: true
    }
  },
  methods: {
    handleClose () {
      this.$emit('close')
    },
    handleInnerClose () {
      this.innerVisible = false
      this.$refs.form && this.$refs.form.resetFields()
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    fetchData () {
      if (!this.workingsubclass_id) return
      this.loading = true
      getOptionalParamsList({
        workingsubclass_id: this.workingsubclass_id,
        page_no: this.pagination.current,
        page_size: this.pagination.size,
        ...this.searchForm
      }).then(res => {
        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
      })
    },
    handleSizeChange (size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.fetchData()
    },
    handleCurrentChange (current) {
      this.pagination.current = current
      this.fetchData()
    },
    handleAdd () {
      this.dialogTitle = this.key('add_row')
      this.formData = {
        id: '',
        code: '',
        name: '',
        field_type: '',
        remark: '',
        is_only: 0,
        is_upload: 0
      }
      this.innerVisible = true
    },
    handleEdit (row) {
      this.dialogTitle = this.key('edit')
      this.formData = {
        id: row.id,
        code: row.code,
        name: row.name,
        field_type: row.field_type,
        remark: row.remark || '',
        is_only: row.is_only || 0,
        is_upload: row.is_upload || 0
      }
      this.innerVisible = true
    },
    handleDelete (row) {
      this.$confirm(this.$t(this.key('confirm_delete_data')), this.$t(this.key('tips')), {
        confirmButtonText: this.$t(this.key('confirm')),
        cancelButtonText: this.$t(this.key('cancel')),
        type: 'warning'
      }).then(() => {
        deleteOptionalParams({ workingsubclass_id: this.workingsubclass_id, id: row.id }).then(() => {
          this.$message.success(this.$t(this.key('operation_success')))
          this.fetchData()
        })
      }).catch(() => {})
    },
    handleSubmit () {
      this.$refs.form.validate(valid => {
        if (!valid) return
        const action = this.formData.id ? editOptionalParams : createOptionalParams
        const data = { workingsubclass_id: this.workingsubclass_id, ...this.formData }
        action(data).then(() => {
          this.$message.success(this.$t(this.key('operation_success')))
          this.innerVisible = false
          this.$refs.form.resetFields()
          this.fetchData()
        })
      })
    },
    handleImport () {
      this.$message.info(this.$t(this.key('import_tip')))
    }
  }
}
</script>

<style scoped>
.search-content {
  margin-bottom: 15px;
}
.box-card {
  width: 100%;
}
</style>
