<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="报价单号" prop="quoteCode">
              <el-input v-model="queryParams.quoteCode" placeholder="请输入报价单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="报价单名称" prop="quoteName">
              <el-input v-model="queryParams.quoteName" placeholder="请输入报价单名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="报价轮次" prop="quoteRound">
              <el-input v-model="queryParams.quoteRound" placeholder="请输入报价轮次" clearable @keyup.enter="handleQuery" />
            </el-form-item>-->
            <!--            <el-form-item label="报价大类" prop="quoteCategory">
              <el-select v-model="queryParams.quoteCategory" placeholder="请选择报价大类" clearable >
                <el-option v-for="dict in quote_category" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="报价类型" prop="quoteType">
              <el-select v-model="queryParams.quoteType" placeholder="请选择报价类型" clearable >
                <el-option v-for="dict in contract_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="业务方向" prop="businessDirection">
              <el-select v-model="queryParams.businessDirection" placeholder="请选择业务方向" clearable >
                <el-option v-for="dict in business_direction" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>-->
            <!--            <el-form-item label="部门" prop="quoteDeptId">
              <el-input v-model="queryParams.quoteDeptId" placeholder="请输入部门" clearable @keyup.enter="handleQuery" />
            </el-form-item>-->
            <!--            <el-form-item label="报价日期" prop="quoteDate">
              <el-date-picker clearable
                              v-model="queryParams.quoteDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择报价日期"
              />
            </el-form-item>
            <el-form-item label="报价有效期起" prop="validFrom">
              <el-date-picker clearable
                              v-model="queryParams.validFrom"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择报价有效期起"
              />
            </el-form-item>
            <el-form-item label="报价有效期" prop="validDays">
              <el-input v-model="queryParams.validDays" placeholder="请输入报价有效期" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="报价有效期止" prop="validTo">
              <el-date-picker clearable
                              v-model="queryParams.validTo"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择报价有效期止"
              />
            </el-form-item>
            <el-form-item label="交货期" prop="deliveryPeriod">
              <el-input v-model="queryParams.deliveryPeriod" placeholder="请输入交货期" clearable @keyup.enter="handleQuery" />
            </el-form-item>-->
            <!--            <el-form-item label="交付/交货方式" prop="deliveryMethod">
              <el-input v-model="queryParams.deliveryMethod" placeholder="请输入交付/交货方式" clearable @keyup.enter="handleQuery" />
            </el-form-item>-->
            <!-- <el-form-item label="付款方式" prop="paymentMethod">
              <el-select v-model="queryParams.paymentMethod" placeholder="请选择付款方式" clearable>
                <el-option v-for="dict in payment_method" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
            <!--            <el-form-item label="币种" prop="currencyType">
              <el-select v-model="queryParams.currencyType" placeholder="请选择币种" clearable >
                <el-option v-for="dict in currency_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="含税信息" prop="taxIncludedInfo">
              <el-input v-model="queryParams.taxIncludedInfo" placeholder="请输入含税信息" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="税率(默认按明细可覆盖)" prop="taxRate">
              <el-input v-model="queryParams.taxRate" placeholder="请输入税率(默认按明细可覆盖)" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="总报价" prop="totalPrice">
              <el-input v-model="queryParams.totalPrice" placeholder="请输入总报价" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="未税总价" prop="totalBeforeTax">
              <el-input v-model="queryParams.totalBeforeTax" placeholder="请输入未税总价" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="税额" prop="totalTax">
              <el-input v-model="queryParams.totalTax" placeholder="请输入税额" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="含税总价" prop="totalIncludingTax">
              <el-input v-model="queryParams.totalIncludingTax" placeholder="请输入含税总价" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户方联系人ID" prop="customerContactId">
              <el-input v-model="queryParams.customerContactId" placeholder="请输入客户方联系人ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户方联系人" prop="customerContactName">
              <el-input v-model="queryParams.customerContactName" placeholder="请输入客户方联系人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户方联系电话" prop="customerContactPhone">
              <el-input v-model="queryParams.customerContactPhone" placeholder="请输入客户方联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户方电子邮箱" prop="customerContactEmail">
              <el-input v-model="queryParams.customerContactEmail" placeholder="请输入客户方电子邮箱" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货方ID" prop="supplierContactId">
              <el-input v-model="queryParams.supplierContactId" placeholder="请输入供货方ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货方联系人" prop="supplierContactName">
              <el-input v-model="queryParams.supplierContactName" placeholder="请输入供货方联系人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货方联系电话" prop="supplierContactPhone">
              <el-input v-model="queryParams.supplierContactPhone" placeholder="请输入供货方联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货方电子邮箱" prop="supplierContactEmail">
              <el-input v-model="queryParams.supplierContactEmail" placeholder="请输入供货方电子邮箱" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目ID(可选)" prop="projectId">
              <el-input v-model="queryParams.projectId" placeholder="请输入项目ID(可选)" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="打印模板ID(可选)" prop="templateId">
              <el-input v-model="queryParams.templateId" placeholder="请输入打印模板ID(可选)" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="附件ID" prop="ossId">
              <el-input v-model="queryParams.ossId" placeholder="请输入附件ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="报价单状态" prop="quoteStatus">
              <el-select v-model="queryParams.quoteStatus" placeholder="请选择报价单状态" clearable >
                <el-option v-for="dict in quote_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="流程状态" prop="flowStatus">
              <el-select v-model="queryParams.flowStatus" placeholder="请选择流程状态" clearable >
                <el-option v-for="dict in flow_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/crm:crmQuoteInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/crm:crmQuoteInfo:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/crm:crmQuoteInfo:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/crm:crmQuoteInfo:export']">导出</el-button>
          </el-col>
          <el-col :span="1.8">
            <el-button
              type="primary"
              plain
              icon="Document"
              :disabled="single"
              @click="handleExportTemplate()"
              v-hasPermi="['oa/crm:crmQuoteInfo:export']"
              >模板导出</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="crmQuoteInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="50" v-if="columns[0].visible" />
        <el-table-column label="报价单号" align="center" prop="quoteCode" v-if="columns[1].visible" />
        <el-table-column label="报价单名称" align="center" prop="quoteName" v-if="columns[2].visible" />
        <el-table-column label="报价轮次" align="center" prop="quoteRound" v-if="columns[3].visible" />
        <el-table-column label="报价大类" align="center" prop="quoteCategory" v-if="columns[4].visible">
          <template #default="scope">
            <dict-tag :options="quote_category" :value="scope.row.quoteCategory" />
          </template>
        </el-table-column>
        <el-table-column label="报价类型" align="center" prop="quoteType" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="contract_type" :value="scope.row.quoteType" />
          </template>
        </el-table-column>
        <el-table-column label="业务方向" align="center" prop="businessDirection" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="business_direction" :value="scope.row.businessDirection" />
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptName" v-if="columns[7].visible" />
        <el-table-column label="报价日期" align="center" prop="quoteDate" width="180" v-if="columns[8].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.quoteDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报价有效期起" align="center" prop="validFrom" width="180" v-if="columns[9].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.validFrom, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报价有效期" align="center" prop="validDays" v-if="columns[10].visible" />
        <el-table-column label="报价有效期止" align="center" prop="validTo" width="180" v-if="columns[11].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.validTo, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="交货期" align="center" prop="deliveryPeriod" v-if="columns[12].visible" />
        <el-table-column label="交付/交货方式" align="center" prop="deliveryMethod" v-if="columns[13].visible" />
        <el-table-column label="付款方式" align="center" prop="paymentMethod" v-if="columns[14].visible">
          <template #default="scope">
            <dict-tag :options="payment_method" :value="scope.row.paymentMethod" />
          </template>
        </el-table-column>
        <el-table-column label="币种" align="center" prop="currencyType" v-if="columns[15].visible">
          <template #default="scope">
            <dict-tag :options="currency_type" :value="scope.row.currencyType" />
          </template>
        </el-table-column>
        <el-table-column label="含税信息" align="center" prop="taxIncludedInfo" v-if="columns[16].visible" />
        <el-table-column label="税率(默认按明细可覆盖)" align="center" prop="taxRate" v-if="columns[17].visible" />
        <el-table-column label="总报价" align="center" prop="totalPrice" v-if="columns[18].visible" />
        <el-table-column label="未税总价" align="center" prop="totalBeforeTax" v-if="columns[19].visible" />
        <el-table-column label="税额" align="center" prop="totalTax" v-if="columns[20].visible" />
        <el-table-column label="含税总价" align="center" prop="totalIncludingTax" v-if="columns[21].visible" />
        <el-table-column label="客户名称" align="center" prop="customerName" v-if="columns[22].visible" />
        <el-table-column label="客户方联系人" align="center" prop="customerContactName" v-if="columns[23].visible" />
        <el-table-column label="客户方联系电话" align="center" prop="customerContactPhone" v-if="columns[24].visible" />
        <el-table-column label="客户方电子邮箱" align="center" prop="customerContactEmail" v-if="columns[25].visible" />
        <el-table-column label="供应商名称" align="center" prop="supplierName" v-if="columns[26].visible" />
        <el-table-column label="供货方联系人" align="center" prop="supplierContactName" v-if="columns[27].visible" />
        <el-table-column label="供货方联系电话" align="center" prop="supplierContactPhone" v-if="columns[28].visible" />
        <el-table-column label="供货方电子邮箱" align="center" prop="supplierContactEmail" v-if="columns[29].visible" />
        <el-table-column label="项目ID(可选)" align="center" prop="projectId" v-if="columns[30].visible" />
        <el-table-column label="打印模板ID(可选)" align="center" prop="templateId" v-if="columns[31].visible" />
        <el-table-column label="附件ID" align="center" prop="ossId" v-if="columns[32].visible" />
        <el-table-column label="报价单状态" align="center" prop="quoteStatus" v-if="columns[33].visible">
          <template #default="scope">
            <dict-tag :options="quote_status" :value="scope.row.quoteStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[34].visible">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[35].visible" />
        <el-table-column label="创建人" align="center" prop="createName" v-if="columns[36].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[37].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 修改：仅草稿或退回状态可编辑（与 projectInfo 保持一致，使用 flowStatus 判断） -->
            <el-tooltip content="修改" placement="top" v-if="scope.row.flowStatus === 'draft' || scope.row.flowStatus === 'back'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/crm:crmQuoteInfo:edit']"></el-button>
            </el-tooltip>
            <!-- 查看：非草稿状态可查看 -->
            <el-tooltip content="查看详情" placement="top" v-if="scope.row.flowStatus && scope.row.flowStatus !== 'draft'">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <!-- 审批记录：非草稿状态可查看 -->
            <el-tooltip content="审批记录" placement="top" v-if="scope.row.flowStatus && scope.row.flowStatus !== 'draft'">
              <el-button link type="warning" icon="Tickets" @click="handleApprovalRecord(scope.row)"></el-button>
            </el-tooltip>
            <!-- 删除：仅草稿状态可删除 -->
            <el-tooltip content="删除" placement="top" v-if="!scope.row.flowStatus || scope.row.flowStatus === 'draft'">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/crm:crmQuoteInfo:remove']"></el-button>
            </el-tooltip>
            <!-- 模板导出 -->
            <el-tooltip content="模板导出" placement="top">
              <el-button
                link
                type="success"
                icon="Document"
                @click="handleExportTemplate(scope.row)"
                v-hasPermi="['oa/crm:crmQuoteInfo:exportTemplate']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改报价单信息对话框 -->
    <!--    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="crmQuoteInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="报价单号" prop="quoteCode">
          <el-input v-model="form.quoteCode" placeholder="请输入报价单号" />
        </el-form-item>
        <el-form-item label="报价单名称" prop="quoteName">
          <el-input v-model="form.quoteName" placeholder="请输入报价单名称" />
        </el-form-item>
        <el-form-item label="报价轮次" prop="quoteRound">
          <el-input v-model="form.quoteRound" placeholder="请输入报价轮次" />
        </el-form-item>
        <el-form-item label="报价大类" prop="quoteCategory">
          <el-radio-group v-model="form.quoteCategory">
            <el-radio
              v-for="dict in quote_category"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报价类型" prop="quoteType">
          <el-select v-model="form.quoteType" placeholder="请选择报价类型">
            <el-option
              v-for="dict in contract_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务方向" prop="businessDirection">
          <el-select v-model="form.businessDirection" placeholder="请选择业务方向">
            <el-option
              v-for="dict in business_direction"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="quoteDeptId">
          <el-input v-model="form.quoteDeptId" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="报价日期" prop="quoteDate">
          <el-date-picker clearable
                          v-model="form.quoteDate"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择报价日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报价有效期起" prop="validFrom">
          <el-date-picker clearable
                          v-model="form.validFrom"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择报价有效期起">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报价有效期" prop="validDays">
          <el-input v-model="form.validDays" placeholder="请输入报价有效期" />
        </el-form-item>
        <el-form-item label="报价有效期止" prop="validTo">
          <el-date-picker clearable
                          v-model="form.validTo"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择报价有效期止">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交货期" prop="deliveryPeriod">
          <el-input v-model="form.deliveryPeriod" placeholder="请输入交货期" />
        </el-form-item>
        <el-form-item label="交付/交货方式" prop="deliveryMethod">
          <el-input v-model="form.deliveryMethod" placeholder="请输入交付/交货方式" />
        </el-form-item>
        <el-form-item label="付款方式" prop="paymentMethod">
          <el-select v-model="form.paymentMethod" placeholder="请选择付款方式">
            <el-option
              v-for="dict in payment_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="币种" prop="currencyType">
          <el-select v-model="form.currencyType" placeholder="请选择币种">
            <el-option
              v-for="dict in currency_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="含税信息" prop="taxIncludedInfo">
          <el-input v-model="form.taxIncludedInfo" placeholder="请输入含税信息" />
        </el-form-item>
        <el-form-item label="税率(默认按明细可覆盖)" prop="taxRate">
          <el-input v-model="form.taxRate" placeholder="请输入税率(默认按明细可覆盖)" />
        </el-form-item>
        <el-form-item label="总报价" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总报价" />
        </el-form-item>
        <el-form-item label="未税总价" prop="totalBeforeTax">
          <el-input v-model="form.totalBeforeTax" placeholder="请输入未税总价" />
        </el-form-item>
        <el-form-item label="税额" prop="totalTax">
          <el-input v-model="form.totalTax" placeholder="请输入税额" />
        </el-form-item>
        <el-form-item label="含税总价" prop="totalIncludingTax">
          <el-input v-model="form.totalIncludingTax" placeholder="请输入含税总价" />
        </el-form-item>
        <el-form-item label="客户方联系人ID" prop="customerContactId">
          <el-input v-model="form.customerContactId" placeholder="请输入客户方联系人ID" />
        </el-form-item>
        <el-form-item label="客户方联系人" prop="customerContactName">
          <el-input v-model="form.customerContactName" placeholder="请输入客户方联系人" />
        </el-form-item>
        <el-form-item label="客户方联系电话" prop="customerContactPhone">
          <el-input v-model="form.customerContactPhone" placeholder="请输入客户方联系电话" />
        </el-form-item>
        <el-form-item label="客户方电子邮箱" prop="customerContactEmail">
          <el-input v-model="form.customerContactEmail" placeholder="请输入客户方电子邮箱" />
        </el-form-item>
        <el-form-item label="供货方ID" prop="supplierContactId">
          <el-input v-model="form.supplierContactId" placeholder="请输入供货方ID" />
        </el-form-item>
        <el-form-item label="供货方联系人" prop="supplierContactName">
          <el-input v-model="form.supplierContactName" placeholder="请输入供货方联系人" />
        </el-form-item>
        <el-form-item label="供货方联系电话" prop="supplierContactPhone">
          <el-input v-model="form.supplierContactPhone" placeholder="请输入供货方联系电话" />
        </el-form-item>
        <el-form-item label="供货方电子邮箱" prop="supplierContactEmail">
          <el-input v-model="form.supplierContactEmail" placeholder="请输入供货方电子邮箱" />
        </el-form-item>
        <el-form-item label="项目ID(可选)" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目ID(可选)" />
        </el-form-item>
        <el-form-item label="打印模板ID(可选)" prop="templateId">
          <el-input v-model="form.templateId" placeholder="请输入打印模板ID(可选)" />
        </el-form-item>
        <el-form-item label="附件ID" prop="ossId">
          <el-input v-model="form.ossId" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="报价单状态" prop="quoteStatus">
          <el-select v-model="form.quoteStatus" placeholder="请选择报价单状态">
            <el-option
              v-for="dict in quote_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流程状态" prop="flowStatus">
          <el-select v-model="form.flowStatus" placeholder="请选择流程状态">
            <el-option
              v-for="dict in flow_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>-->
    <!-- 审批记录 -->
    <ApprovalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="CrmQuoteInfo" lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { addCrmQuoteInfo, delCrmQuoteInfo, exportQuoteTemplate, listCrmQuoteInfo, updateCrmQuoteInfo } from '@/api/oa/crm/crmQuoteInfo';
import { CrmQuoteInfoForm, CrmQuoteInfoQuery, CrmQuoteInfoVO } from '@/api/oa/crm/crmQuoteInfo/types';
import { getCrmCustomerContactList } from '@/api/oa/crm/customerContact';
import FileSaver from 'file-saver';
import { blobValidate } from '@/utils/ruoyi';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();
const { business_direction, currency_type, quote_category, payment_method, quote_status, wf_business_status, contract_type } = toRefs<any>(
  proxy?.useDict('business_direction', 'currency_type', 'quote_category', 'payment_method', 'quote_status', 'wf_business_status', 'contract_type')
);

const crmQuoteInfoList = ref<CrmQuoteInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const crmQuoteInfoFormRef = ref<ElFormInstance>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `序号`, visible: true },
  { key: 1, label: `报价单号`, visible: true },
  { key: 2, label: `报价单名称`, visible: true },
  { key: 3, label: `报价轮次`, visible: false },
  { key: 4, label: `报价大类`, visible: false },
  { key: 5, label: `报价类型`, visible: false },
  { key: 6, label: `业务方向`, visible: false },
  { key: 7, label: `部门`, visible: false },
  { key: 8, label: `报价日期`, visible: true },
  { key: 9, label: `报价有效期起`, visible: true },
  { key: 10, label: `报价有效期`, visible: false },
  { key: 11, label: `报价有效期止`, visible: true },
  { key: 12, label: `交货期`, visible: false },
  { key: 13, label: `交付/交货方式`, visible: false },
  { key: 14, label: `付款方式`, visible: false },
  { key: 15, label: `币种`, visible: false },
  { key: 16, label: `含税信息`, visible: false },
  { key: 17, label: `税率(默认按明细可覆盖)`, visible: false },
  { key: 18, label: `总报价`, visible: true },
  { key: 19, label: `未税总价`, visible: false },
  { key: 20, label: `税额`, visible: false },
  { key: 21, label: `含税总价`, visible: true },
  { key: 22, label: `客户名称`, visible: true },
  { key: 23, label: `客户方联系人`, visible: false },
  { key: 24, label: `客户方联系电话`, visible: false },
  { key: 25, label: `客户方电子邮箱`, visible: false },
  { key: 26, label: `供应商名称`, visible: false },
  { key: 27, label: `供货方联系人`, visible: false },
  { key: 28, label: `供货方联系电话`, visible: false },
  { key: 29, label: `供货方电子邮箱`, visible: false },
  { key: 30, label: `项目ID(可选)`, visible: false },
  { key: 31, label: `打印模板ID(可选)`, visible: false },
  { key: 32, label: `附件ID`, visible: false },
  { key: 33, label: `报价单状态`, visible: true },
  { key: 34, label: `流程状态`, visible: true },
  { key: 35, label: `备注`, visible: true },
  { key: 36, label: `创建人`, visible: true },
  { key: 37, label: `创建时间`, visible: true }
  // 预留：删除标志、创建部门、更新人、更新时间等
]);

const initFormData: CrmQuoteInfoForm = {
  quoteId: undefined,
  quoteCode: undefined,
  quoteName: undefined,
  quoteRound: undefined,
  quoteCategory: undefined,
  quoteType: undefined,
  businessDirection: undefined,
  quoteDeptId: undefined,
  quoteDate: undefined,
  validFrom: undefined,
  validDays: undefined,
  validTo: undefined,
  deliveryPeriod: undefined,
  deliveryMethod: undefined,
  paymentMethod: undefined,
  currencyType: undefined,
  taxIncludedInfo: undefined,
  taxRate: undefined,
  totalPrice: undefined,
  totalBeforeTax: undefined,
  totalTax: undefined,
  totalIncludingTax: undefined,
  customerContactId: undefined,
  customerContactName: undefined,
  customerContactPhone: undefined,
  customerContactEmail: undefined,
  supplierContactId: undefined,
  supplierContactName: undefined,
  supplierContactPhone: undefined,
  supplierContactEmail: undefined,
  projectId: undefined,
  templateId: undefined,
  ossId: undefined,
  quoteStatus: undefined,
  flowStatus: undefined,
  remark: undefined,
  createName: undefined
};
const data = reactive<PageData<CrmQuoteInfoForm, CrmQuoteInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    quoteCode: undefined,
    quoteName: undefined,
    quoteRound: undefined,
    quoteCategory: undefined,
    quoteType: undefined,
    businessDirection: undefined,
    quoteDeptId: undefined,
    quoteDate: undefined,
    validFrom: undefined,
    validDays: undefined,
    validTo: undefined,
    deliveryPeriod: undefined,
    deliveryMethod: undefined,
    paymentMethod: undefined,
    currencyType: undefined,
    taxIncludedInfo: undefined,
    taxRate: undefined,
    totalPrice: undefined,
    totalBeforeTax: undefined,
    totalTax: undefined,
    totalIncludingTax: undefined,
    customerContactId: undefined,
    customerContactName: undefined,
    customerContactPhone: undefined,
    customerContactEmail: undefined,
    supplierContactId: undefined,
    supplierContactName: undefined,
    supplierContactPhone: undefined,
    supplierContactEmail: undefined,
    projectId: undefined,
    templateId: undefined,
    ossId: undefined,
    quoteStatus: undefined,
    flowStatus: undefined,
    createName: undefined,
    params: {}
  },
  rules: {
    quoteId: [{ required: true, message: '报价ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询报价单信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCrmQuoteInfo(queryParams.value);
  crmQuoteInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  crmQuoteInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CrmQuoteInfoVO[]) => {
  ids.value = selection.map((item) => item.quoteId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作（改为路由跳转到编辑页） */
const handleAdd = () => {
  proxy.$tab.closePage(route);
  router.push({
    path: '/oa/crm/crmQuoteInfo/edit',
    query: { type: 'add' }
  });
};

/** 修改按钮操作（改为路由跳转到编辑页） */
const handleUpdate = (row?: CrmQuoteInfoVO) => {
  const _quoteId = row?.quoteId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: '/oa/crm/crmQuoteInfo/edit',
    query: { id: _quoteId, type: 'update' }
  });
};

/** 查看按钮操作（查看模式只读） */
const handleView = (row?: CrmQuoteInfoVO) => {
  const _quoteId = row?.quoteId;
  proxy.$tab.closePage(route);
  router.push({
    path: '/oa/crm/crmQuoteInfo/edit',
    query: { id: _quoteId, type: 'view' }
  });
};

/** 提交按钮 */
const submitForm = () => {
  crmQuoteInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.quoteId) {
        await updateCrmQuoteInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addCrmQuoteInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CrmQuoteInfoVO) => {
  const _quoteIds = row?.quoteId || ids.value;
  await proxy?.$modal.confirm('是否确认删除报价单信息编号为"' + _quoteIds + '"的数据项？').finally(() => (loading.value = false));
  await delCrmQuoteInfo(_quoteIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/crm/crmQuoteInfo/export',
    {
      ...queryParams.value
    },
    `crmQuoteInfo_${new Date().getTime()}.xlsx`
  );
};

/** 审批记录按钮操作 */
const handleApprovalRecord = (row: CrmQuoteInfoVO) => {
  approvalRecordRef.value?.init(row.quoteId as any);
};

/** 模板导出（支持选中或行内按钮，GET Blob 下载） */
const handleExportTemplate = async (row?: CrmQuoteInfoVO) => {
  const _quoteId = row?.quoteId || ids.value[0];
  if (!_quoteId) {
    proxy?.$modal.msgWarning('请先选择一条报价记录');
    return;
  }
  try {
    const resp = await exportQuoteTemplate(_quoteId);
    // 校验是否为有效文件（后端错误时返回JSON）
    if (blobValidate(resp as any)) {
      const blob = resp as any;
      FileSaver.saveAs(blob as Blob, `报价单_${new Date().getTime()}.xlsx`);
    } else {
      const resText = await (resp as any).text();
      const rspObj = JSON.parse(resText);
      proxy?.$modal.msgError(rspObj.msg || '导出失败');
    }
  } catch (e) {
    console.error(e);
    proxy?.$modal.msgError('导出失败，请联系管理员');
  }
};

let crmCustomerContactList = ref([]);
const getCustomerContactList = async () => {
  const res = await getCrmCustomerContactList(null);
  crmCustomerContactList.value = res.data;
};
onMounted(() => {
  getCustomerContactList();
  getList();
});
</script>
