<template>
  <div class="p-2">
    <el-alert v-if="detailQuoteId" :title="detailQuoteTitle" type="info" show-icon :closable="false" class="mb-[10px]" />
    <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="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="SAP物料名称" prop="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入SAP物料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="销售物料名称" prop="saleMaterialName">
              <el-input v-model="queryParams.saleMaterialName" placeholder="请输入销售物料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料编号" prop="materialCode">
              <el-input v-model="queryParams.materialCode" placeholder="请输入物料编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="规格描述" prop="specificationDescription">
              <el-input v-model="queryParams.specificationDescription" placeholder="请输入规格描述" clearable @keyup.enter="handleQuery" />
            </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="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/crm:crmQuoteMaterial: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="crmQuoteMaterialList">
        <el-table-column label="报价单号" align="center" prop="quoteCode" min-width="160" v-if="columns[0].visible" show-overflow-tooltip />
        <el-table-column label="报价单名称" align="center" prop="quoteName" min-width="180" v-if="columns[1].visible" show-overflow-tooltip />
        <el-table-column label="报价日期" align="center" prop="quoteDate" width="180" v-if="columns[3].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="quoteStatus" width="120" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="quote_status" :value="scope.row.quoteStatus" />
          </template>
        </el-table-column>
        <el-table-column label="付款方式" align="center" prop="paymentMethod" width="120" v-if="columns[7].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" width="100" v-if="columns[8].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" min-width="140" v-if="columns[9].visible" show-overflow-tooltip />
        <el-table-column label="总报价" align="center" prop="totalPrice" width="120" v-if="columns[10].visible">
          <template #default="scope">
            {{ scope.row.totalPrice ? Number(scope.row.totalPrice).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="未税总价" align="center" prop="totalBeforeTax" width="120" v-if="columns[11].visible">
          <template #default="scope">
            {{ scope.row.totalBeforeTax ? Number(scope.row.totalBeforeTax).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="税额" align="center" prop="totalTax" width="120" v-if="columns[12].visible">
          <template #default="scope">
            {{ scope.row.totalTax ? Number(scope.row.totalTax).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="含税总价" align="center" prop="totalIncludingTax" width="120" v-if="columns[13].visible">
          <template #default="scope">
            {{ scope.row.totalIncludingTax ? Number(scope.row.totalIncludingTax).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" prop="itemNo" width="80" v-if="columns[14].visible" />
        <el-table-column label="产品名称" align="center" prop="productName" min-width="160" v-if="columns[15].visible" show-overflow-tooltip />
        <el-table-column
          label="规格描述"
          align="center"
          prop="specificationDescription"
          min-width="160"
          v-if="columns[16].visible"
          show-overflow-tooltip
        />
        <el-table-column label="物料编号" align="center" prop="materialCode" min-width="140" v-if="columns[17].visible" show-overflow-tooltip />
        <el-table-column label="SAP物料名称" align="center" prop="materialName" min-width="160" v-if="columns[18].visible" show-overflow-tooltip />
        <el-table-column
          label="销售物料名称"
          align="center"
          prop="saleMaterialName"
          min-width="160"
          v-if="columns[19].visible"
          show-overflow-tooltip
        />
        <el-table-column label="数量" align="center" prop="amount" width="120" v-if="columns[20].visible">
          <template #default="scope">
            {{ scope.row.amount ? Number(scope.row.amount).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="unitName" width="100" v-if="columns[21].visible" show-overflow-tooltip />
        <el-table-column label="未税单价" align="center" prop="beforePrice" width="120" v-if="columns[22].visible">
          <template #default="scope">
            {{ scope.row.beforePrice ? Number(scope.row.beforePrice).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="税率(%)" align="center" prop="taxRate" width="100" v-if="columns[23].visible">
          <template #default="scope">
            {{ scope.row.taxRate ? Number(scope.row.taxRate).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="含税单价" align="center" prop="includingPrice" width="120" v-if="columns[24].visible">
          <template #default="scope">
            {{ scope.row.includingPrice ? Number(scope.row.includingPrice).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center" prop="subtotal" width="120" v-if="columns[25].visible">
          <template #default="scope">
            {{ scope.row.subtotal ? Number(scope.row.subtotal).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="160" v-if="columns[26].visible" show-overflow-tooltip />
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="CrmQuoteMaterial" lang="ts">
import { useRoute } from 'vue-router';
import { listCrmQuoteMaterial } from '@/api/oa/crm/crmQuoteMaterial';
import { CrmQuoteMaterialQuery, CrmQuoteMaterialVO } from '@/api/oa/crm/crmQuoteMaterial/types';

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

const crmQuoteMaterialList = ref<CrmQuoteMaterialVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const detailQuoteId = computed(() => route.query.quoteId as string | undefined);
const detailQuoteTitle = computed(() => {
  const quoteCode = route.query.quoteCode as string | undefined;
  const quoteName = route.query.quoteName as string | undefined;
  // 从报价主表按上下文跳进来时，优先展示业务可识别的单号/名称；
  // 不回退展示 quoteId，是为了避免把技术字段暴露给业务用户。
  if (quoteCode && quoteName) {
    return `当前查看报价明细：${quoteCode} / ${quoteName}`;
  }
  if (quoteCode) {
    return `当前查看报价明细：${quoteCode}`;
  }
  return '当前按指定报价单查看明细';
});

const columns = ref<FieldOption[]>([
  // 列顺序按“先主表概览、后明细行项目”组织：
  // 业务人员在明细页先看整单背景，再看物料行，认知负担更低。
  { key: 0, label: `报价单号`, visible: true },
  { key: 1, label: `报价单名称`, visible: true },
  // 下面三个字段按你的要求隐藏；保留在列配置中只是为了不打乱既有 right-toolbar 键位顺序。
  { key: 2, label: `报价轮次`, visible: false },
  { key: 3, label: `报价日期`, visible: true },
  { key: 4, label: `报价类型`, visible: false },
  { key: 5, label: `业务方向`, visible: false },
  { key: 6, label: `报价单状态`, visible: true },
  { key: 7, label: `付款方式`, visible: true },
  { key: 8, label: `币种`, visible: true },
  { key: 9, label: `含税信息`, visible: true },
  { key: 10, label: `总报价`, visible: true },
  { key: 11, label: `未税总价`, visible: true },
  { key: 12, label: `税额`, visible: true },
  { key: 13, label: `含税总价`, visible: true },
  { key: 14, label: `序号`, visible: true },
  { key: 15, label: `产品名称`, visible: true },
  { key: 16, label: `规格描述`, visible: true },
  { key: 17, label: `物料编号`, visible: true },
  { key: 18, label: `SAP物料名称`, visible: true },
  { key: 19, label: `销售物料名称`, visible: true },
  { key: 20, label: `数量`, visible: true },
  { key: 21, label: `单位`, visible: true },
  { key: 22, label: `未税单价`, visible: true },
  { key: 23, label: `税率(%)`, visible: true },
  { key: 24, label: `含税单价`, visible: true },
  { key: 25, label: `小计`, visible: true },
  { key: 26, label: `备注`, visible: true }
]);

const initQueryParams: CrmQuoteMaterialQuery = {
  pageNum: 1,
  pageSize: 10,
  quoteId: undefined,
  quoteCode: undefined,
  quoteName: undefined,
  itemNo: undefined,
  productName: undefined,
  materialCode: undefined,
  materialName: undefined,
  saleMaterialName: undefined,
  specificationDescription: undefined,
  materialId: undefined,
  relationMaterialId: undefined,
  amount: undefined,
  unitId: undefined,
  unitName: undefined,
  beforePrice: undefined,
  taxRate: undefined,
  includingPrice: undefined,
  subtotal: undefined,
  activeFlag: undefined,
  params: {}
};

const queryParams = reactive<CrmQuoteMaterialQuery>({ ...initQueryParams });

const getList = async () => {
  loading.value = true;
  try {
    const res = await listCrmQuoteMaterial(queryParams);
    crmQuoteMaterialList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  // 明细页重置后仍保持当前报价上下文：
  // 否则用户从某张报价单点进来后点“重置”，会突然看到全量明细，业务上非常容易误判数据归属。
  Object.assign(queryParams, {
    ...initQueryParams,
    quoteId: detailQuoteId.value
  });
  queryFormRef.value?.clearValidate?.();
  handleQuery();
};

const handleExport = () => {
  // 导出直接复用当前查询条件，确保“页面看到什么口径，导出就是什么口径”。
  // 这样业务筛过报价单号/产品名称后，导出的 Excel 不会出现与页面结果不一致的问题。
  proxy?.download(
    'oa/crm/crmQuoteMaterial/export',
    {
      ...queryParams
    },
    `crmQuoteMaterial_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  if (detailQuoteId.value) {
    queryParams.quoteId = detailQuoteId.value;
  }
  getList();
});
</script>
