<template>
  <el-card class="main-card">
    <template #header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>订单审核</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <el-form :model="forms" ref="forms" label-width="70px" class="search-form">
      <el-row>
        <el-form-item label="关键词" prop="keyword">
          <el-col>
            <el-input v-model="forms.keyword" prefix-icon="Search"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="" label-width="20px">
          <el-button type="primary" icon="search" @click="submit('forms')">
            搜索
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <div class="toolbar">
      <!-- <el-button type="primary" icon="plus" @click="add">
        新增
      </el-button> -->
      <!-- <el-button type="primary" plain icon="fold" @click="toggleRowExpand">
        展开
      </el-button>
      <el-button type="primary" plain icon="Expand" @click="toggleRowExpand">
        折叠
      </el-button> -->
    </div>

    <el-table class="table" ref="table" :data="tableData" row-key="id" border size="small">
      <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
      <el-table-column prop="orderNo" label="订单号" min-width="180"></el-table-column>
      <el-table-column prop="agencyName" label="旅行社名称" min-width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="travelStartDate" label="游玩日期" width="200">
        <template #default="scope">
          <div>开始日期： {{ moment(scope.row.travelStartDate).format('YYYY-MM-DD') }}</div>
          <div>结束日期： {{ getEndDay(scope.row) }}</div>
          <div>共： <el-tag size="small">{{ scope.row.travelDays }}天</el-tag></div>
        </template>
      </el-table-column>
      <el-table-column prop="touristCount" label="人数" width="80" align="center"></el-table-column>
      <el-table-column label="金额" width="120">
        <template #default="scope">
          <div>总额：¥{{ scope.row.totalAmount }}</div>
          <div>已付：¥{{ scope.row.paidAmount }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.status)">
            {{ getOrderStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="auditStatus" label="审核状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.auditStatus === 'Approved' ? 'success' :
            scope.row.auditStatus === 'Rejected' ? 'danger' : 'warning'">
            {{ scope.row.auditStatus === 'Approved' ? '已通过' :
              scope.row.auditStatus === 'Rejected' ? '已驳回' : '待审核' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="paymentStatus" label="支付状态" width="100">
        <template #default="scope">
          <el-tag :type="getPaymentStatusType(scope.row.paymentStatus)">
            {{ getPaymentStatusText(scope.row.paymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="progress" label="进度" width="180">
        <template #default="scope">
          <el-progress :percentage="scope.row.progress"></el-progress>
        </template>
      </el-table-column> -->

      <el-table-column fixed="right" label="操作" width="320">
        <template #default="scope">
          <!-- <el-button type="primary" link size="small" @click="edit(scope.row)">编辑</el-button> -->
          <el-button type="success" link size="small" @click="audit(scope.row)">
            {{ scope.row.status === 'Cancelling' ? '退费' : '订单' }}审核
          </el-button>
          <el-button type="info" link size="small" @click="view(scope.row)">详情</el-button>
          <!-- <el-button type="warning" link size="small" @click="payment(scope.row)">付款</el-button>
          <el-button type="info" link size="small" @click="editSchedule(scope.row)">行程</el-button>
          <el-button type="primary" link size="small" @click="editTourists(scope.row)">游客</el-button>
          <el-button type="danger" link size="small" @click="del(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="pagination" background layout="total, sizes, prev, pager, next"
      :page-sizes="[10, 20, 50, 100]" :page-size="forms.rows" :total="total" @size-change="sizeHandler"
      @current-change="pageHandler">
    </el-pagination>

    <el-dialog title="订单审核" width="800px" destroy-on-close v-model="formDialogVisible" @close="close">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px" class="audit-form">
        <el-form-item label="审核结果" prop="isApproved">
          <el-radio-group v-model="formData.isApproved">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitReviewOrder">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <order-detail-dialog ref="orderDetailDialog" :orderId="currentOrderId"></order-detail-dialog>
  </el-card>
</template>
<script>
import request from '@/utils/request'
import { getOrders, reviewOrder, getOrderRefundInfo, reviewRefundOrder } from '@/api/order';
import { cloneDeep, groupBy } from 'lodash-es';
import moment from 'moment/moment';
import { ProductTypes } from '@/constant';
import utils from '@/utils/util';
import { getOrderStatusText, getOrderStatusType, getPaymentStatusText, getPaymentStatusType } from '@/utils/order';
import OrderDetailDialog from './detial.vue';

export default {
  name: "OrderReview",
  components: {
    OrderDetailDialog
  },
  data() {
    return {
      forms: {
        keyword: "",
        columns: [
          { label: "订单号", prop: "orderNo" },
          { label: "旅行社名称", prop: "agencyName" },
          { label: "游玩日期", prop: "travelStartDate" },
          { label: "游玩日期", prop: "travelEndDate" },
          { label: "游玩天数", prop: "travelDays" },
          { label: "人数", prop: "touristCount" },
          { label: "金额", prop: "totalAmount" },
          { label: "金额", prop: "paidAmount" },
          { label: "订单状态", prop: "status" },
          { label: "审核状态", prop: "auditStatus" },
          { label: "支付状态", prop: "paymentStatus" },
          { label: "进度", prop: "progress" },
        ],
        sorters: [
          {
            name: 'createDate',
            asc: false,
          }
        ],
        filters: [
          {
            name: "paymentStatus",
            operate: 0, // 0 等于; 1 不等于; 2 like; 3 not like
            value: 'Paid',
          },
          {
            name: "status",
            operate: 1, // 0 等于; 1 不等于; 2 like; 3 not like
            value: 'Cancelled',
          },
          {
            name: "auditStatus",
            operate: 0, // 0 等于; 1 不等于; 2 like; 3 not like
            value: 'Pending',
          }
        ],
        page: 1,
        rows: 10,
      },
      expand: false, //默认展开所有节点
      tableData: [],
      total: 0,
      formDialogVisible: false,
      formData: {
        id: '',
        status: '',
        isApproved: true,
        remark: '',
      },
      isAdd: true,
      formLabelWidth: "120px",
      activeTab: ['basic', 'details', 'tourists'],
      currUseDate: '',
      useDateList: [],
      categoryOptions: [],
      agencyOptions: [],
      formRules: {
        isApproved: [
          { required: true, message: "请选择审核结果", trigger: "change" }
        ],
        remark: [
          { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
        ]
      },
    };
  },
  methods: {
    moment,
    getEndDay(row) {
      if (!row.travelStartDate || !row.travelDays) return '-';
      return moment(row.travelStartDate).add(row.travelDays - 1, 'days').format('YYYY-MM-DD');
    },
    sizeHandler(val) {
      this.forms.rows = val;
      this.getOrderList();
    },
    pageHandler(val) {
      this.forms.page = val;
      this.getOrderList();
    },
    audit(row) {
      this.formData.id = row.id;
      this.formData.status = row.status;
      this.formDialogVisible = true;
    },
    view(row) {
      if (!row.id) return;
      this.$refs.orderDetailDialog.open(row.id);
    },
    close() {
      this.$refs.formRef.resetFields();
      this.formData = {
        id: '',
        status: '',
        isApproved: true,
        remark: '',
      };
    },
    getOrderList() {
      getOrders(this.forms || {}).then((res) => {
        this.tableData = res.data?.data || []
        this.total = res.data?.records || 0
      });
    },
    submitReviewOrder() {
      this.$refs.formRef.validate((valid) => {
        const { id, isApproved, remark, status } = this.formData;
        if (!valid || !id) return;
        if (status === 'Cancelling') {
          this.reviewCancelOrder(id, isApproved, remark);
        } else {
          this.reviewNormalOrder(id, isApproved, remark);
        }
      });
    },
    reviewCancelOrder(orderId, isApproved, remark) {
      getOrderRefundInfo(orderId).then((res) => {
        const refundInfo = res.data || {};
        const refundId = refundInfo.refundList?.[0]?.id || '';
        if (!refundId) {
          this.$message.error('未找到退款信息，无法审核取消订单');
          return;
        }
        reviewRefundOrder(refundId, isApproved, remark).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "审核成功",
            });
            this.formDialogVisible = false;

            this.getOrderList();
          }
        });
      });
    },
    reviewNormalOrder(orderId, isApproved, remark) {
      reviewOrder(orderId, isApproved, remark).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "审核成功",
          });
          this.formDialogVisible = false;

          this.getOrderList();
        }
      });
    },
    toggleRowExpand() {
      let that = this;
      this.tableData.forEach(function (row) {
        that.$refs.table.toggleRowExpansion(row);
      });
    },

    del(row) {
      this.$confirm("此操作将删除选择数据, 是否继续?", "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning", })
        .then(() => {
          delOrder(row.id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getOrderList();
            }
          });
        })
        .catch(() => {
        });
    },
    getOrderStatusType,
    getOrderStatusText,
    getPaymentStatusType,
    getPaymentStatusText,
  },
  created() {
    this.getOrderList();
  },
};
</script>