<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.username"
                     placeholder="请输入用户名"
                     clearable
                     style="width: 240px"
                     @keyup.enter="handleQuery"
                  />
               </el-form-item>
               <el-form-item label="手机号码">
                  <el-input
                     v-model="queryParams.phone"
                     placeholder="请输入手机号码"
                     clearable
                     style="width: 240px"
                     @keyup.enter="handleQuery"
                  />
               </el-form-item>
               <el-form-item label="园所">
                  <el-select
                     v-model="queryParams.school_id"
                     placeholder="请选择园所"
                     clearable
                     filterable
                     remote
                     style="width: 240px"
                  >
                     <el-option
                        v-for="school in schoolList"
                        :key="school._id"
                        :label="school.name"
                        :value="school._id"
                     />
                  </el-select>
               </el-form-item>
               <el-form-item label="售后状态">
                  <el-select
                     v-model="queryParams.state"
                     placeholder="售后状态"
                     clearable
                     style="width: 240px"
                  >
                     <el-option
                        label="待处理"
                        value="待处理"
                     />
                     <el-option
                        label="处理中"
                        value="处理中"
                     />
                     <el-option
                        label="已处理"
                        value="已处理"
                     />
                  </el-select>
               </el-form-item>
               <el-form-item label="创建时间" style="width: 308px;">
                  <el-date-picker
                     v-model="dateRange"
                     value-format="YYYY-MM-DD"
                     type="daterange"
                     range-separator="-"
                     start-placeholder="开始日期"
                     end-placeholder="结束日期"
                  ></el-date-picker>
               </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>

            <!-- @selection-change="handleSelectionChange" -->
            <el-table v-loading="loading" :data="userList" >
               <!-- <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" key="username" prop="username" />
               <el-table-column label="手机号码" align="center" key="phone" prop="phone" />
               <el-table-column label="园所" align="center" key="schoolName" prop="schoolName" />
               <el-table-column label="订单号" align="center" key="orderId" prop="orderId"  />
               <el-table-column label="描述" align="center" key="description" prop="description" />
               <el-table-column
               label="售后状态"
               align="center"
               :formatter="
                  (row) => ['待处理', '处理中', '已处理'][row.state]
               "
               />
               <el-table-column label="创建时间" align="center" key="createdAt" prop="createdAt" >
                  <template #default="scope">
                    <span>{{ moment(scope.row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}</span>
                  </template>
               </el-table-column>
               <!-- <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-tooltip content="查看详情" placement="top">
                        <el-button link type="primary" icon="Postcard" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']"></el-button>
                     </el-tooltip>
                  </template>
               </el-table-column> -->
               <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <!-- 查看详情 -->
                     <el-button link type="primary" @click="handleDelete(scope.row)"> 查看详情 </el-button>

                     <!-- 修改售后状态 -->
                     <el-dropdown 
                        trigger="click" 
                        @command="(val) => handleUpdateState(scope.row, val)"
                        v-if="scope.row.showDropdown !== false" 
                        style="margin-top: 2px;"
                     >
                        <el-button link type="primary"> 修改状态 <i class="el-icon-arrow-down el-icon--right"></i> </el-button>
                        <template #dropdown>
                        <el-dropdown-menu>
                           <el-dropdown-item :command="0">待处理</el-dropdown-item>
                           <el-dropdown-item :command="1">处理中</el-dropdown-item>
                           <el-dropdown-item :command="2">已处理</el-dropdown-item>
                        </el-dropdown-menu>
                        </template>
                     </el-dropdown>
                  </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="售后详情" v-model="detailDialogVisible" width="700px">
   <el-descriptions :column="1" border>
      <el-descriptions-item label="用户名">{{ detailData.username }}</el-descriptions-item>
      <el-descriptions-item label="手机号码">{{ detailData.phone }}</el-descriptions-item>
      <el-descriptions-item label="园所">{{ detailData.schoolName }}</el-descriptions-item>
      <el-descriptions-item label="订单号">{{ detailData.orderId }}</el-descriptions-item>
      <el-descriptions-item label="描述">{{ detailData.description }}</el-descriptions-item>
      <el-descriptions-item label="售后状态">
         {{ ['待处理', '处理中', '已处理'][detailData.state] }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ detailData.createdAt ? moment(detailData.createdAt).format("YYYY-MM-DD HH:mm:ss") : "" }}</el-descriptions-item>
   </el-descriptions>
   <!-- 图片展示 -->
   <div v-if="detailData.url && detailData.url.length" style="margin-top: 20px;">
      <el-carousel height="200px" trigger="click">
         <el-carousel-item v-for="(img, index) in detailData.url" :key="index">
         <el-image :src="img" style="width: 100%; height: 200px;" fit="contain" />
         </el-carousel-item>
      </el-carousel>
   </div>

   <template #footer>
      <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
   </template>
   </el-dialog>
  </div>
</template>

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

import { nextTick } from 'vue';
function showDropdown(row) {
  nextTick(() => {
    row.showDropdown = true;
  });
}

const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict("sys_normal_disable", "sys_user_sex");

const userList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref([]);
const schoolList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    phone: null,
    school_id: null,
    state: null,
    startTime: null,
    endTime: null,
  },
});

const { queryParams } = toRefs(data);

async function getSchoolList() {
  try {
    const { data } = await proxy.$models.wx_school.list({
      filter: { where: {} },
      pageSize: 10000,
      pageNumber: 1,
      getCount: true,
      envType: "prod",
    });
    schoolList.value = data.records;
  } catch (error) {
    console.error("Failed to fetch school list", error);
  }
}


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

  // 只传有效的查询条件
  const params = {};
  for (const [key, value] of Object.entries(queryParams.value)) {
    if (value !== null && value !== "" && value !== undefined) {
      params[key] = value;
    }
  }

  const res = await callCloudFunction("database", {
    page: "shouhouguanli",
    action: "findAfterServicePage",
    data: params,
  });

  loading.value = false;
  console.log(res, "res");
  userList.value = res.records;
  total.value = res.total;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;

  // 处理时间范围
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startTime = new Date(dateRange.value[0]).getTime();
    queryParams.value.endTime =
      new Date(dateRange.value[1]).getTime() + 24 * 60 * 60 * 1000 - 1;
  } else {
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
  }

  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];

  // 清空 queryParams
  Object.assign(queryParams.value, {
    pageNum: 1,
    pageSize: 10,
    username: null,
    phone: null,
    school_id: null,
    state: null,
    startTime: null,
    endTime: null,
  });

  proxy.resetForm("queryRef"); // 清空表单 UI

  getList();
}

/** 修改售后状态 */
async function handleUpdateState(row, newState) {
  try {
    loading.value = true;
    console.log(row, newState, 'row');
    // 调用云函数更新状态
    const asd = await callCloudFunction("database", {
      page: "shouhouguanli",
      action: "updateAfterService",
      data: {
        _id: row._id, // 主键ID
        state: newState, // 新状态
      },
    });
    console.log(asd, 'asd');
    // 本地更新表格里的状态，避免强制刷新全表
    row.state = newState;

    proxy.$modal.msgSuccess("状态修改成功");
  } catch (error) {
    console.error("修改状态失败", error);
    proxy.$modal.msgError("修改状态失败");
  } finally {
    loading.value = false;
  }
}

const detailDialogVisible = ref(false);
const detailData = ref({
  username: "",
  phone: "",
  schoolName: "",
  orderId: "",
  description: "",
  state: 0,
  createdAt: "",
  url: [], // 图片数组
});

/** 获取临时图片链接 */
async function getTempUrls(fileIds) {
  if (!fileIds?.length) return [];
  const res = await proxy.$apps.getTempFileURL({ fileList: fileIds });
  return res.fileList.map((item) => ({
    fileID: item.fileID,
    tempFileURL: item.tempFileURL,
  }));
}

/** 查看详情 */
async function handleDelete(row) {
  console.log(row, 'row');

  // 解析字符串数组
  const urls = row.url ? JSON.parse(row.url) : [];

  // 获取临时链接
  const tempFiles = urls.length ? await getTempUrls(urls) : [];
  const tempUrls = tempFiles.map(item => item.tempFileURL);

  // 响应式赋值
  detailData.value = {
    username: row.username,
    phone: row.phone,
    schoolName: row.schoolName,
    orderId: row.orderId,
    description: row.description,
    state: row.state,
    createdAt: row.createdAt,
    url: tempUrls,
  };

  detailDialogVisible.value = true;
}

getList();
getSchoolList();
</script>

<style lang='scss' scoped>
.el-dialog__body {
  padding: 20px 30px;
}

.el-descriptions {
  font-size: 14px;
}

.el-carousel .el-carousel__item {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}
</style>