<template>
  <div class="resource-out-manage-container">
    <el-card class="box-card">
      <div slot="header" class="flex justify-between">
        <span>{{ $t('resourceOutManage.orderId') }}：{{ resourceOutManageInfo.applyOrderId }}</span>
      </div>
      <el-row>
        <el-col :span="24">
          <el-table :data="resourceOutManageInfo.purchaseApplyDetailVo" border style="width: 100%" v-loading="loading">
            <el-table-column prop="rstName" :label="$t('resourceOutManage.itemType')" align="center" width="180">
              <template slot-scope="scope">
                {{ scope.row.rstName || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="resName" :label="$t('resourceOutManage.itemName')" align="center" width="180" />
            <el-table-column prop="specName" :label="$t('resourceOutManage.itemSpec')" align="center" width="180">
              <template slot-scope="scope">
                {{ scope.row.specName || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="resCode" :label="$t('resourceOutManage.itemCode')" align="center" width="180" />
            <el-table-column prop="stock" :label="$t('resourceOutManage.itemStock')" align="center" width="120" />
            <el-table-column prop="quantity" :label="$t('resourceOutManage.applyQuantity')" align="center"
              width="120" />
            <el-table-column :label="$t('resourceOutManage.issueQuantity')" align="center" width="200">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.purchaseQuantity" type="number"
                  :placeholder="$t('resourceOutManage.issueQuantityPlaceholder')" clearable />
              </template>
            </el-table-column>
            <el-table-column :label="$t('resourceOutManage.remark')" align="center" width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.purchaseRemark" type="text"
                  :placeholder="$t('resourceOutManage.remarkPlaceholder')" clearable />
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <el-row class="footer-row">
        <el-col :span="24" class="text-right">
          <el-button type="primary" @click="handleSubmit">
            {{ $t('resourceOutManage.submit') }}
          </el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { listPurchaseApplys, submitResourceOut } from '@/api/resource/resourceOutManageApi'

export default {
  name: 'ResourceOutManageList',
  data() {
    return {
      loading: false,
      resourceOutManageInfo: {
        purchaseApplyDetailVo: [],
        applyOrderId: '',
        taskId: '',
        resOrderType: ''
      }
    }
  },
  created() {
    this.resourceOutManageInfo.applyOrderId = this.$route.query.applyOrderId
    this.resourceOutManageInfo.resOrderType = this.$route.query.resOrderType
    this.resourceOutManageInfo.taskId = this.$route.query.taskId
    this.getList()
  },
  methods: {
    async getList() {
      try {
        this.loading = true
        const params = {
          page: 1,
          row: 10,
          applyOrderId: this.resourceOutManageInfo.applyOrderId,
          resOrderType: this.resourceOutManageInfo.resOrderType
        }
        const { data } = await listPurchaseApplys(params)
        const purchaseApply = data.purchaseApplys[0]
        this.resourceOutManageInfo = {
          ...this.resourceOutManageInfo,
          ...purchaseApply
        }
        this.resourceOutManageInfo.purchaseApplyDetailVo.forEach(item => {
          item.purchaseQuantity = ''
          item.price = ''
          item.purchaseRemark = ''
        })
      } catch (error) {
        console.error('Failed to fetch purchase apply list:', error)
        this.$message.error(this.$t('resourceOutManage.fetchError'))
      } finally {
        this.loading = false
      }
    },
    async handleSubmit() {
      try {
        // Validate form
        let isValid = true
        this.resourceOutManageInfo.purchaseApplyDetailVo.forEach(item => {
          if (!item.purchaseQuantity || parseFloat(item.purchaseQuantity) <= 0) {
            this.$message.error(this.$t('resourceOutManage.quantityRequired'))
            isValid = false
            return
          }
          item.purchaseQuantity = parseFloat(item.purchaseQuantity)
          if (item.purchaseQuantity > parseFloat(item.stock)) {
            this.$message.error(this.$t('resourceOutManage.insufficientStock'))
            isValid = false
            return
          }
        })

        if (!isValid) return

        const response = await submitResourceOut(this.resourceOutManageInfo)
        if (response.code === 0) {
          this.$message.success(this.$t('resourceOutManage.submitSuccess'))
          this.$router.go(-1)
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        console.error('Failed to submit resource out:', error)
        this.$message.error(this.$t('resourceOutManage.submitError'))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.resource-out-manage-container {
  padding: 20px;

  .box-card {
    margin-bottom: 20px;
  }

  .footer-row {
    margin-top: 20px;
  }

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