<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="服务购买方" prop="serviceBuyer">
        <el-input
          v-model="queryParams.serviceBuyer"
          placeholder="请输入服务购买方"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="车架号" prop="vin">
        <el-input
          v-model="queryParams.vin"
          placeholder="请输入车架号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="门店" prop="storeId">
        <el-select
          v-model="queryParams.storeId"
          placeholder="请选择门店"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="store in storeList"
            :key="store.id"
            :label="store.storeName"
            :value="store.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['car:renewal-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['car:renewal-order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="index" label="序号" align="center" width="60" />
      <el-table-column label="车牌号" align="center" prop="licensePlate" width="120">
        <template #default="scope">
          <span
            v-if="scope.row.licensePlate"
            class="license-plate-link"
            @click="openForm('update', scope.row.id)"
          >
            {{ scope.row.licensePlate }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="汽车品牌" align="center" prop="carBrand" />
      <el-table-column label="车型" align="center" prop="carModel" />
      <el-table-column label="厂牌型号" align="center" prop="factoryModel" />
      <el-table-column label="发票金额" align="center" prop="invoiceAmount" :formatter="priceFormatter" />
      <el-table-column label="购买时公里数" align="center" prop="purchaseMileage" />
      <el-table-column label="发动机号" align="center" prop="engineNo" />
      <el-table-column label="车架号" align="center" prop="vin" />
      <el-table-column label="发票日期" align="center" prop="invoiceDate" :formatter="dateFormatter2" />
      <el-table-column label="发票图片" align="center" prop="invoiceUrl" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.invoiceUrl"
            :src="scope.row.invoiceUrl"
            :preview-src-list="[scope.row.invoiceUrl]"
            preview-teleported
            fit="cover"
            class="h-60px w-60px cursor-pointer"
            lazy
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="服务购买方" align="center" prop="serviceBuyer" />
      <el-table-column label="车辆购买方" align="center" prop="carBuyer" />
      <el-table-column label="证件类型" align="center" prop="certType" />
      <el-table-column label="联系电话" align="center" prop="mobile" />
      <el-table-column label="证件号码" align="center" prop="certNo" />
      <el-table-column label="联系地址" align="center" prop="contactAddress" />
      <el-table-column label="会员邮箱" align="center" prop="memberEmail" />
      <el-table-column label="门店" align="center" prop="storeName" />
      <el-table-column label="服务产品" align="center" prop="serviceProduct" />
      <el-table-column label="产品时效" align="center" prop="productValidity" />
      <el-table-column label="原厂质保时长" align="center" prop="originalWarrantyYears" />
      <el-table-column label="原厂质保里程" align="center" prop="originalWarrantyMileage" />
      <el-table-column label="产品费用" align="center" prop="productFee" :formatter="priceFormatter" />
      <el-table-column label="结算方式" align="center" prop="settlementMethod" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="录单人" align="center" prop="inputUser" />
      <el-table-column label="合同备注" align="center" prop="contractRemark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['car:renewal-order:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['car:renewal-order:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RenewalOrderForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import { erpPriceTableColumnFormatter } from '@/utils'
import download from '@/utils/download'
import { RenewalOrderApi, RenewalOrderVO } from '@/api/car/renewalorder'
import { StoreApi, StoreVO } from '@/api/tire/store'
import RenewalOrderForm from './RenewalOrderForm.vue'

/** 车辆续保订单 列表 */
defineOptions({ name: 'RenewalOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<RenewalOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const storeList = ref<StoreVO[]>([]) // 门店列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  licensePlate: undefined,
  serviceBuyer: undefined,
  mobile: undefined,
  vin: undefined,
  storeId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RenewalOrderApi.getRenewalOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RenewalOrderApi.deleteRenewalOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RenewalOrderApi.exportRenewalOrder(queryParams)
    download.excel(data, '车辆续保订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取门店列表 */
const getStoreList = async () => {
  try {
    const data = await StoreApi.getStorePage({ pageNo: 1, pageSize: -1 })
    storeList.value = data.list || []
  } catch (error) {
    console.error('获取门店列表失败:', error)
  }
}

/** 金额格式化 */
const priceFormatter = erpPriceTableColumnFormatter

/** 初始化 **/
onMounted(() => {
  getStoreList()
  getList()
})
</script>

<style scoped>
.license-plate-link {
  color: #409eff;
  text-decoration: underline;
  cursor: pointer;
}

.license-plate-link:hover {
  color: #66b1ff;
}
</style>
