<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="1000px" append-to-body :close-on-click-modal="false" @close="handleClose">
    <el-row :gutter="10" class="mb8" v-if="procurementStatus === 'approved'">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增报价</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="quoteList" border>
      <el-table-column label="供应商" align="center" prop="supplierName" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="总价" align="center" prop="totalPrice" width="120">
        <template slot-scope="scope">
          <span>¥{{ scope.row.totalPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计交货时间" align="center" prop="eta" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.eta">{{ scope.row.eta }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="报价说明" align="center" prop="note" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="是否中标" align="center" prop="isAwarded" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isAwarded === 1" type="success">已中标</el-tag>
          <el-tag v-else type="info">未中标</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right" v-if="procurementStatus === 'approved'">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAward(scope.row)"
            v-if="scope.row.isAwarded !== 1"
          >设为中标</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </div>

    <!-- 报价编辑对话框 -->
    <el-dialog :title="quoteTitle" :visible.sync="quoteOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="quoteForm" :model="quoteForm" :rules="quoteRules" label-width="120px">
        <el-form-item label="供应商" prop="supplierId">
          <el-select
            v-model="quoteForm.supplierId"
            placeholder="请选择供应商"
            filterable
            style="width: 100%"
            :disabled="quoteForm.id != undefined"
          >
            <el-option
              v-for="supplier in supplierList"
              :key="supplier.id"
              :label="supplier.supplierName"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="总价" prop="totalPrice">
          <el-input-number
            v-model="quoteForm.totalPrice"
            :min="0"
            :precision="2"
            placeholder="请输入总价"
            style="width: 100%"
          >
            <template slot="prepend">¥</template>
          </el-input-number>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">单位：人民币（元）</div>
        </el-form-item>
        <el-form-item label="预计交货时间" prop="eta">
          <el-date-picker
            v-model="quoteForm.eta"
            type="date"
            placeholder="请选择预计交货时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="报价说明" prop="note">
          <el-input v-model="quoteForm.note" type="textarea" placeholder="请输入报价说明" maxlength="500" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitQuoteForm">确 定</el-button>
        <el-button @click="quoteOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { listProcurementQuote, submitQuote } from '@/api/resource/procurement'
import { listSupplier } from '@/api/resource/supplier'
import { awardProcurement } from '@/api/resource/procurement'

export default {
  name: 'ProcurementQuoteDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    procurementId: {
      type: Number,
      default: null
    },
    procurementTitle: {
      type: String,
      default: ''
    },
    procurementStatus: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      loading: false,
      quoteList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      quoteOpen: false,
      quoteTitle: '',
      quoteForm: {},
      supplierList: [],
      quoteRules: {
        supplierId: [{ required: true, message: '供应商不能为空', trigger: 'change' }],
        totalPrice: [{ required: true, message: '总价不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    title() {
      return `报价管理 - ${this.procurementTitle}`
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.procurementId) {
        this.getList()
        if (this.procurementStatus === 'approved') {
          this.getSupplierList()
        }
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    /** 查询报价列表 */
    getList() {
      this.loading = true
      listProcurementQuote(this.procurementId, this.queryParams).then(response => {
        this.quoteList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 查询供应商列表 */
    getSupplierList() {
      listSupplier({ status: 'active' }).then(response => {
        this.supplierList = response.rows || []
      })
    },
    /** 新增报价 */
    handleAdd() {
      this.resetQuoteForm()
      this.quoteOpen = true
      this.quoteTitle = '新增报价'
    },
    /** 设为中标 */
    handleAward(row) {
      this.$modal.confirm('确认将该供应商设为中标？').then(() => {
        return awardProcurement(this.procurementId, row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('设置成功')
        this.$emit('success')
      }).catch(() => {})
    },
    /** 提交报价表单 */
    submitQuoteForm() {
      this.$refs['quoteForm'].validate(valid => {
        if (valid) {
          // 确保包含 procurementId，满足后端验证要求
          const formData = {
            ...this.quoteForm,
            procurementId: this.procurementId
          }
          submitQuote(this.procurementId, formData).then(response => {
            this.$modal.msgSuccess('提交成功')
            this.quoteOpen = false
            this.getList()
            this.$emit('success')
          })
        }
      })
    },
    /** 重置报价表单 */
    resetQuoteForm() {
      this.quoteForm = {
        id: undefined,
        supplierId: undefined,
        totalPrice: undefined,
        eta: undefined,
        note: undefined
      }
      this.resetForm('quoteForm')
    },
    /** 关闭对话框 */
    handleClose() {
      this.quoteList = []
      this.total = 0
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
    }
  }
}
</script>