<template>
  <el-dialog
    title="状态流转"
    :visible.sync="dialogVisible"
    width="500px"
    append-to-body :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="当前状态">
        <dict-tag :options="statusOptions" :value="equipment ? equipment.status : ''" />
      </el-form-item>
      <el-form-item v-if="!preselectedAction" label="目标操作" prop="action">
        <el-radio-group v-model="form.action">
          <el-radio
            v-for="action in availableActions"
            :key="action.value"
            :label="action.value"
          >{{ action.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-else label="目标操作">
        <span style="font-weight: bold;">{{ getActionLabel(preselectedAction) }}</span>
      </el-form-item>
      <el-form-item
        :label="getRemarkLabel()"
        :prop="getRemarkProp()"
      >
        <el-input
          v-model="form.remark"
          type="textarea"
          :placeholder="getRemarkPlaceholder()"
          :rows="3"
          maxlength="500"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  releaseEquipment,
  sendRepair,
  finishRepair,
  scrapEquipment
} from '@/api/resource/equipment'

export default {
  name: 'EquipmentStatusDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    equipment: {
      type: Object,
      default: () => ({})
    }
  },
  dicts: ['equipment_status'],
  data() {
    return {
      form: {
        action: '',
        remark: ''
      },
      rules: {
        action: [
          { required: true, message: '请选择目标操作', trigger: 'change' }
        ],
        remark: []
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    statusOptions() {
      return this.dict.type.equipment_status || []
    },
    preselectedAction() {
      // 如果从下拉菜单传入了 action，使用它
      return this.equipment?.action || null
    },
    availableActions() {
      if (!this.equipment) {
        return []
      }
      const status = this.equipment?.status || '';
      const actions = []
      
      if (status === 'available') {
        actions.push(
          { label: '送修', value: 'send-repair' },
          { label: '报废', value: 'scrap' }
        )
      } else if (status === 'busy') {
        actions.push(
          { label: '解除占用', value: 'release' },
          { label: '送修', value: 'send-repair' },
          { label: '报废', value: 'scrap' }
        )
      } else if (status === 'repair') {
        actions.push(
          { label: '修复完成', value: 'finish-repair' },
          { label: '报废', value: 'scrap' }
        )
      }
      // scrap 状态没有可用操作
      
      return actions
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initForm()
      }
    },
    'form.action'(val) {
      // 根据操作类型更新备注校验规则
      if (val === 'send-repair' || val === 'scrap') {
        this.rules.remark = [
          { required: true, message: this.getRemarkLabel() + '不能为空', trigger: 'blur' },
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      } else {
        this.rules.remark = [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    initForm() {
      // 如果从下拉菜单传入了 action，使用它；否则使用第一个可用操作
      const action = this.preselectedAction || (this.availableActions.length > 0 ? this.availableActions[0].value : '')
      this.form = {
        action: action,
        remark: ''
      }
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    getActionLabel(action) {
      const actionMap = {
        'assign': '分配占用',
        'release': '解除占用',
        'send_repair': '送修',
        'send-repair': '送修',
        'finish_repair': '修复完成',
        'finish-repair': '修复完成',
        'scrap': '报废'
      }
      return actionMap[action] || action || '-'
    },
    getRemarkLabel() {
      const action = this.form.action
      if (action === 'send-repair') {
        return '送修原因'
      } else if (action === 'scrap') {
        return '报废原因'
      } else if (action === 'finish-repair') {
        return '修复情况'
      }
      return '备注'
    },
    getRemarkProp() {
      const action = this.form.action
      if (action === 'send-repair' || action === 'scrap') {
        return 'remark'
      }
      return ''
    },
    getRemarkPlaceholder() {
      const action = this.form.action
      if (action === 'send-repair') {
        return '请输入送修原因'
      } else if (action === 'scrap') {
        return '请输入报废原因（报废为终态，不可回退）'
      } else if (action === 'finish-repair') {
        return '请输入修复情况（可选）'
      }
      return '请输入备注（可选）'
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        
        if (!this.equipment || !this.equipment.id) {
          this.$modal.msgError('装备信息不存在')
          return
        }
        
        const action = this.form.action
        const equipmentId = this.equipment.id
        
        // 确认操作
        let confirmMessage = ''
        if (action === 'scrap') {
          confirmMessage = '报废为终态，不可回退，是否确认报废？'
        } else if (action === 'send-repair') {
          confirmMessage = '送修后装备状态将变为维修，是否继续？'
        }
        
        if (confirmMessage) {
          this.$modal.confirm(confirmMessage).then(() => {
            this.executeAction(action, equipmentId)
          }).catch(() => {})
        } else {
          this.executeAction(action, equipmentId)
        }
      })
    },
    executeAction(action, equipmentId) {
      const data = {
        remark: this.form.remark || undefined
      }
      
      if (action === 'release') {
        releaseEquipment(equipmentId, data).then(() => {
          this.$modal.msgSuccess('解除占用成功')
          this.handleSuccess()
        })
      } else if (action === 'send-repair') {
        sendRepair(equipmentId, data).then(() => {
          this.$modal.msgSuccess('送修成功')
          this.handleSuccess()
        })
      } else if (action === 'finish-repair') {
        finishRepair(equipmentId, data).then(() => {
          this.$modal.msgSuccess('修复完成')
          this.handleSuccess()
        })
      } else if (action === 'scrap') {
        scrapEquipment(equipmentId, data).then(() => {
          this.$modal.msgSuccess('报废成功')
          this.handleSuccess()
        })
      }
    },
    handleSuccess() {
      this.handleClose()
      this.$emit('success')
    },
    handleClose() {
      this.dialogVisible = false
      this.$nextTick(() => {
        this.initForm()
      })
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>

