<!-- 询价单新增 -->
<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" clearable />
      </el-form-item>
      <el-form-item :label="'供应商编码'">
        <el-input v-model="searchData.supplierId" placeholder="供应商编码" style="width:160px" @keyup.enter.native="getList" clearable />
      </el-form-item>
      <el-form-item :label="'供应商名称'">
        <el-input v-model="searchData.supplierName" placeholder="供应商名称" style="width:200px" @keyup.enter.native="getList" clearable />
      </el-form-item>
      <el-form-item :label="'状态'">
        <el-select v-model="searchData.status" placeholder="请选择" style="width:100px" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="待提交" value="待提交"></el-option>
              <el-option label="待报价" value="待报价"></el-option>
              <el-option label="已报价" value="已报价"></el-option>
              <el-option label="已关闭" value="已关闭"></el-option>
        </el-select>
      </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="tableHeight" border highlight-current-row @row-click="selectInquiry" v-loading="loading" style="width:100%">
      <el-table-column fixed="right" label="操作" header-align="center" align="center" width="140">
        <template slot-scope="scope" >
          <a class="customer-a"  v-if="scope.row.status === '待提交'" @click.stop="openDialog(scope.row)">编辑 |</a>
          <a class="customer-a"  v-if="scope.row.status === '待提交'" @click.stop="handleDelete(scope.row)">删除</a>
          <a class="customer-a"  v-if="scope.row.status === '待提交'" @click="updateQuoDetail(scope.row)">提交</a>
           <a class="customer-a"  v-if="scope.row.status != '已关闭'" @click="closePurHeader(scope.row)">关闭</a>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="80" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="orderNo" label="询价单号" min-width="140" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="supplierId" label="供应商编码" min-width="120" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="supplierName" label="供应商名称" min-width="180" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="orderDate" label="询价日期" min-width="120" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="wantReplyDate" label="要求报价日期" min-width="120" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="userName" label="录入人" min-width="100" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="buyer" label="采购员" min-width="100" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="paymentTermDesc" label="付款方式" min-width="120" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="deliveryTermDesc" label="交易条款" min-width="120" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="currencyDesc" label="货币" min-width="80" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="currencyRate" label="货币汇率" min-width="100" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="taxRate" label="税率" min-width="80" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="otherCondition" label="其他要求" min-width="180" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="phoneNo" label="电话号码" min-width="120" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="faxNo" label="传真" min-width="120" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="contact" label="联系人" min-width="100" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="remark" label="备注" min-width="180" header-align="center" align="left" show-overflow-tooltip />
     
    </el-table>

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

    <!-- 子表：物料明细列表 - 始终显示表头 -->
    <div class="sub-title">
      物料明细列表 
       <el-button type="primary" class="customer-bun-min" @click="openMaterialDialog()" style="margin-left: 10px;">新增物料</el-button>
    </div>
     
    <el-table 
      :data="materialList" 
      :height="subTableHeight" 
      border 
      v-loading="materialLoading" 
      style="width:100%">
      <el-table-column fixed="right" label="操作" header-align="center" align="center" width="120">
        <template slot-scope="scope">
          <a class="material-action-btn" @click="openMaterialDialog(scope.row)">编辑</a>
          <a class="material-action-btn" @click="deleteMaterial(scope.row)">删除</a>
          <a class="material-action-btn" @click="openUploadDialog(scope.row)">附件</a>
        </template>
      </el-table-column>
      <el-table-column prop="partNo" label="物料编码" min-width="130" header-align="center" align="center" show-overflow-tooltip />
      <el-table-column prop="partDesc" label="物料名称" min-width="150" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="umid" label="计量单位" min-width="80" header-align="center" align="center" />
      <el-table-column prop="spec" label="规格型号" min-width="150" header-align="center" align="left" show-overflow-tooltip />
      <el-table-column prop="qty" label="询价数量" min-width="100" header-align="center" align="right">
        <template slot-scope="scope">{{ scope.row.qty || 0 }}</template>
      </el-table-column>
      <el-table-column prop="remark2" label="特殊要求" min-width="150" header-align="center" align="left" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.remark2 || '-' }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="80" header-align="center" align="center">
        <template slot-scope="scope">{{ scope.row.status }}
          <!-- <span :class="'status-badge ' + (scope.row.status === 'Y' ? 'status-sent' : 'status-closed')">{{ scope.row.status === 'Y' ? '启用' : '停用' }}</span> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 空数据提示 -->
    <div v-if="materialList.length === 0 && !materialLoading" style="margin-top: 8px; color: #909399; font-size: 12px; text-align: center;">
      {{ currentInquiry ? '暂无物料数据' : '请点击左侧询价单查看物料明细' }}
    </div>

    <!-- 新增/编辑 询价单弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" :close-on-click-modal="false" append-to-body>
      <el-form label-position="top" class="pi-form" :model="form" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item>
              <span style="cursor: pointer" slot="label" @click="getBaseList(520)"><a href="javascript:void(0)">供应商编码</a></span>
              <el-input v-model="form.supplierId"  @change="handleSupplierIdChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" :required="true">
              <el-input v-model="form.supplierName"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="询价日期">
              <el-date-picker v-model="form.orderDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="要求报价日期">
              <el-date-picker v-model="form.wantReplyDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货币汇率">
              <el-input-number v-model="form.currencyRate" :precision="4" :step="0.1" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="税率(%)">
              <!-- <el-input-number v-model="form.taxRate" :precision="2" :step="1" style="width:100%" /> -->
               <el-select v-model="form.taxCode" placeholder="请选择" clearable >
                <el-option
                  v-for = "t in taxList"
                  :key = "t.taxCode"
                  :label = "t.taxRate"
                  :value = "t.taxCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="6">
            <el-form-item label="货币">
              <!-- <el-input-number v-model="form.taxRate" :precision="2" :step="1" style="width:100%" /> -->
               <el-select v-model="form.currency" placeholder="请选择"   clearable>
                <el-option
                  v-for = "t in currencyList"
                  :key = "t.currency"
                  :label = "t.currencyDesc"
                  :value = "t.currency">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item>
              <span style="cursor: pointer" slot="label" @click="getBaseList(529)"><a href="javascript:void(0)">采购员</a></span>
              <el-input v-model="form.buyer" style="width: 130px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="付款方式">
              <!-- <el-input v-model="form.paymentTermDesc" /> -->
                 <el-select v-model="form.paymentTerm" placeholder="请选择"   clearable>
                <el-option
                  v-for = "t in paymentList"
                  :key = "t.paymentTermId"
                  :label = "t.paymentTerm"
                  :value = "t.paymentTermId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易条款">
              <!-- <el-input v-model="form.deliveryTermDesc" /> -->
                  <el-select v-model="form.deliveryTerm" placeholder="请选择"   clearable style="width: 100%">
                <el-option
                  v-for = "t in deliveryList"
                  :key = "t.deliveryTermId"
                  :label = "t.deliveryTerm"
                  :value = "t.deliveryTermId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
         
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="电话号码">
              <el-input v-model="form.phoneNo" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="传真">
              <el-input v-model="form.faxNo" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人">
              <el-input v-model="form.contact" />
            </el-form-item>
          </el-col>
      
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="其他要求">
              <el-input v-model="form.otherCondition" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="form.remark" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </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>

    <!-- 物料明细新增/编辑弹窗 -->
    <el-dialog :title="materialDialogTitle" :visible.sync="materialDialogVisible" width="700px" :close-on-click-modal="false" append-to-body>
      <el-form label-position="top" class="pi-form" :model="materialForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item >
               <span style="cursor: pointer" slot="label" @click="getBaseList(507)"><a href="#">物料编码</a></span>
              <el-input v-model="materialForm.partNo" placeholder="请输入物料编码"  @change="handlePartNoChange" :readonly="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" required>
              <el-input v-model="materialForm.partDesc" placeholder="请输入物料名称" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="12">
            <el-form-item label="规格型号">
              <el-input v-model="materialForm.spec" placeholder="规格型号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量单位">
              <!-- <span style="cursor: pointer" slot="label" @click="getBaseList(510)"><a href="#">计量单位</a></span> -->
              <el-input v-model="materialForm.umid" placeholder="计量单位" disabled/>
            </el-form-item>
          </el-col>
        
          <el-col :span="6">
            <el-form-item label="询价数量">
              <el-input-number v-model="materialForm.qty" :min="0" :precision="0" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="特殊要求">
              <el-input type="textarea" v-model="materialForm.remark2" :rows="2" placeholder="特殊要求" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px">
        <el-button type="primary" @click="saveMaterial" :loading="materialSubmitLoading">保存</el-button>
        <el-button @click="materialDialogVisible=false">取消</el-button>
      </div>
    </el-dialog>


     <el-dialog 
    :title="dialogTitle" 
    :visible.sync="uploadDialogVisible" 
    width="800px" 
    :close-on-click-modal="false" 
    append-to-body
    @close="handleClose">
    <div class="customer-css">
      <!-- 上传按钮 -->
      <el-form label-position="top" style="margin-top: -5px;">
        <el-row style="margin-top: 10px">
          <el-col :span="4">
            <el-button class="customer-bun-min" type="primary" @click="handleUpload">Upload</el-button>
          </el-col>
        </el-row>

        <!-- 文件列表表格 -->
        <el-table
          :height="240"
          :data="fileList"
          ref="fileTableRef"
          style="width: 100%; margin-top: 10px;">
          <el-table-column
            prop="fileName"
            header-align="center"
            align="left"
            min-width="200"
            label="File">
          </el-table-column>
          <el-table-column
            prop="createdBy"
            header-align="center"
            align="center"
            min-width="100"
            label="Upload By">
          </el-table-column>
          <el-table-column
            prop="createDate"
            header-align="center"
            align="center"
            min-width="100"
            label="Upload Time">
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            width="100"
            fixed="right"
            label="Actions">
            <template slot-scope="scope">
              <a type="text" size="small" v-if="scope.row.id" @click="handleDownload(scope.row)">View |</a>
              <a type="text" size="small" v-if="scope.row.id" @click="deleteFileReal(scope.row)"> delete</a>
              <a type="text" size="small" v-else @click="deleteFile(scope.$index)"> delete</a>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <!-- File Upload Dialog -->
    <el-dialog 
      title="UpLoad" 
      :visible.sync="ossVisible" 
      v-drag 
      width="400px" 
      append-to-body 
      :close-on-click-modal="false"
      @close="handleUploadClose">
      <el-form ref="form" class="rq" label-width="80px" label-position="top">
        <el-row :gutter="10">
          <slot></slot>
          <el-col :span="24">
            <el-form-item label=" " class="auto">
              <el-upload 
                drag 
                :file-list="fileList2"
                action="#" 
                ref="upload"
                :on-remove="onRemoveFile"
                :on-change="onChangeFile"
                multiple
                :auto-upload="false">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">Drag files here, or<em> click to upload</em></div>
              </el-upload>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="Remark" class="auto">
              <el-input type="textarea" v-model="ossForm.remark" resize="none" :autosize="{minRows: 3, maxRows: 3}"></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="uploadLoading" @click="submitData">Confirm</el-button>
        <el-button @click="ossVisible = false">Close</el-button>
      </span>
    </el-dialog>

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

    <Chooselist ref="baseList" @getBaseData="getBaseData" />
  </div>
</template>

<script>
import Chooselist from '@/views/modules/common/Chooselist_eam'
import {
    searchPurHeaderList,
    createPurHeader,
    updatePurHeader,
    deletePurHeader,
    updatePurHeaderStatus,
    searchMaterialList,
    createMaterial,
    updateMaterial,
    deleteMaterial,
    updatePurDetailStatus
} from '@/api/supplier/purQuotation.js'

import {
    getSupplierInfo
} from '@/api/srm/srmSupplier.js'

import {
  ossUploadNoSaveOSSForYJY,
  queryOssFilePlus,
  removeOss,
  downLoadObjectFile
} from "../../../api/oss/oss";

import {
    searchTaxList
} from "@/api/base/tax.js";

import {
    searchCurrencyList
} from "@/api/base/currency.js";

import {
    searchPaymentList
} from "@/api/base/paymentTerm.js";


import {
    searchDeliveryList
} from "@/api/base/deliveryTerm.js";

// 添加物料信息查询接口
import {
    searchPartInfo
} from '@/api/part/partInfo.js'


export default {
  components: {
    Chooselist
  },
  name: 'InquiryList',
  data() {
    return {
      tableHeight: 200,
      subTableHeight: 200,
      loading: false,
      submitLoading: false,
      materialLoading: false,
      materialSubmitLoading: false,
      taxLoading: false,
      currencyLoading: false,
      pamentLoading: false,
      deliveryLoading: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      searchData: {
        site: this.$store.state.user.site,
        orderNo: '',
        supplierId: '',
        supplierName: '',
        status: ''
      },
      taxList: [],
      taxForm: {
        taxRate: '',
        taxCode: null,
        taxDesc: ''
      },
      currencyList: [],
      currencyForm: {
        currency: '',
        currencyDesc: ''
      },
      paymentList: [],
      paymentForm: {
        paymentTermId: '',
        paymentTerm: ''
      },
      deliveryList: [],
      deliveryForm: {
        deliveryTermId:'',
        deliveryTerm:''
      },
      dialogVisible: false,
      dialogTitle: '新增询价单',
      editMode: false,
      form: { 
        id: '',
        taxRate: '',
        paymentTerm: '',
        paymentTermDesc: '',
        deliveryTerm: '',
        deliveryTermDesc: '',
        currency: '',
        currencyDesc: '',
        orderNo: '',
        supplierId: '',
        supplierName: '',
        orderDate: '',
        wantReplyDate: '',
        userName: '',
        buyer: '',
        currencyRate: 1,
        taxRate: 0,
        taxCode:'',
        otherCondition: '',
        phoneNo: '',
        faxNo: '',
        contact: '',
        remark: '',
        printed : "N",
        status: '待提交'
      },
      // 物料子表相关
      currentInquiry: null,
      materialList: [],
      materialDialogVisible: false,
      materialDialogTitle: '新增物料',
      materialForm: {
        id: null,
        site: this.$store.state.user.site,
        partNo: '',
        partDesc: '',
        umid: '',
        spec: '',
        qty: 0,
        remark2: '',
        status: '待提交'
      },
    searchParams: {
      orderRef1: '',
      orderRef2: '',
      orderRef3: '',
      orderReftype: ''
    },
      fileList: [],
      fileList2: [],
      ossVisible: false,
      ossForm: {
        remark: '',
      },
      uploadLoading: false,
      // staged files selected in upload dialog but not yet persisted
      stagedFiles: [],
      stagedFileRemark: '',
      uploadDialogTitle: '上传附件',
      uploadDialogVisible: false,
      tagNo: null,
      tagNo1: null
    }
  },
  mounted() {
      this.$nextTick(() => {
      this.tableHeight = (window.innerHeight - 250) / 2
      this.subTableHeight = (window.innerHeight - 250) / 2
    })
    // this.calcHeight()
    // window.addEventListener('resize', this.calcHeight)
    this.getList()
    this.getTaxList()
    this.getCurrencyList()
    this.getPamentList()
    this.getDeliveryList()
  },
  beforeDestroy() {
    // window.removeEventListener('resize', this.calcHeight)
  },
  methods: {
    // calcHeight() {
    //   this.$nextTick(() => {
    //     this.tableHeight = window.innerHeight - 360
    //     this.subTableHeight = 220
    //   })
    // },
    getBaseList(val, type) {
      this.tagNo = val
      this.tagNo1 = type
      this.$nextTick(() => {
        let strVal = ''
        if (val === 520) {
          if(type == 1) {
            strVal = this.form.supplierId
          }
        }
        if (val === 529) {
          strVal = this.form.buyer
        }
        if(val === 507) {
          strVal = this.form.part_spec
        }
        if (val === 510) {
          strVal = this.form.unit
        }
        this.$refs.baseList.init(val, strVal?strVal:'')
      })
    },
    getBaseData(val) {
      if (this.tagNo === 520) {
        this.form.supplierId = val.supplier_no
        this.form.supplierName = val.supplier_name
        this.searchSupplierInfo()
      }
      if (this.tagNo === 529) {
        this.form.buyer = val.UserName
      }
      if(this.tagNo === 507) {
        this.materialForm.partNo = val.part_no
        this.materialForm.partDesc = val.part_desc
        this.materialForm.spec = val.part_spec
        this.materialForm.umid = val.unit
        this.getPartInfo()
      }

      if (this.tagNo === 510) {
        this.materialForm.umid = val.UMID
      }
    },
    // 供应商编码变化时触发，自动带出供应商信息
    handleSupplierIdChange(val) {
      if (!val || val.trim() === '') {
        return
      }
      // 调用查询供应商信息接口
      const params = { 
        site: this.$store.state.user.site,
        supplierNo: val.trim()
      }
      this.searchSupplierInfo()
    },
   
    searchSupplierInfo() {
      const params = { 
        site: this.$store.state.user.site,
        supplierNo: this.form.supplierId
      }
      getSupplierInfo(params).then(({data}) => {
        if (data.code === 0) {
          this.form.supplierId = data.row.supplierId || this.form.supplierId
          this.form.supplierName = data.row.supplierName || this.form.supplierName
          this.form.phoneNo = data.row.phoneNo || this.form.phoneNo
          this.form.faxNo = data.row.faxNo || this.form.faxNo
          this.form.contact = data.row.contact || this.form.contact
          this.form.taxRate = data.row.taxRate || this.taxForm.taxRate
          this.form.taxCode = data.row.taxCode || this.taxForm.taxCode
          this.form.paymentTerm = data.row.paymentTerm || this.paymentForm.paymentTermId
          this.form.paymentTermDesc = data.row.paymentTermDesc || this.paymentForm.paymentTerm
          this.form.deliveryTerm = data.row.deliveryTerm || this.deliveryForm.deliveryTermId
          this.form.deliveryTermDesc = data.row.deliveryTermDesc || this.deliveryForm.deliveryTerm
          this.form.currency = data.row.currency || this.currencyForm.currency
        } else {
          this.$message.error((data && data.msg) || '获取列表失败')
        }
      }).catch(() => {
        this.$message.error('请求失败')
      })
    },
    getList() {
      this.loading = true
        const params = {
        ...this.searchData,
        limit: this.pageSize,
        page: this.pageIndex
      }
  
      searchPurHeaderList(params).then(({data}) => {
        if (data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
          // 保留选中状态
          if (this.currentInquiry) {
            const exists = this.dataList.some(item => item.orderNo === this.currentInquiry.orderNo)
            if (exists) {
              this.selectInquiry(this.currentInquiry)
            } else {
              this.materialList = []
              this.currentInquiry = null
            }
          } else if (this.dataList.length > 0 && !this.currentInquiry) {
            this.selectInquiry(this.dataList[0])
          }
        } 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()
    },
    selectInquiry(row) {
      this.currentInquiry = row
      this.loadMaterialList(row.orderNo)
    },
  
    //加载税率列表
    getTaxList() {
      this.taxLoading = true
      searchTaxList({ 
        site: this.$store.state.user.site 
      }).then(({data}) => {
        if (data.code === 0) {
          this.taxList = data.rows || []
        } else {
          this.taxList = []
        }
        this.taxLoading = false
      }).catch(() => {
        this.taxList = []
        this.taxLoading = false
        this.$message.error('获取税率列表失败')
      })
    },
     //加载货币列表
    getCurrencyList() {
      this.currencyLoading = true
      searchCurrencyList({ 
        site: this.$store.state.user.site 
      }).then(({data}) => {
        if (data.code === 0) {
          this.currencyList = data.rows || []
        } else {
          this.currencyList = []
        }
        this.currencyLoading = false
      }).catch(() => {
        this.currencyList = []
        this.currencyLoading = false
        this.$message.error('获取货币列表失败')
      })
    },

     //加载付款方式列表
    getPamentList() {
      this.pamentLoading = true
      searchPaymentList({ 
        site: this.$store.state.user.site 
      }).then(({data}) => {
        if (data.code === 0) {
          this.paymentList = data.rows || []
        } else {
          this.paymentList = []
        }
        this.pamentLoading = false
      }).catch(() => {
        this.paymentList = []
        this.pamentLoading = false
        this.$message.error('获取付款方式列表失败')
      })
    },

      //加载交易条款列表
    getDeliveryList() {
      this.deliveryLoading = true
      searchDeliveryList({ 
        site: this.$store.state.user.site 
      }).then(({data}) => {
        if (data.code === 0) {
          this.deliveryList = data.rows || []
        } else {
          this.deliveryList = []
        }
        this.deliveryLoading = false
      }).catch(() => {
        this.deliveryList = []
        this.deliveryLoading = false
        this.$message.error('获取交易条款列表失败')
      })
    },

  

    // 加载物料列表
    loadMaterialList(orderNo) {
      this.materialLoading = true
      searchMaterialList({ orderNo: orderNo }).then(({data}) => {
        if (data.code === 0) {
          this.materialList = data.rows || []
        } else {
          this.materialList = []
        }
        this.materialLoading = false
      }).catch(() => {
        this.materialList = []
        this.materialLoading = false
        this.$message.error('获取物料列表失败')
      })
    },
    openDialog(row) {
      if (row) {
        this.dialogTitle = '编辑询价单'
        this.editMode = true
        this.form = { ...row }
      } else {
        this.dialogTitle = '新增询价单'
        this.editMode = false
        const today = this.getTodayDate()
        this.form = {
          id: '',
          site: this.$store.state.user.site,
          orderNo: '',
          supplierId: '',
          supplierName: '',
          orderDate: today,
          wantReplyDate: today,
          userName: this.$store.state.user.name,
          buyer: '',
          paymentTerm: '',
          paymentTermDesc: '',
          deliveryTerm: '',
          deliveryTermDesc: '',
          currency: '',
          currencyRate: 1,
          taxRate: 0,
          taxCode:'',
          otherCondition: '',
          phoneNo: '',
          faxNo: '',
          contact: '',
          remark: '',
          printed : "N",
          status: '待提交'
        }
      }
      this.dialogVisible = true
    },
    validateForm() {
      if (!this.form.supplierId) { this.$message.warning('供应商编码不能为空'); return false }
      if (!this.form.supplierName) { this.$message.warning('供应商名称不能为空'); return false }
      //付款方式不能为空
      if(!this.form.paymentTerm) { this.$message.warning('付款方式不能为空');return false}
      //交易条款不能为空
      if(!this.form.deliveryTerm) { this.$message.warning('交易条款不能为空');return false}
      //货币不能为空
      if(!this.form.currency) { this.$message.warning('货币不能为空');return false}
      //货币汇率不能为空
      if(!this.form.currencyRate) { this.$message.warning('货币汇率不能为空');return false}
      //税率不能为空
      if(!this.form.taxCode) { this.$message.warning('税率不能为空');return false}
      return true
    },
    getTodayDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    submitForm() {
      if (!this.validateForm()) return
      this.submitLoading = true
      const api = this.editMode ? updatePurHeader : createPurHeader
      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(() => {
        deletePurHeader({ 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(() => {})
    },
     updateQuoDetail(row) {
      this.$confirm('确定提交询价单: ' + row.orderNo + ' ?', '提示', { type: 'warning' }).then(() => {
        updatePurDetailStatus({ 
          orderNo: row.orderNo, 
          site: row.site,
          status : "待报价",
          submitFlag : "Y"
        }).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(() => {})
    },

     closePurHeader(row) {
      this.$confirm('确定关闭询价单: ' + row.orderNo + ' ?', '提示', { type: 'warning' }).then(() => {
        updatePurHeaderStatus({ id: row.id,status: '已关闭' }).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(() => {})
    },
  
    // 物料操作
    openMaterialDialog(row) {
      if (!this.currentInquiry) {
        this.$message.warning('请先选择一个询价单')
        return
      }
      if (row) {
        this.materialDialogTitle = '编辑物料'
        this.materialForm = { ...row }
      } else {
        this.materialDialogTitle = '新增物料'
        this.materialForm = {
          id: null,
          site: this.$store.state.user.site,
          partNo: '',
          partDesc: '',
          umid: '',
          spec: '',
          qty: 0,
          remark2: '',
          status: '待提交'
        }
      }
      this.materialDialogVisible = true
    },
    // 物料编码变化时触发，自动带出物料信息
    handlePartNoChange(val) {
      if (!val || val.trim() === '') {
        return
      }
      
      // 假设有一个 getPartInfo 接口
     this.getPartInfo()
    },

    getPartInfo(){   
      // 调用物料信息查询接口
      const params = { 
        site: this.$store.state.user.site,
        partNo: this.materialForm.partNo
      }
      searchPartInfo(params).then(({data}) => {
            console.log(data)
              if (data.code === 0) {
                // 自动填充物料相关信息
                this.materialForm.partNo = data.data.partNo || val
                this.materialForm.partDesc = data.data.partDesc || this.materialForm.partDesc
                this.materialForm.spec = data.data.partSpec || this.materialForm.spec
                this.materialForm.umid = data.data.unit || this.materialForm.umid
                
                // this.$message.success('已自动获取物料信息')
              } else {
                this.$message.warning('未找到该物料信息，请手动填写')
              }
            }).catch(() => {
              this.$message.error('获取物料信息失败')
            })
    },
  

    saveMaterial() {
      if (!this.materialForm.partNo) {
        this.$message.warning('物料编码不能为空')
        return
      }
      if (!this.materialForm.partDesc) {
        this.$message.warning('物料名称不能为空')
        return
      }
      if(!this.materialForm.umid){
        this.$message.warning('请选择计量单位')
         return
      }
      if(this.materialForm.qty <= 0){
        this.$message.warning('请选择询价数量')
         return
      }


      this.materialSubmitLoading = true
      const submitData = {
        ...this.materialForm,
        orderNo: this.currentInquiry.orderNo
      }
      const api = this.materialForm.id ? updateMaterial : createMaterial
      api(submitData).then(({data}) => {
        if (data && data.code === 0) {
          this.$message.success('保存成功')
          this.materialDialogVisible = false
          this.loadMaterialList(this.currentInquiry.orderNo)
        } else {
          this.$message.error((data && data.msg) || '保存失败')
        }
      }).catch(err => {
        this.$message.error('保存失败: ' + err.message)
      }).finally(() => {
        this.materialSubmitLoading = false
      })
    },
    deleteMaterial(row) {
      this.$confirm('确定删除物料: ' + row.partNo + ' ?', '提示', { type: 'warning' }).then(() => {
        deleteMaterial({ id: row.id }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('删除成功')
            this.loadMaterialList(this.currentInquiry.orderNo)
          } else {
            this.$message.error((data && data.msg) || '删除失败')
          }
        }).catch(err => {
          this.$message.error('删除失败: ' + err.message)
        })
      }).catch(() => {})
    },
    
    openUploadDialog(row) {
      if (!row) {
        this.$message.warning('请先选择一个物料')
        return
      }
      if (row) {
        this.uploadDialogTitle = '上传附件'
         this.searchParams = {
          orderRef1: this.$store.state.user.site,
          orderRef2: row.orderNo,
          orderRef3: row.partNo,
          orderReftype: 'purQuotationDetail'  
        }
       
      } 
      this.uploadDialogVisible = true
      this.searchTable()
    },
     // 关闭弹窗
    handleClose() {
      this.$emit('update:visible', false);
      this.$emit('close');
    },

    // 关闭上传弹窗
    handleUploadClose() {
      this.fileList2 = [];
      this.ossForm.remark = '';
    },

    // 查询文件列表
    searchTable() {
      queryOssFilePlus(this.searchParams).then(({ data }) => {
        if (data && data.code == 0) {
          this.fileList = data.rows || [];
        } else {
          this.fileList = [];
        }
      }).catch(() => {
        this.fileList = [];
      });
    },

    // 打开上传弹窗
    handleUpload() {
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      })
      this.fileList2 = [];
      this.ossForm.remark = '';
      this.ossVisible = true;
    },

    onRemoveFile(file, fileList) {
      this.fileList2 = fileList;
    },

    onChangeFile(file, fileList) {
      this.fileList2 = fileList;
    },

    // 提交上传
    submitData() {
      if (this.fileList2.length === 0) {
        this.$message.error('请选择文件');
        return;
      }
      
      this.stagedFileRemark = this.ossForm.remark || '';
      this.uploadLoading = true;
      
      // 准备要上传的文件
      const stagedFiles = [];
      for (let i = 0; i < this.fileList2.length; i++) {
        stagedFiles.push(this.fileList2[i].raw);
      }
      
      // 立即关闭弹窗
      this.ossVisible = false;
      this.fileList2 = [];
      this.ossForm.remark = '';
      
      // 上传文件
      const formData = new FormData();
      for (let i = 0; i < stagedFiles.length; i++) {
        formData.append('file', stagedFiles[i]);
      }
      formData.append('orderRef1', this.searchParams.orderRef1 || '');
      formData.append('orderRef2', this.searchParams.orderRef2 || '');
      formData.append('orderRef3', this.searchParams.orderRef3 || '');
      formData.append('createdBy', this.$store.state.user.name);
      formData.append('fileRemark', this.stagedFileRemark || '');
      formData.append('orderReftype', this.searchParams.orderReftype || 'purQuotationDetail');
      
      ossUploadNoSaveOSSForYJY(formData)
        .then(({ data }) => {
          if (data && data.code === 0) {
            // 移除临时文件，添加上传成功的文件
            this.fileList = this.fileList.filter(f => !f._staged);
            for (let i = 0; i < data.rows.length; i++) {
              this.fileList.push(data.rows[i]);
            }
            
            // 清除暂存数据
            this.stagedFiles = [];
            this.stagedFileRemark = '';
            this.uploadLoading = false;
            
            this.$message.success('上传成功');
            this.$emit('upload-success', data.rows);
          } else {
            this.uploadLoading = false;
            this.$message.warning(data.msg || '文件上传失败');
          }
        })
        .catch(err => {
          this.uploadLoading = false;
          this.$message.error(err.message || err);
        });
    },

    // 下载/预览文件
    handleDownload(row) {
      let image = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      let video = ['mp4', 'avi', 'mov', 'wmv', 'flv'];
      let office = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'];
      let txt = ['txt'];
      let pdf = ['pdf'];
      let type = '';
      
      if (image.includes(row.fileType.toLowerCase())) {
        type = 'image/' + row.fileType;
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: type });
          const fileURL = URL.createObjectURL(blob);
          window.open(fileURL, '_blank');
        });
      } else if (video.includes(row.fileType.toLowerCase())) {
        type = 'video/' + row.fileType;
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: type });
          const fileURL = URL.createObjectURL(blob);
          window.open(fileURL, '_blank');
        });
      } else if (txt.includes(row.fileType.toLowerCase())) {
        type = 'text/plain';
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: type });
          const fileURL = URL.createObjectURL(blob);
          window.open(fileURL, '_blank');
        });
      } else if (office.includes(row.fileType.toLowerCase())) {
        if (row.fileType.toLowerCase() === 'doc' || row.fileType.toLowerCase() === 'docx') {
          type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        } else if (row.fileType.toLowerCase() === 'ppt' || row.fileType.toLowerCase() === 'pptx') {
          type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        } else {
          type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        }
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: 'application/octet-stream;charset=utf-8' });
          const fileName = row.fileName;
          const linkNode = document.createElement('a');
          linkNode.download = fileName;
          linkNode.style.display = 'none';
          linkNode.href = URL.createObjectURL(blob);
          document.body.appendChild(linkNode);
          linkNode.click();
          URL.revokeObjectURL(linkNode.href);
          document.body.removeChild(linkNode);
        });
      } else if (pdf.includes(row.fileType.toLowerCase())) {
        type = 'application/pdf';
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: type });
          const fileURL = URL.createObjectURL(blob);
          window.open(fileURL, '_blank');
        });
      } else {
        this.$message({
          message: '不支持的文件类型',
          type: 'warning'
        });
      }
    },

    // 删除已保存的文件
    deleteFileReal(row) {
      if (!row || !row.id) return;
      this.$confirm('确定要删除该文件吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeOss([row.id]).then(({ data }) => {
          if (data && data.code === 0) {
            const idx = this.fileList.findIndex(f => f.id === row.id);
            if (idx !== -1) this.fileList.splice(idx, 1);
            this.$message.success(data.msg || '文件已删除');
            this.$emit('delete-success', row);
          } else {
            this.$message.warning(data.msg || '删除失败');
          }
        }).catch(err => {
          this.$message.error('删除失败：' + (err.message || err));
        });
      }).catch(() => { });
    },

    // 删除临时文件
    deleteFile(index) {
      const f = this.fileList[index];
      if (f && f._staged && f.raw) {
        const idx = this.stagedFiles.findIndex(sf => sf.name === f.raw.name && sf.size === f.raw.size);
        if (idx !== -1) this.stagedFiles.splice(idx, 1);
      }
      this.fileList.splice(index, 1);
    },
     // 刷新列表
    refresh() {
      this.searchTable();
    }
  }
}
</script>

<style scoped>
.pi-search-form { margin-top:0; }
.pi-form { margin-top:-5px; }
.customer-a {
  color: #409EFF;
  cursor: pointer;
  text-decoration: none;
}
.customer-a:hover {
  text-decoration: underline;
}
.customer-bun-min {
  margin-right: 8px;
}
.sub-title {
  font-weight: 600;
  margin: 16px 0 8px 0;
  padding-left: 4px;
  border-left: 4px solid #409eff;
  line-height: 1.2;
  color: #303133;
}
.status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
.status-sent { background-color: #e6f7ff; color: #409eff; }
.status-closed { background-color: #fef0e6; color: #e6a23c; }
.material-action-btn {
  color: #409EFF;
  cursor: pointer;
  margin: 0 4px;
}
.material-action-btn:hover {
  text-decoration: underline;
}
.dialog-footer {
  text-align: center;
}

.rq .auto /deep/ .el-form-item__content {
  height: auto;
  line-height: 1.5;
}
</style>