<template>
  <div class="customer-css">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" class="pi-search-form">
      <el-form-item :label="'报价单号'">
        <el-input v-model="searchData.orderNo" placeholder="报价单号" style="width:160px" @keyup.enter.native="getList" />
      </el-form-item>
      <el-form-item :label="'物料编码'">
        <el-input v-model="searchData.partNo" placeholder="物料编码" style="width:160px" @keyup.enter.native="getList" />
      </el-form-item>
      <el-form-item :label="'物料名称'">
        <el-input v-model="searchData.partDesc" placeholder="物料名称" style="width:200px" @keyup.enter.native="getList" />
      </el-form-item>
      <el-form-item :label="'报价日期'">
            <el-date-picker
              style="width: 130px"
              v-model="searchData.startDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="Start">
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="'To'">
            <el-date-picker
              style="width: 130px"
              v-model="searchData.endDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="End">
            </el-date-picker>
          </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" class="customer-bun-min" @click="getList">查询</el-button>
        <!-- <el-button type="primary" class="customer-bun-min" @click="openDialog()">新增报价</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table :data="dataList" :height="height" border highlight-current-row v-loading="loading" style="width:100%" stripe>
      <el-table-column fixed="right" :label="'操作'" header-align="center" align="center" width="140">
        <template slot-scope="scope">
          <a class="customer-a" @click="openDialog(scope.row)">编辑 |</a>
          <a class="customer-a" @click="handleDelete(scope.row)">删除</a>
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="'状态'" min-width="100" header-align="center" align="center">
        <template slot-scope="scope">
          {{ getStatusLabel(scope.row.status) }}
          <!-- <el-tag :type="getStatusType(scope.row.status)" size="small">{{ getStatusLabel(scope.row.status) }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column prop="orderNo" :label="'报价单号'" min-width="150" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="itemNo" :label="'序号'" min-width="80" header-align="center" align="center" />
      <el-table-column prop="seqNo" :label="'报价次数'" min-width="100" header-align="center" align="center" />
      <el-table-column prop="createdDate" :label="'报价时间'" min-width="160" header-align="center" align="center" />
      <el-table-column prop="supplierId" :label="'供应商编码'" min-width="120" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="supplierName" :label="'供应商名称'" min-width="150" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="partNo" :label="'物料编码'" min-width="140" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="partDesc" :label="'物料名称'" min-width="180" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="qty" :label="'数量'" min-width="100" header-align="center" align="right" />
      <el-table-column prop="umid" :label="'计量单位'" min-width="100" header-align="center" align="center" />
      <el-table-column prop="remark2" :label="'特殊要求'" min-width="150" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="materialCost" :label="'材料费用'" min-width="120" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.materialCost) }}
        </template>
      </el-table-column>
      <el-table-column prop="produceFee" :label="'加工费'" min-width="100" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.produceFee) }}
        </template>
      </el-table-column>
      <el-table-column prop="surfaceFee" :label="'表面处理费'" min-width="120" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.surfaceFee) }}
        </template>
      </el-table-column>
      <el-table-column prop="profit" :label="'利润'" min-width="100" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.profit) }}
        </template>
      </el-table-column>
      <el-table-column prop="price" :label="'未税单价'" min-width="120" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.price) }}
        </template>
      </el-table-column>
      <el-table-column prop="taxRate" :label="'税率(%)'" min-width="100" header-align="center" align="center" />
      <el-table-column prop="tax" :label="'含税单价'" min-width="120" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.tax) }}
        </template>
      </el-table-column>
      <el-table-column prop="duty" :label="'关税'" min-width="100" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.duty) }}
        </template>
      </el-table-column>
      <el-table-column prop="purchaseCycle" :label="'采购周期(天)'" min-width="120" header-align="center" align="center" />
      <el-table-column prop="mouldFee" :label="'模具费'" min-width="100" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.mouldFee) }}
        </template>
      </el-table-column>
      <el-table-column prop="additionalCost" :label="'附加费用'" min-width="100" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.additionalCost) }}
        </template>
      </el-table-column>
      <el-table-column prop="freight" :label="'运费'" min-width="100" header-align="center" align="right">
        <template slot-scope="scope">
          {{ formatMoney(scope.row.freight) }}
        </template>
      </el-table-column>
      <el-table-column prop="reason" :label="'原因'" min-width="150" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="remark" :label="'备注'" min-width="150" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="createdBy" :label="'报价人'" min-width="120" header-align="center" align="center" />
      <el-table-column prop="wantReplyDate" :label="'要求报价时间'" min-width="160" header-align="center" align="center" />
      <el-table-column prop="buyer" :label="'采购员'" min-width="120" header-align="center" align="center" />
      <el-table-column prop="paymentTerm" :label="'付款方式'" min-width="120" header-align="center" align="center" />
      <el-table-column prop="deliveryTerm" :label="'交货条款'" min-width="120" header-align="center" align="center" />
      <el-table-column prop="currency" :label="'货币'" min-width="80" header-align="center" align="center" />
      <el-table-column prop="contact" :label="'联系人'" min-width="120" header-align="center" align="center" />
      <el-table-column prop="phoneNo" :label="'联系电话'" min-width="130" header-align="center" align="center" />
      <el-table-column prop="faxNo" :label="'传真'" min-width="130" header-align="center" align="center" />
      <el-table-column prop="otherCondition" :label="'其他要求'" min-width="180" header-align="center" align="left" show-overflow-tooltip />
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top:10px"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20,50,100,200,500]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper" />

    <!-- 新增 / 编辑 弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" :close-on-click-modal="false" v-drag>
      <el-form label-position="top" class="pi-form" :model="form" label-width="120px">
           <!-- 基础信息 -->
          <div class="form-section">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="物料编码" prop="partNo">
                  <el-input v-model="form.partNo" :disabled="true" placeholder="物料编码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="物料名称" prop="partDesc">
                  <el-input v-model="form.partDesc" :disabled="true" placeholder="物料名称"></el-input>
                </el-form-item>
              </el-col>  
            </el-row>
            <el-row :gutter="20">
                <el-col :span="18">
                <el-form-item label="规格型号" prop="spec">
                  <el-input v-model="form.spec" :disabled="true" placeholder="规格型号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="询价数量" prop="qty">
                  <el-input-number v-model="form.qty" :disabled="true" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="18">
                <el-form-item label="其他要求" prop="otherCondition">
                  <el-input v-model="form.otherCondition" type="text" :disabled="true" :rows="1" placeholder="其他要求"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="计量单位" prop="umid">
                  <el-input v-model="form.umid" :disabled="true" placeholder="计量单位"></el-input>
                </el-form-item>
              </el-col>   
            </el-row>        
          </div>

          <!-- 费用信息 -->
          <div class="form-section">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="材料费用" prop="materialCost">
                  <el-input-number v-model="form.materialCost" @change="calculatePrice" :precision="2" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="加工费" prop="produceFee">
                  <el-input-number v-model="form.produceFee" @change="calculatePrice" :precision="2" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="表面处理费" prop="surfaceFee">
                  <el-input-number v-model="form.surfaceFee" @change="calculatePrice" :precision="2" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
                <el-col :span="6">
                <el-form-item label="利润" prop="profit">
                  <el-input-number v-model="form.profit" @change="calculatePrice" :precision="2" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>

             <!-- 价格信息 -->
          <div class="form-section">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="未税单价" prop="price">
                  <el-input-number v-model="form.price"  :disabled="true" :precision="4" :min="0" style="width: 100%" @change="calculateTax"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="税率(%)" prop="taxRate">
                  <el-input-number v-model="form.taxRate" :disabled="true" :precision="2" :min="0" :max="100" style="width: 100%" @change="calculateTax"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="含税单价" prop="tax">
                  <el-input-number v-model="form.tax"  :disabled="true" :precision="4" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
                <el-col :span="6">
                <el-form-item label="关税" prop="duty">
                  <el-input-number v-model="form.duty" :precision="2" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
            <el-row :gutter="20">
               <el-col :span="6">
                <el-form-item label="采购周期(天)" prop="purchaseCycle">
                  <el-input-number v-model="form.purchaseCycle" :min="0" :precision="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="模具费" prop="mouldFee">
                  <el-input-number v-model="form.mouldFee" :precision="2" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="附加费用" prop="additionalCost">
                  <el-input-number v-model="form.additionalCost" :precision="2" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
               <el-col :span="6">
                <el-form-item label="运费" prop="freight">
                  <el-input-number v-model="form.freight" :precision="2" :min="0" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>           
            </el-row>
          </div>

          <!-- 其他信息 -->
          <div class="form-section">
             <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="特殊要求" prop="remark2">
                  <el-input v-model="form.remark2" type="textarea" :disabled="true" :rows="1" placeholder="请输入特殊要求"></el-input>
                </el-form-item>
              </el-col>
             </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" :rows="1" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
            </el-row>
          </div>
      
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
        <el-button @click="dialogVisible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
    searchPurReplyHistPage,
    createPurReplyHist, 
    updatePurReplyHist, 
    deletePurReplyHist } from '@/api/supplier/purReplyHist.js'

export default {
  name: 'MyQuotation',
  data() {
    return {
      height: 200,
      loading: false,
      submitLoading: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      searchData: {
        site: this.$store.state.user.site,
        createdBy: this.$store.state.user.name,
        orderNo: '',
        partNo: '',
        partDesc: '',
        status: ''
      },
      dialogVisible: false,
      dialogTitle: '新增报价',
      editMode: false,
      form: {
        id: '',
        status: 'pending',
        orderNo: '',
        itemNo: '',
        seqNo: '',
        createdDate: '',
        supplierId: '',
        supplierName: '',
        partNo: '',
        partDesc: '',
        qty: 0,
        umid: '',
        remark2: '',
        materialCost: 0,
        produceFee: 0,
        surfaceFee: 0,
        profit: 0,
        price: 0,
        taxRate: 13,
        tax: 0,
        duty: 0,
        purchaseCycle: 0,
        mouldFee: 0,
        additionalCost: 0,
        freight: 0,
        reason: '',
        remark: '',
        createdBy: this.$store.state.user.name,
        wantReplyDate: '',
        employeeName: '',
        paymentTerm: '',
        deliveryTerm: '',
        currency: 'CNY',
        contact: '',
        phoneNo: '',
        faxNo: '',
        otherCondition: ''
      }
    }
  },
  mounted() {
    this.calcHeight()
    window.addEventListener('resize', this.calcHeight)
    this.getList()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calcHeight)
  },
  methods: {
    calcHeight() {
      this.$nextTick(() => {
        this.height = window.innerHeight - 212
      })
    },
    getStatusType(status) {
      const map = {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger'
      }
      return map[status] || 'info'
    },
    getStatusLabel(status) {
      const map = {
        pending: '待审核',
        approved: '已通过',
        rejected: '已拒绝'
      }
      return map[status] || status
    },
    formatMoney(value) {
      if (value === null || value === undefined) return '-'
      return new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value)
    },
    getList() {
      this.loading = true
      const params = {
        limit: this.pageSize,
        page: this.pageIndex,
        ...this.searchData
      }
      searchPurReplyHistPage(params).then(({ data }) => {
        if (data.code === 0) {
          this.dataList = data.page.list
          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount
        } else {
          this.$message.error((data && data.msg) || '获取列表失败')
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('请求失败')
      })
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getList()
    },
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getList()
    },
    openDialog(row) {
      if (row) {
        this.dialogTitle = '编辑报价'
        this.editMode = true
        this.form = { ...row }
      } else {
        this.dialogTitle = '新增报价'
        this.editMode = false
        this.form = {
          id: '',
          status: '已报价',
          orderNo: '',
          itemNo: '',
          seqNo: '',
          createdDate: new Date().toISOString(),
          supplierId: '',
          supplierName: '',
          partNo: '',
          partDesc: '',
          qty: 0,
          umid: '',
          remark2: '',
          materialCost: 0,
          produceFee: 0,
          surfaceFee: 0,
          profit: 0,
          price: 0,
          taxRate: 13,
          tax: 0,
          duty: 0,
          purchaseCycle: 0,
          mouldFee: 0,
          additionalCost: 0,
          freight: 0,
          reason: '',
          remark: '',
          createdBy: this.$store.state.user.name,
          wantReplyDate: '',
          employeeName: '',
          paymentTerm: '',
          deliveryTerm: '',
          currency: 'CNY',
          contact: '',
          phoneNo: '',
          faxNo: '',
          otherCondition: ''
        }
      }
        // 计算含税单价: 
      this.calculatePrice()
      // this.calculateTax()
      this.quoteDialogVisible = true
      this.dialogVisible = true
    },
      calculatePrice(){
      //未税单价=材料成本+加工费+表面费用+利润
      this.form.price = this.form.materialCost + this.form.produceFee + 
                          this.form.surfaceFee + this.form.profit
       this.calculateTax()

    },
   // 计算含税单价
    calculateTax() {
      //含税单价=未税单价*(1+税率)
      if (this.form.price && this.form.taxRate) {
        this.form.tax = this.form.price * (1 + this.form.taxRate / 100)
      }
    },
    validateForm() {
      if (!this.form.partNo) {
        this.$message.warning('物料编码不能为空')
        return false
      }
      if (!this.form.partDesc) {
        this.$message.warning('物料名称不能为空')
        return false
      }
      return true
    },
    submitForm() {
      if (!this.validateForm()) return
      this.submitLoading = true
      const api = this.editMode ? updatePurReplyHist : createPurReplyHist
      api(this.form).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success('保存成功')
          this.dialogVisible = false
          this.getList()
        } else {
          this.$message.error((data && data.msg) || '保存失败')
        }
      }).catch(err => {
        this.$message.error('请求失败: ' + err.message)
      }).finally(() => {
        this.submitLoading = false
      })
    },
    handleDelete(row) {
      this.$confirm(`确定删除报价单: ${row.orderNo} ?`, '提示', { type: 'warning' }).then(() => {
        deletePurReplyHist({ id: row.id }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error((data && data.msg) || '删除失败')
          }
        }).catch(err => {
          this.$message.error('删除失败: ' + err.message)
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.pi-search-form { margin-top: 0; }
.pi-form { margin-top: -5px; }
.customer-a {
  cursor: pointer;
  color: #409EFF;
  margin: 0 4px;
}
.customer-a:hover {
  color: #66b1ff;
}
.customer-bun-min {
  margin-right: 10px;
}
</style>