<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!-- 查询表单 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="团购名称">
            <el-input v-model="queryParams.name" placeholder="请输入团购名称" clearable style="width: 240px" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="queryParams.user_name" placeholder="请输入用户名" clearable style="width: 240px" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="queryParams.status" placeholder="订单状态" clearable style="width: 240px" filterable>
              <el-option label="待付款" :value="0"/>
              <el-option label="待收货" :value="1"/>
              <el-option label="已完成" :value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item label="订单号">
            <el-input v-model="queryParams.order_id" placeholder="请输入订单号" clearable style="width: 240px" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="物流单号">
            <el-input v-model="queryParams.tracking_number" placeholder="请输入物流单号" clearable style="width: 240px" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="下单时间" style="width: 308px;">
            <el-date-picker v-model="dateRange" type="daterange" value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </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-table v-loading="loading" :data="userList" style="width: 100%">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column type="index" label="序号" width="60" align="center" :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"/>
          <el-table-column label="用户名称" align="center" prop="username" width="150"/>
          <el-table-column label="团购名称" align="center" prop="tuangoumingcheng" width="230"/>
          <el-table-column label="规格" align="center" prop="spec" width="150"/>
          <el-table-column label="下单数量" align="center" prop="xiadanshuliang" width="150"/>
          <el-table-column label="订单状态" align="center" width="150">
            <template #default="scope">
              <span>
                {{ scope.row.dingdanzhuangtai === 0 ? '待付款' : scope.row.dingdanzhuangtai === 1 ? '待收货' : scope.row.dingdanzhuangtai === 2 ? '已完成' : '已取消' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="收货方式" align="center" width="150">
            <template #default="scope">
              <span>{{ scope.row.shouhuofangshi === 0 ? '邮寄' : scope.row.shouhuofangshi === 1 ? '自提' : '未知方式' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单号" align="center" prop="dingdanhao" width="150"/>
          <el-table-column label="物流单号" align="center" prop="wuliudanhao" width="260"/>
          <el-table-column label="修改前地址" align="center" prop="addressBefore" width="260"/>
          <el-table-column label="修改后地址" align="center" prop="addressAfter" width="260"/>
          <el-table-column label="修改前手机号" align="center" prop="phoneBefore" width="150"/>
          <el-table-column label="修改后手机号" align="center" prop="phoneAfter" width="150"/>
          <el-table-column label="修改前收货人" align="center" prop="shouhuorenBefore" width="150"/>
          <el-table-column label="修改后收货人" align="center" prop="shouhuorenAfter" width="150"/>
          <el-table-column label="下单时间" align="center" prop="createdAt" width="160">
            <template #default="scope">
              <span>{{ moment(scope.row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="150">
            <template #default="scope">
              <el-tooltip content="填写物流单号" placement="top">
                <el-button link type="primary" icon="Van" @click="handleUpdates(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></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-col>
    </el-row>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" ref="userRef" label-width="80px">
        <!-- 编辑用户 -->
        <el-row v-if="title !== '填写物流单号'">
          <el-col :span="24">
            <el-form-item label="修改后姓名" label-width="120px">
              <el-input v-model="form.update_name" placeholder="请输入联系人" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="修改后手机号" label-width="120px">
              <el-input v-model="form.update_phone" placeholder="请输入手机号" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="修改后地址" label-width="120px">
              <el-input v-model="form.updat_adress" type="textarea" placeholder="请输入修改后地址"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 填写物流单号 -->
        <el-row v-if="title === '填写物流单号'">
          <el-col :span="24">
            <el-form-item label="物流单号">
              <el-input v-model="form.tracking_number" placeholder="请输入物流单号" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { callCloudFunction } from "@/api/cloud";
import moment from "moment";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    user_name: null,
    status: null,
    order_id: null,
    tracking_number: null,
    startTime: null,
    endTime: null,
  },
});

const { queryParams, form } = toRefs(data);

/** 查询用户列表 */
async function getList() {
  loading.value = true;

  if (Array.isArray(dateRange.value) && dateRange.value.length === 2) {
    queryParams.value.startTime = new Date(dateRange.value[0]).getTime();
    queryParams.value.endTime = new Date(dateRange.value[1]).getTime();
  } else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }

  const params = {};
  for (const [key, value] of Object.entries(queryParams.value)) {
    if (value !== null && value !== "" && value !== undefined) {
      params[key] = value;
    }
  }

  try {
    const res = await callCloudFunction("database", {
      page: "dingdanguanli",
      action: "findOrderPage",
      data: params,
    });
    userList.value = res.records;
    total.value = res.total;
  } catch (error) {
    console.error("查询失败", error);
  } finally {
    loading.value = false;
  }
}

/** 搜索 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置查询 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value.name = "";
  queryParams.value.user_name = "";
  queryParams.value.status = "";
  queryParams.value.order_id = "";
  queryParams.value.tracking_number = "";
  queryParams.value.startTime = undefined;
  queryParams.value.endTime = undefined;
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  getList();
}

/** 重置表单 */
function reset() {
  form.value = {};
  proxy.resetForm("userRef");
}

/** 修改用户 */
function handleUpdate(row) {
  reset();
  form.value._id = row._id;
  form.value.update_name = row.shouhuorenAfter;
  form.value.update_phone = row.phoneAfter;
  form.value.updat_adress = row.addressAfter;
  open.value = true;
  title.value = "修改用户";
}

/** 填写物流单号 */
function handleUpdates(row) {
  reset();
  form.value._id = row._id;
  form.value.tracking_number = row.wuliudanhao;
  open.value = true;
  title.value = "填写物流单号";
}

/** 删除用户 */
async function handleDelete(row) {
  const userIds = row._id;
  try {
    await proxy.$modal.confirm(`是否确认删除用户编号为"${userIds}"的数据项？`);
    await callCloudFunction("database", {
      page: "dingdanguanli",
      action: "deleteOrder",
      data: { _id: userIds },
    });
    getList();
    proxy.$modal.msgSuccess("删除成功");
  } catch (err) {
    // 用户取消或接口报错都不会影响页面
  }
}

/** 过滤空字段 */
function filterFormData(obj) {
  const res = {};
  for (const [key, value] of Object.entries(obj)) {
    if (value !== null && value !== undefined && value !== "") {
      res[key] = value;
    }
  }
  return res;
}

/** 提交表单 */
async function submitForm() {
  try {
    await proxy.$refs["userRef"].validate();
    if (title.value === "填写物流单号") {
      await callCloudFunction("database", {
        page: "dingdanguanli",
        action: "updateOrder",
        data: {
          _id: form.value._id,
          tracking_number: form.value.tracking_number,
        },
      });
    } else {
      const filteredData = filterFormData(form.value);
      await callCloudFunction("database", {
        page: "dingdanguanli",
        action: "updateOrder",
        data: filteredData,
      });
    }
    open.value = false;
    getList();
  } catch (err) {
    console.log("表单验证失败或接口报错", err);
  }
}

/** 取消 */
function cancel() {
  open.value = false;
  reset();
}

getList();
</script>

<style scoped lang="scss">
</style>
