<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" append-to-body :close-on-click-modal="false" @close="handleClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item v-if="action === 'approve' || action === 'reject'" label="审核意见" prop="comment">
        <el-input
          v-model="form.comment"
          type="textarea"
          placeholder="请输入审核意见"
          maxlength="500"
          :rows="4"
        />
      </el-form-item>
      <el-form-item v-if="action === 'award'" label="选择报价" prop="quoteId">
        <el-select v-model="form.quoteId" placeholder="请选择报价" style="width: 100%">
          <el-option
            v-for="quote in quoteList"
            :key="quote.id"
            :label="`${quote.supplierName} - ¥${quote.totalPrice}`"
            :value="quote.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="action === 'receive'" label="仓库" prop="warehouseId">
        <el-select v-model="form.warehouseId" placeholder="请选择仓库（物资入库时必选，装备入库时可选）" style="width: 100%">
          <el-option
            v-for="warehouse in warehouseList"
            :key="warehouse.id"
            :label="warehouse.warehouseName"
            :value="warehouse.id"
          />
        </el-select>
        <div style="color: #909399; font-size: 12px; margin-top: 5px;">
          提示：如果采购明细中包含物资，仓库为必选项；如果只有装备，仓库可选
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { approveProcurement, rejectProcurement, awardProcurement, receiveProcurement } from '@/api/resource/procurement'
import { listProcurementQuote } from '@/api/resource/procurement'
import { listWarehouse } from '@/api/resource/warehouse'

export default {
  name: 'ProcurementStatusDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    procurement: {
      type: Object,
      default: null
    },
    action: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      form: {},
      quoteList: [],
      warehouseList: [],
      rules: {
        comment: [
          { required: true, message: '审核意见不能为空', trigger: 'blur' },
          { max: 500, message: '审核意见长度不能超过500个字符', trigger: 'blur' }
        ],
        quoteId: [{ required: true, message: '请选择报价', trigger: 'change' }]
        // warehouseId 验证由后端处理：如果有物资明细，仓库必选；如果只有装备，仓库可选
      }
    }
  },
  computed: {
    dialogTitle() {
      const titles = {
        approve: '审核通过',
        reject: '审核驳回',
        award: '确认中标',
        receive: '采购入库'
      }
      return titles[this.action] || '状态流转'
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.initForm()
        if (this.action === 'award') {
          this.getQuoteList()
        }
        if (this.action === 'receive') {
          this.getWarehouseList()
        }
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    /** 初始化表单 */
    initForm() {
      this.form = {
        comment: undefined,
        quoteId: undefined,
        warehouseId: undefined
      }
      this.resetForm('form')
    },
    /** 查询报价列表 */
    getQuoteList() {
      if (!this.procurement || !this.procurement.id) {
        return
      }
      listProcurementQuote(this.procurement.id, {}).then(response => {
        this.quoteList = response.rows || []
      })
    },
    /** 查询仓库列表 */
    getWarehouseList() {
      listWarehouse({ status: '0' }).then(response => {
        this.warehouseList = response.rows || []
      })
    },
    /** 提交表单 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const procurementId = this.procurement.id
          if (this.action === 'approve') {
            approveProcurement(procurementId, this.form.comment).then(response => {
              this.$modal.msgSuccess('审核通过成功')
              this.dialogVisible = false
              this.$emit('success')
            })
          } else if (this.action === 'reject') {
            rejectProcurement(procurementId, this.form.comment).then(response => {
              this.$modal.msgSuccess('审核驳回成功')
              this.dialogVisible = false
              this.$emit('success')
            })
          } else if (this.action === 'award') {
            awardProcurement(procurementId, this.form.quoteId).then(response => {
              this.$modal.msgSuccess('确认中标成功')
              this.dialogVisible = false
              this.$emit('success')
            })
          } else if (this.action === 'receive') {
            receiveProcurement(procurementId, this.form.warehouseId).then(response => {
              this.$modal.msgSuccess('入库成功')
              this.dialogVisible = false
              this.$emit('success')
            })
          }
        }
      })
    },
    /** 关闭对话框 */
    handleClose() {
      this.form = {}
      this.quoteList = []
      this.warehouseList = []
    }
  }
}
</script>