<template>
  <doc-alert title="【销售】销售订单、出库、退货" url="https://doc.iocoder.cn/erp/sale/" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="换货单号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入换货单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          clearable
          filterable
          placeholder="请选择产品"
          class="!w-240px"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="换货时间" prop="exchangeTime">
        <el-date-picker
          v-model="queryParams.exchangeTime"
          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-240px"
        />
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          clearable
          filterable
          placeholder="请选择客户"
          class="!w-240px"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未审核" value="10" />
          <el-option label="已审核" value="20" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联出库单" prop="outNo">
        <el-input
          v-model="queryParams.outNo"
          placeholder="请输入关联出库单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </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="['erp:sale-exchange:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:sale-exchange:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleDelete(selectionList.map((item) => item.id))"
          v-hasPermi="['erp:sale-exchange:delete']"
          :disabled="selectionList.length === 0"
        >
          <Icon icon="ep:delete" 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"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="换货单号" align="center" prop="no" width="180"/>
      <el-table-column
        label="换货时间"
        align="center"
        prop="exchangeTime"
        :formatter="dateFormatter" width="180" />
      <el-table-column label="客户" align="center" prop="customerName" />
      <el-table-column label="销售人员" align="center" prop="saleUserName" />
      <el-table-column label="关联出库单" align="center" prop="outNo" width="180px">
        <template #default="scope">
          <el-link
            v-if="scope.row.outNo"
            type="primary"
            @click="openSaleOutDetail(scope.row.outId)"
          >
            {{ scope.row.outNo }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="换出商品总数" align="center" prop="totalOutCount" />
      <el-table-column label="换入商品总数" align="center" prop="totalInCount" />
      <el-table-column label="总金额" align="center" prop="totalPrice">
        <template #default="scope">
          <span>{{ erpPriceInputFormatter(scope.row.totalPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_AUDIT_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        width="220"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="详情" placement="top">
            <el-button
              link
              type="primary"
              @click="openForm('detail', scope.row.id)"
              v-hasPermi="['erp:sale-exchange:query']"
            >
              详情
            </el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['erp:sale-exchange:update']"
              :disabled="scope.row.status === 20"
            >
              编辑
            </el-button>
          </el-tooltip>
          <el-tooltip content="审核" placement="top" v-if="scope.row.status === 10">
            <el-button
              link
              type="success"
              @click="handleUpdateStatus(scope.row.id, 20)"
              v-hasPermi="['erp:sale-exchange:update-status']"
            >
              审核
            </el-button>
          </el-tooltip>
          <el-tooltip content="反审核" placement="top" v-else>
            <el-button
              link
              type="warning"
              @click="handleUpdateStatus(scope.row.id, 10)"
              v-hasPermi="['erp:sale-exchange:update-status']"
            >
              反审核
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="danger"
              @click="handleDelete([scope.row.id])"
              v-hasPermi="['erp:sale-exchange:delete']"
            >
              删除
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

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

  <!-- 销售出库单详情弹窗 -->
  <SaleOutForm ref="saleOutFormRef" />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { getSaleExchangePage, deleteSaleExchange, updateSaleExchangeStatus, exportSaleExchange, SaleExchangeVO } from '@/api/erp/sale/exchange'
import {ProductApi,ProductVO} from '@/api/erp/product/product'
import {CustomerApi,CustomerVO} from '@/api/erp/sale/customer'
import SaleExchangeForm from './SaleExchangeForm.vue'
import { erpPriceInputFormatter } from '@/utils'
import SaleOutForm from '@/views/erp/sale/out/SaleOutForm.vue'
import {ErpBizType} from "@/utils/constants";

defineOptions({ name: 'ErpSaleExchange' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const total = ref(0)
const list = ref([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  customerId: undefined,
  productId: undefined,
  exchangeTime: [],
  status: undefined,
  outNo: undefined,
  remark: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)
const selectionList = ref<SaleExchangeVO[]>([])

const productList = ref<ProductVO[]>([])
const customerList = ref<CustomerVO[]>([])

const getList = async () => {
  loading.value = true
  try {
    const data = await getSaleExchangePage(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 handleSelectionChange = (selection: SaleExchangeVO[]) => {
  selectionList.value = selection
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (ids: number[]) => {
  try {
    await message.delConfirm()
    await deleteSaleExchange(ids)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleUpdateStatus = async (id: number, status: number) => {
  try {
    await updateSaleExchangeStatus(id, status)
    message.success('更新状态成功')
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await exportSaleExchange(queryParams)
    download.excel(data, '销售换货.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const saleOutFormRef = ref()
const openSaleOutDetail = (id: number) => {
  console.log('打开销售出库单详情', id)
  saleOutFormRef.value.open('detail', id)

}


if (onMounted) {
  onMounted(async () => {
    await getList()
    productList.value = await ProductApi.getProductSimpleList()
    customerList.value = await CustomerApi.getCustomerSimpleList()
  })
}
</script>
