<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="customerId">
              <el-select v-model="queryParams.customerId" placeholder="请选择客户名称" clearable filterable style="width: 220px">
                <el-option v-for="item in customerList" :key="item.customerId" :label="item.customerName" :value="item.customerId" />
              </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.8">
            <el-button
              type="primary"
              plain
              icon="Document"
              :disabled="single"
              @click="handleExportTemplate()"
              v-hasPermi="['oa/crm:crmQuoteInfo:export']"
              >PDF预览</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="60" v-if="columns[0].visible" />
        <el-table-column label="报价单号" align="center" prop="quoteCode" width="160" v-if="columns[1].visible" show-overflow-tooltip />
        <el-table-column label="报价单名称" align="center" prop="quoteName" width="200" v-if="columns[2].visible" show-overflow-tooltip />
        <el-table-column label="报价轮次" align="center" prop="quoteRound" width="100" v-if="columns[3].visible" />
        <el-table-column label="报价大类" align="center" prop="quoteCategory" width="120" 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" width="120" 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" width="120" 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="customerName" width="180" v-if="columns[23].visible" show-overflow-tooltip />
        <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}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报价有效期" align="center" prop="validDays" width="100" 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}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="交货期" align="center" prop="deliveryPeriod" width="100" v-if="columns[12].visible" />
        <el-table-column label="质保期" align="center" prop="warrantyPeriod" width="100" v-if="columns[13].visible" />
        <el-table-column label="交付/交货方式" align="center" prop="deliveryMethod" width="140" v-if="columns[14].visible" show-overflow-tooltip />
        <el-table-column label="付款方式" align="center" prop="paymentMethod" width="120" v-if="columns[15].visible">
          <template #default="scope">
            <span>{{ scope.row.paymentMethod || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="币种" align="center" prop="currencyType" width="80" v-if="columns[16].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" width="100" v-if="columns[17].visible" show-overflow-tooltip />
        <el-table-column label="税率" align="center" prop="taxRate" width="180" v-if="columns[18].visible" />
        <el-table-column label="总报价" align="center" prop="totalPrice" width="130" v-if="columns[19].visible" />
        <el-table-column label="未税总价" align="center" prop="totalBeforeTax" width="130" v-if="columns[20].visible" />
        <el-table-column label="税额" align="center" prop="totalTax" width="130" v-if="columns[21].visible" />
        <el-table-column label="含税总价" align="center" prop="totalIncludingTax" width="130" v-if="columns[22].visible" />
        <el-table-column
          label="客户方联系人"
          align="center"
          prop="customerContactName"
          width="130"
          v-if="columns[24].visible"
          show-overflow-tooltip
        />
        <el-table-column label="客户方联系电话" align="center" prop="customerContactPhone" width="140" v-if="columns[25].visible" />
        <el-table-column
          label="客户方电子邮箱"
          align="center"
          prop="customerContactEmail"
          width="180"
          v-if="columns[26].visible"
          show-overflow-tooltip
        />
        <el-table-column label="供应商名称" align="center" prop="supplierName" width="180" v-if="columns[27].visible" show-overflow-tooltip />
        <el-table-column
          label="供货方联系人"
          align="center"
          prop="supplierContactName"
          width="130"
          v-if="columns[28].visible"
          show-overflow-tooltip
        />
        <el-table-column label="供货方联系电话" align="center" prop="supplierContactPhone" width="140" v-if="columns[29].visible" />
        <el-table-column
          label="供货方电子邮箱"
          align="center"
          prop="supplierContactEmail"
          width="180"
          v-if="columns[30].visible"
          show-overflow-tooltip
        />
        <el-table-column label="部门" align="center" prop="deptName" width="120" v-if="columns[7].visible" show-overflow-tooltip />
        <el-table-column label="项目ID(可选)" align="center" prop="projectId" width="120" v-if="columns[31].visible" />
        <el-table-column label="打印模板ID(可选)" align="center" prop="templateId" width="140" v-if="columns[32].visible" />
        <el-table-column label="附件ID" align="center" prop="ossId" width="120" v-if="columns[33].visible" />
        <el-table-column label="报价单状态" align="center" prop="quoteStatus" width="120" v-if="columns[34].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" width="120" v-if="columns[35].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" width="200" v-if="columns[36].visible" show-overflow-tooltip />
        <el-table-column label="创建人" align="center" prop="createName" width="100" v-if="columns[37].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[38].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="100" 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>
            <!-- 参考合同信息 contractView：仅当已绑定模板时显示预览/导出入口，避免无模板时反复告警 -->
            <el-tooltip content="PDF预览" placement="top" v-if="scope.row.templateId != null">
              <el-button
                link
                type="info"
                icon="Download"
                @click="handleExportTemplate(scope.row)"
                v-hasPermi="['oa/crm:crmQuoteInfo:export']"
              ></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>
    <!-- 审批记录 -->
    <ApprovalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="CrmQuoteInfo" lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { delCrmQuoteInfo, listCrmQuoteInfo } from '@/api/oa/crm/crmQuoteInfo';
import { CrmQuoteInfoForm, CrmQuoteInfoQuery, CrmQuoteInfoVO } from '@/api/oa/crm/crmQuoteInfo/types';
import { getCrmCustomerInfoList } from '@/api/oa/crm/customerInfo';
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, quote_status, wf_business_status, contract_type } = toRefs<any>(
  proxy?.useDict('business_direction', 'currency_type', 'quote_category', 'quote_status', 'wf_business_status', 'contract_type')
);

const crmQuoteInfoList = ref<CrmQuoteInfoVO[]>([]);
const customerList = ref<any[]>([]);
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 approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `序号`, visible: false },
  { 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: false },
  { 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: false },
  { key: 19, label: `总报价`, visible: true },
  { key: 20, label: `未税总价`, visible: false },
  { key: 21, label: `税额`, visible: false },
  { key: 22, label: `含税总价`, visible: true },
  { key: 23, label: `客户名称`, visible: true },
  { 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: `供货方电子邮箱`, visible: false },
  { key: 31, label: `项目ID(可选)`, visible: false },
  { key: 32, label: `打印模板ID(可选)`, visible: false },
  { key: 33, label: `附件ID`, visible: false },
  { key: 34, label: `报价单状态`, visible: true },
  { key: 35, label: `流程状态`, visible: true },
  { key: 36, label: `备注`, visible: true },
  { key: 37, label: `创建人`, visible: true },
  { key: 38, 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,
  warrantyPeriod: 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,
    warrantyPeriod: undefined,
    deliveryMethod: undefined,
    paymentMethod: undefined,
    currencyType: undefined,
    taxIncludedInfo: undefined,
    taxRate: undefined,
    totalPrice: undefined,
    totalBeforeTax: undefined,
    totalTax: undefined,
    totalIncludingTax: undefined,
    customerId: 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 } = 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 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: '/quote/crmQuoteInfo/edit',
    query: { type: 'add' }
  });
};

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

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

/** 删除按钮操作 */
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 handleApprovalRecord = (row: CrmQuoteInfoVO) => {
  approvalRecordRef.value?.init(row.quoteId as any);
};

/** 模板导出：参考合同信息 contractView，直接跳转系统菜单已配置的 /quote/quoteView，由预览页执行导出 */
const handleExportTemplate = (row?: CrmQuoteInfoVO) => {
  const _quote = row || crmQuoteInfoList.value.find((item) => item.quoteId === ids.value[0]);
  if (!_quote?.quoteId) {
    proxy?.$modal.msgWarning('请先选择一条报价记录');
    return;
  }
  if (!_quote.templateId) {
    proxy?.$modal.msgWarning('请先在报价单上选择打印模板');
    return;
  }
  router.push({
    path: '/quote/quoteView',
    query: { templateId: _quote.templateId, quoteId: _quote.quoteId }
  });
};

onMounted(() => {
  getCrmCustomerInfoList({}).then((res) => {
    customerList.value = res.data || [];
  });
  getList();
});
</script>
