<template>
  <div class="table_page">
    <div class="titleHeader">
      <div>
        <el-input style="width: 250px; height: 30px; margin-right: 10px; font-size: 14px" suffix-icon="Search"
                  placeholder="请输入订单编号" v-model="orderNumber"></el-input>
        <el-button class="ml-5" type="primary" @click="load(orderNumber)" style="height: 30px;">搜索</el-button>
        <el-button type="warning" @click="reset" style="height:30px">重置</el-button>
      </div>
      <div>
        <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='取消' icon="InfoFilled" icon-color="red"
                       title="是否导出本页数据?" @confirm="exportExcel" width=180>
          <template #reference>
            <el-button type="success" size="default" style="height:30px">导出为表格</el-button>
          </template>
        </el-popconfirm>
      </div>
    </div>
    <!-- 数据展示层 -->
    <el-table v-loading="loading" :data="tableData" border stripe header-cell-class-name="headerBg"
              :cell-style="{ 'text-align': 'center', 'font-size': '16px' }" @selection-change="handleSelectionChange"
              :header-cell-style="{ 'text-align': 'center' }" :row-style="{ height: '70px' }">
      <el-table-column type="selection" width="55" fixed="left"></el-table-column>
      <el-table-column prop="id" label="订单序号" width="80">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="orderNumber" label="订单编号" width="250"></el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="180"></el-table-column>
      <el-table-column prop="userName" label="用户名" width="100"></el-table-column>
      <el-table-column label="所购买的商品" width="150">
        <el-table-column label="展开" type="expand" width="150">
          <template #default="props">
            <el-table :data="props.row.orderItemList" border
                      :cell-style="{ 'text-align': 'center', 'font-size': '14px' }">
              <el-table-column label="商品名称" prop="goodSnapshot.name" width="200" />
              <el-table-column label="商品图片" prop="goodSnapshot.goodImg" width="200">
                <template #default="scope">
                  <div>
                    <img :src=" downloadUrl + scope.row.goodSnapshot.goodImg.split(';')[0]" alt="" style="height: 50px;">
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="类别" prop="goodSnapshot.type" width="200" />
              <el-table-column label="商品单价" prop="goodSnapshot.price" width="200" />
              <el-table-column label="数量" prop="quantity" width="200" />
              <el-table-column label="总价" prop="itemTotalAmount" width="200" />
            </el-table>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="地址信息" width="180">
        <el-table-column prop="addressSnapshot.name" label="收货人" />
        <el-table-column prop="addressSnapshot.phone" label="手机号" width="180" />
        <el-table-column prop="addressSnapshot.region" label="地区" width="180" />
        <el-table-column prop="addressSnapshot.detailAddress" label="详细地址" width="180" />
      </el-table-column>
      <el-table-column prop="postage" label="快递费用"></el-table-column>
      <el-table-column prop="totalAmount" label="订单实付金额">

      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态"></el-table-column>
      <el-table-column prop="trackingNumber" label="快递单号"></el-table-column>
      <el-table-column label="操作" width="220px" fixed="right">
        <template #default="scope">
          <el-button v-if="['待支付'].includes(scope.row.orderStatus)" size="small" @click="cancelOrder(scope.row)" type="warning" plain>
            取消订单
          </el-button>
          <el-button size="small" @click="showDetail(scope.$index, scope.row)">
            详情
          </el-button>
          <el-button v-if="['待发货'].includes(scope.row.orderStatus)" size="small"
                     @click="openShipmentDialog(scope.row.id)">
            发货
          </el-button>
          <el-popconfirm confirm-button-text='是' cancel-button-text='否' icon="InfoFilled" icon-color="red"
                         title="订单是否完成？" @confirm="orderTransaction(scope.row.id,'交易成功')" width=180>
            <template #reference>
              <el-button v-if="['待收货'].includes(scope.row.orderStatus)" size="small" type="success"
                         plain>交易成功</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="InfoFilled" icon-color="red"
                         title="确定要退款吗？" @confirm="deleteOrder(scope.row)" width=180>
            <template #reference>
              <el-button v-if="['待发货','待收货'].includes(scope.row.orderStatus)" size="small" type="danger"
                         plain>退款</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页器 -->
  <div style="padding: 10px 0">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="searchParams.current" :page-size="searchParams.pageSize" :page-sizes="[5, 10, 15, 20]"
                   :small="null" :disabled="null" :background="null" layout="total, sizes, prev, pager, next, jumper"
                   :total="total" />
  </div>
  <!--  弹窗-->
  <el-dialog title="订单详情信息" v-model="DialogVisible" width="60%">
    <el-form label-width="100px" size="default" :model="editForm" :disabled="disabled">
      <div style="display: flex">
        <el-form-item label="订单编号" style="width: 400px">
          <el-input v-model="editForm.orderNumber" autocomplete="off"></el-input>
        </el-form-item>
      </div>

      <div style="display: flex">
        <el-form-item label="收货人姓名" style="width: 300px">
          <el-input v-model="editForm.addressSnapshot.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="手机号" style="width: 300px">
          <el-input v-model="editForm.addressSnapshot.phone" autocomplete="off"></el-input>
        </el-form-item>
      </div>

      <div style="display: flex">
        <el-form-item label="收货地址" style="width: 300px">
          <el-input v-model="editForm.addressSnapshot.region" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input v-model="editForm.addressSnapshot.detailAddress" autocomplete="off"></el-input>
        </el-form-item>
      </div>

      <!-- 这里的商品明细就不放图片了 -->
      <div style="display: flex"></div>
      <el-form-item label="订单状态" style="width: 250px">
        <el-input v-model="editForm.orderStatus" autocomplete="off"></el-input>
      </el-form-item>

      <div style="display: flex">
        <el-form-item label="订单总金额" style="width: 250px">
          <el-input v-model="totalAmount" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="优惠价格" style="width: 250px">
          <el-input v-model="couponAmount" autocomplete="off"></el-input>
        </el-form-item>
      </div>

      <el-form-item label="订单实付金额" style="width: 250px">
        <el-input v-model="editForm.totalAmount" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="快递单号" style="width: 300px">
        <el-input v-model="editForm.trackingNumber" autocomplete="off"></el-input>
      </el-form-item>

      <div style="display: flex">
        <el-form-item label="下单时间" style="width: 300px;">
          <el-input v-model="editForm.createTime" autocomplete="off"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button style="height: 30px;" @click="DialogVisible = false">取消</el-button>
        <el-button style="height: 30px" type="primary" @click="DialogVisible = false">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!--  发货弹窗-->
  <el-dialog title="发货" v-model="shipments" width="60%">
    <el-form label-width="100px" size="default">
      <el-form-item label="快递单号" style="width: 300px;">
        <el-input v-model="shipment.trackingNumber"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button style="height: 30px;" @click=" shipments = false">取消</el-button>
        <el-button style="height: 30px" type="primary" @click="deliverGoods">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import myAxios from "@/api/myAxios";
import { ElMessage } from "element-plus";
import {SuccessInfo, ErrorInfo, WarnInfo} from "@/utils/messageInfo";
import { downloadUrl } from '@/utils/formatImgUpload'
import { entityOrderList } from "@/utils/excelUtil/entityOrderExcel";

const tableData: any = ref([]);  //表单展示数据
const total = ref(0);
const title = ref('')
const disabled = ref(true)
const editForm: any = ref({});//编辑表单
const shipment: any = ref({
  trackingNumber: null
})//物流单号
const DialogVisible = ref(false); //详情展示
const shipments = ref(false)
const orderNumber = ref('')
const searchParams: any = ref({ //封装分页 
  current: 1, //当前页码
  pageSize: 5, //每页显示条数
  sortField: "id",  //根据ID分类
  sortOrder: "descend", //降序
  orderType: "product"
})
const loading = ref(false)
onMounted(() => {
  getOrderList()  //页面加载获取订单列表
})
const handleSizeChange = (newSize: any) => {
  searchParams.value.pageSize = newSize //新的页面数
  getOrderList()
}
const handleCurrentChange = (Current: any) => {
  searchParams.value.current = Current
  getOrderList()
}
const handleSelectionChange = (row: any) => {
  // id.value = JSON.parse(JSON.stringify(row));
}
//获取订单列表
const getOrderList = async () => {
  try {
    searchParams.value.orderNumber = orderNumber.value
    const res = await myAxios.post('/order/list/page', { ...searchParams.value });
    // console.log('订单信息--->', res.data.data);
    if (res.data.code === 1) {
      tableData.value = res.data.data.records;
      total.value = parseInt(res.data.data.total)
      console.log('表单信息--->', tableData.value);
    } else {
      ElMessage({
        message: '获取数据失败',
      });
    }
  } catch (error) {
    ElMessage({
      message: '发生错误',
    });
  }
}
//查看订单详情
const totalAmount = ref(0)
const couponAmount = ref(0)
const showDetail = (index: number, row: any) => {
  title.value = "订单详情"
  DialogVisible.value = true;
  if (row.couponSnapshot !== null) {
    couponAmount.value = row.couponSnapshot.conditionAmount;
  }
  totalAmount.value = row.totalAmount + couponAmount.value;
  console.log('editForm--->', editForm.value);
  editForm.value = row;
};
//发货方法
const currentId = ref<number | null>(null);
const openShipmentDialog = (id: number) => {
  shipments.value = true;
  currentId.value = id;
}
const deliverGoods = async () => {  //发货方法
  const values = Object.values(shipment.value );
  if (values.some((value: any) => value === null || value === undefined || value === '')) {
    WarnInfo('请填写快递单号')
    return;
  }
  if (currentId.value) {
    const res = await myAxios.post('/order/update', {
      id: currentId.value,
      trackingNumber: shipment.value.trackingNumber
    })
    if (res.data.code === 1) {
      ElMessage({
        type: 'success',
        message: '发货成功'
      })
      await getOrderList();
    }
  } else {
    ElMessage.error('更新失败，请检查字段')
  }
  shipments.value = false;
}
const deleteOrder = async (row: any) => {  //微信退款
  loading.value = true
  console.log('row-->', row)
  const res = await myAxios.post('/wechat/refund/create', { id: row.id })   //传入订单号取消订单并退款
  console.log(res)
  setTimeout(async () => {
    if (res.data.code === 1) {
      SuccessInfo('退款成功')
      await orderTransaction(row.id,'已退款')
      await getOrderList()
      loading.value = false
    }
  }, 3000)
}
const reset = () => {  //重置搜索框
  orderNumber.value = '';
}

const load = (onum : any) => {    //搜索的方法
  searchParams.value.orderNumber = onum
  searchParams.value.current = 1
  getOrderList()
}
const cancelOrder = async (row: any) => {  //取消订单的方法(未支付能取消)
  // console.log('点击的这一行--->', row);
  const res = await myAxios.post('/order/cancel/id', { id: row.id })
  if (res.data.code === 1) {
    await getOrderList()
    SuccessInfo('取消订单成功')
  } else {
    ErrorInfo('请求错误')
  }
}
const orderTransaction = async (oid: any,msg: string) => {
  // console.log('当前订单信息---->',oid)
  // loading.value = true
  const res = await myAxios.post('/order/update/all/orderStatus',{
    id: oid,
    orderStatus: msg
  })
  if (res.data.code === 1) {
    SuccessInfo(msg)
    await getOrderList()
    loading.value = false
  } else {
    WarnInfo('更新失败')
    loading.value = false
  }
  loading.value = false
}

const exportExcel =()=> {
  entityOrderList(tableData.value)
}
</script>

<style scoped>
/* 使用 ::v-deep 来修改表头的对齐方式 */
.el-table__header th {
  text-align: center;
  /* 表头居中 */
  font-size: 14px;
  /* 设置字体大小 */
  font-weight: bold;
  /* 设置字体加粗 */
  font-family: 'Arial', sans-serif;
  /* 设置字体 */
}
.table_page {
  min-width: 1000px;
  overflow: auto;
}

.titleHeader {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px
}
</style>