<template>
  <el-dialog :title="title" :visible.sync="visible" append-to-body :close-on-click-modal="false" width="70%" :before-close="handleClose">
    <div class="toolbar">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="openAdd">
        {{ $t(key('add_calculation_script')) }}
      </el-button>
    </div>
    <el-table :data="tableData" border height="480" v-loading="loading">
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="code" :label="$t(key('script_code'))" min-width="130" show-overflow-tooltip />
      <el-table-column prop="name" :label="$t(key('script_name'))" min-width="150" show-overflow-tooltip />
      <el-table-column prop="interface_code" :label="$t(key('interface_name'))" min-width="220" show-overflow-tooltip />
      <el-table-column :label="$t(key('interface_position'))" width="130">
        <template slot-scope="{ row }">
          {{ row.interface_position === 'begin' ? $t(key('start_position')) : $t(key('end_position')) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t(key('status'))" width="110">
        <template slot-scope="{ row }">
          <span v-if="Number(row.status) === 1" class="status-on"><i class="el-icon-circle-check" /> {{ $t(key('enabled')) }}</span>
          <span v-else class="status-off"><i class="el-icon-circle-close" /> {{ $t(key('disabled')) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" :label="$t(key('remark'))" show-overflow-tooltip />
      <el-table-column :label="$t(key('operation'))" width="150" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="openEdit(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-dialog :title="$t(dialogTitle)" :visible.sync="formVisible" append-to-body width="900px" :close-on-click-modal="false">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
            <el-form-item :label="$t(key('script_code'))" prop="code">
              <el-input v-model="formData.code" :placeholder="$t(key('enter_code'))" clearable />
            </el-form-item>
            <el-form-item :label="$t(key('script_name'))" prop="name">
              <el-input v-model="formData.name" :placeholder="$t(key('enter_name'))" clearable />
            </el-form-item>
            <el-form-item :label="$t(key('interface_name'))" prop="interface_code">
              <el-select v-model="formData.interface_code" :placeholder="$t(key('select_interface'))" clearable filterable style="width:100%">
                <el-option v-for="item in interfaceOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t(key('interface_position'))" prop="interface_position">
              <el-select v-model="formData.interface_position" :placeholder="$t(key('select_interface_position'))" clearable style="width:100%">
                <el-option :label="$t(key('start_position'))" value="begin" />
                <el-option :label="$t(key('end_position'))" value="end" />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t(key('status'))" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio label="1">{{ $t(key('enabled')) }}</el-radio>
                <el-radio label="0">{{ $t(key('disabled')) }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t(key('remark'))">
              <el-input v-model="formData.remark" type="textarea" :rows="4" :placeholder="$t(key('enter_remark'))" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="14">
          <div class="script-editor-title">{{ $t(key('script_content')) }}</div>
          <el-input v-model="scriptContent" type="textarea" :rows="20" class="script-editor" :placeholder="$t(key('script_content_required'))" />
        </el-col>
      </el-row>
      <span slot="footer">
        <el-button @click="formVisible = false">{{ $t(key('cancel')) }}</el-button>
        <el-button type="primary" :loading="submitting" @click="submitForm">{{ $t(key('confirm')) }}</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { i18nMixin } from '@/composables/useI18n'
import {
  getCalculationScriptAll,
  createCalculationScript,
  editCalculationScript,
  deleteCalculationScript
} from '@/api/production-master-data/calculation-script'

export default {
  name: 'ProcessRoutingCardCalculationScript',
  mixins: [i18nMixin('page.production_master_data.process_model.process_routing.card')],
  props: {
    title: { type: String, default: '' },
    visible: { type: Boolean, default: false },
    flowProcessId: { type: [String, Number], default: '' }
  },
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      formVisible: false,
      dialogTitle: '',
      handleType: 'create',
      editId: '',
      scriptContent: '',
      formData: { code: '', name: '', interface_code: '', interface_position: '', status: '1', remark: '' },
      interfaceOptions: [
        { label: 'set_battery_process_result（成品段下料接口）', value: 'set_battery_process_result' },
        { label: 'set_material_input（制片段上料接口）', value: 'set_material_input' },
        { label: 'get_battery_process_route（电芯路由接口）', value: 'get_battery_process_route' },
        { label: 'set_wip_output_by_item_id（裸电芯下料接口）', value: 'set_wip_output_by_item_id' },
        { label: 'set_tray_process_result（托盘下料接口）', value: 'set_tray_process_result' }
      ],
      rules: {
        code: [
          { required: true, message: this.key('enter_code'), trigger: 'blur' },
          { min: 1, max: 45, message: this.key('length_1_45'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('enter_name'), trigger: 'blur' },
          { min: 1, max: 45, message: this.key('length_1_45'), trigger: 'blur' }
        ],
        interface_code: [{ required: true, message: this.key('select_interface'), trigger: 'change' }],
        interface_position: [{ required: true, message: this.key('select_interface_position'), trigger: 'change' }]
      }
    }
  },
  watch: {
    visible (val) {
      if (val) this.fetchData()
    },
    flowProcessId (val) {
      if (val && this.visible) this.fetchData()
    }
  },
  methods: {
    handleClose () {
      this.$emit('close')
    },
    async fetchData () {
      if (!this.flowProcessId) return
      this.loading = true
      try {
        const res = await getCalculationScriptAll({ process_id: this.flowProcessId })
        this.tableData = (res && res.data) || res || []
      } finally {
        this.loading = false
      }
    },
    resetForm () {
      this.formData = { code: '', name: '', interface_code: '', interface_position: '', status: '1', remark: '' }
      this.scriptContent = ''
      this.editId = ''
      this.$nextTick(() => this.$refs.form && this.$refs.form.clearValidate())
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_calculation_script')
      this.resetForm()
      this.formVisible = true
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_calculation_script')
      this.editId = row.id
      this.formData = {
        code: row.code || '',
        name: row.name || '',
        interface_code: row.interface_code || '',
        interface_position: row.interface_position || '',
        status: row.status !== undefined ? String(row.status) : '1',
        remark: row.remark || ''
      }
      this.scriptContent = row.calculation_script_content || ''
      this.formVisible = true
    },
    submitForm () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (!this.scriptContent) {
          this.$message.error(this.$t(this.key('script_content_required')))
          return
        }
        this.submitting = true
        try {
          const payload = {
            ...this.formData,
            process_id: this.flowProcessId,
            calculation_script_content: this.scriptContent
          }
          if (this.handleType === 'create') {
            await createCalculationScript(payload)
          } else {
            await editCalculationScript({ ...payload, id: this.editId })
          }
          this.$message.success(this.$t(this.key('operation_success')))
          this.formVisible = false
          this.fetchData()
        } finally {
          this.submitting = false
        }
      })
    },
    async handleDelete (row) {
      await this.$confirm(this.$t(this.key('confirm_delete_script')), this.$t(this.key('tip')), {
        confirmButtonText: this.$t(this.key('confirm')),
        cancelButtonText: this.$t(this.key('cancel')),
        type: 'warning',
        closeOnClickModal: false
      })
      await deleteCalculationScript({ id: row.id })
      this.$message.success(this.$t(this.key('operation_success')))
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.toolbar {
  margin-bottom: 10px;
}
.status-on {
  color: #67C23A;
}
.status-off {
  color: #F56C6C;
}
.script-editor-title {
  margin-bottom: 8px;
  color: #606266;
}
.script-editor /deep/ textarea {
  font-family: Menlo, Consolas, monospace;
}
</style>
