<template>
  <div style="background-color: #f0f2f5; padding-bottom: 20px; min-height: 100%; ">
    <div style="padding: 20px; background-color: #fff;">
      积分订单详情
    </div>
    <div class="contentx" v-if="item != null">
      <div class="desct"> 积分订单信息</div>
      <div class="order-status" v-if="item != null && item.status != 5">
        <el-steps :active="getStepActive(item.status)" align-center finish-status="success">
          <el-step title="待支付"></el-step>
          <el-step title="待发货"></el-step>
          <el-step title="待收货"></el-step>
          <el-step title="已完成"></el-step>
        </el-steps>
      </div>
      <el-card shadow="never" style="margin-top: 15px">
        <div class="operate-container" v-if="item != null">
          <span style="margin-left: 20px" class="color-danger">订单状态：
            <el-tag prop="status" v-for="(ite, index) in statusOptions" v-if="item.status == ite.dictValue">{{
              ite.dictLabel }}</el-tag>
          </span>
          <div class="operate-button-container" v-if="item.status == 1" v-hasPermi="['his:integralOrder:sendGoods']">
            <!-- <el-button size="mini" @click="sendVisible=true" >发货</el-button> -->
            <el-button size="mini" @click="showSend()">发货</el-button>
          </div>
          <div class="operate-button-container" v-if="item.deliverySn != null"
            v-hasPermi="['his:integralOrder:express']">
            <el-button size="mini" @click="showExpress()">查看物流</el-button>
          </div>

          <div class="operate-button-container" v-if="item.status!=-1" v-hasPermi="['his:integralOrder:edit']">
            <el-button size="mini" @click="updateOrder()">修改订单</el-button>
          </div>

          <div class="operate-button-container" v-if="item.status==2">
            <el-button size="mini" @click="handleFinishOrder">确认收货</el-button>
          </div>
          <div class="operate-button-container" v-if="item.status>1" v-hasPermi="['his:integralOrder:cancel']">
            <el-button size="mini" @click="applyRefund">申请退款</el-button>
          </div>
        </div>
        <div class="desct">
          基本信息
        </div>
        <el-descriptions title="" :column="3" border>
          <el-descriptions-item label="订单编号"><span v-if="item != null">{{ item.orderCode
              }}</span></el-descriptions-item>
          <el-descriptions-item label="会员ID"><span v-if="item != null">{{ item.userId }}</span></el-descriptions-item>
          <el-descriptions-item label="会员"><span v-if="item.nickName != null">{{ item.nickName }}({{ item.phone
              }})</span></el-descriptions-item>
          <el-descriptions-item label="用户名称"><span v-if="item != null">{{ item.userName }}</span></el-descriptions-item>
          <el-descriptions-item label="用户电话"><span v-if="item != null">{{ item.userPhone }}</span>
            <el-button icon="el-icon-search" size="mini" @click="handlePhone()" style="margin-left: 20px;" circle
              v-hasPermi="['his:integralOrder:queryPhone']"></el-button>
          </el-descriptions-item>
          <el-descriptions-item label="用户地址"><span v-if="item != null">{{ item.userAddress
              }}</span></el-descriptions-item>
          <el-descriptions-item label="支付积分"><span v-if="item != null">{{ item.integral }}</span></el-descriptions-item>
          <el-descriptions-item label="状态"><span v-if="item != null"> <dict-tag :options="statusOptions"
                :value="item.status" /></span></el-descriptions-item>
          <el-descriptions-item label="快递公司编号"><span v-if="item != null">{{ item.deliveryCode
              }}</span></el-descriptions-item>
          <el-descriptions-item label="快递名称"><span v-if="item != null">{{ item.deliveryName
              }}</span></el-descriptions-item>
          <el-descriptions-item label="快递单号"><span v-if="item != null">{{ item.deliverySn
              }}</span></el-descriptions-item>
          <!-- <el-descriptions-item label="物流状态"><span v-if="item != null">{{ item.deliveryType
              }}</span></el-descriptions-item> -->
          <el-descriptions-item label="物流状态" ><dict-tag :options="deliveryStatusOptions" :value="item.deliveryStatus"/></el-descriptions-item>

          <el-descriptions-item label="物流跟踪状态" ><span v-if="item!=null"><dict-tag :options="deliveryTypeOptions" :value="item.deliveryType"/> </span></el-descriptions-item>

          <el-descriptions-item label="发货时间"><span v-if="item != null">{{ item.deliveryTime
              }}</span></el-descriptions-item>
          <el-descriptions-item label="提交时间"><span v-if="item != null">{{ item.createTime
              }}</span></el-descriptions-item>
        </el-descriptions>
      </el-card>

    </div>
    <div class="contentx" v-if="item != null" style="padding-bottom: 70px;">
      <div class="desct">
        商品信息
      </div>
      <el-table border v-if="prod != null" :data="prod" size="small" style="margin-top: 20px">
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.imgUrl" style="height: 80px">
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.goodsName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="积分" align="center">
          <template slot-scope="scope">
            <p>￥{{ scope.row.integral }}</p>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center">
          <template slot-scope="scope">
            <p>￥{{ scope.row.cash || 0 }}</p>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 操作记录 -->
    <div class="contentx" v-if="item != null" style="padding-bottom: 70px;">
      <div class="desct">
        操作记录
      </div>
      <el-table :data="orderLogs" border style="width: 100%; margin-top: 20px;" v-loading="logsLoading">
        <!-- <el-table-column prop="changeType" label="操作类型" align="center" width="120">
        </el-table-column> -->
        <el-table-column prop="changeTime" label="操作时间" align="center" width="180">
          <template slot-scope="scope">
            {{ parseTime(scope.row.changeTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="changeMessage" label="操作备注" align="center">
        </el-table-column>
        <!-- <el-table-column prop="operator" label="操作员" align="center" width="120">
        </el-table-column> -->

      </el-table>
    </div>
    <el-dialog width="35%" title="发货" :visible.sync="sendVisible" append-to-body @close="sendCancel">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="快递名称" prop="deliveryName">
          <el-select v-model="selectedExpress" placeholder="请选择快递名称" value-key="name">
            <el-option v-for="item in expressOption" :key="item.name" :label="item.name" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司编号" prop="deliveryCode">
          <el-input v-model="form.deliveryCode" placeholder="请输入快递公司编号" disabled />

        </el-form-item>

        <el-form-item label="快递单号" prop="deliverySn">
          <el-input v-model="form.deliverySn" placeholder="请输入快递单号" />
        </el-form-item>

        <!-- 代服账号选择表格 -->
        <!-- <el-form-item label="代服账号选择" prop="selectedAccount" required>
          <div style="border: 1px solid #e6ebf5; border-radius: 4px; padding: 10px;">
            <el-table ref="accountTable" :data="tableData" highlight-current-row
              @current-change="handleAccountSelectionChange" style="width: 100%" size="small" max-height="400">

              <el-table-column type="index" width="60" label="序号" align="center"></el-table-column>
              <el-table-column prop="loginAccount" label="登录账号" align="center" width="120"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="monthlyCard" label="月结账号" align="center" width="120"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="expressProductCode" label="物流产品" align="center" width="120" show-overflow-tooltip>
                <template slot-scope="scope">
                  <dict-tag :options="expressOptions" :value="scope.row.expressProductCode" />
                </template>
              </el-table-column>
              <el-table-column prop="senderName" label="寄件人姓名" align="center" width="100"></el-table-column>
              <el-table-column prop="senderPhone" label="寄件人手机" align="center" width="120"></el-table-column>
              <el-table-column prop="senderProvince" label="寄件人省" align="center" width="100"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="senderCity" label="寄件人市" align="center" width="100"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="senderDistrict" label="寄件人区" align="center" width="100"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="senderAddress" label="寄件人地址" align="center" min-width="150"
                show-overflow-tooltip></el-table-column>

            </el-table>


            <el-pagination small layout="prev, pager, next" :total="total" :page-size="queryParams.pageSize"
              :current-page="queryParams.pageNum" @current-change="handlePageChange"
              style="margin-top: 10px; text-align: center;">
            </el-pagination>

            <div style="margin-top: 10px; color: #909399; font-size: 12px; text-align: center;">
              提示：点击表格行选择代服账号
            </div>


            <div v-if="selectedRow" style="margin-top: 10px; padding: 8px; background: #f5f7fa; border-radius: 4px;">
              <span style="color: #67C23A;">已选择：</span>
              <span>{{ selectedRow.loginAccount }} ({{ selectedRow.senderName }})</span>
            </div>
          </div>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendGoods">确 定</el-button>
        <el-button @click="sendCancel">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog :title="expressDialog.title" :visible.sync="expressDialog.open" width="600px" append-to-body>
      <div style="margin-bottom: 10px; text-align: right;">
        <el-button type="primary" size="small" @click="syncExpressInfo" :loading="syncLoading">同步物流信息</el-button>
      </div>
      <el-table style="margin-top: 20px;width: 100%" ref="orderHistoryTable" :data="traces" border v-loading="tableLoading">
        <el-table-column label="操作时间" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.AcceptTime }}
          </template>
        </el-table-column>
        <el-table-column label="位置" align="center">
          <template slot-scope="scope">
            {{ scope.row.Location }}
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template slot-scope="scope">
            {{ scope.row.AcceptStation }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="editOrder.title" :visible.sync="editOrder.open" width="600px" append-to-body>
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" clearable size="small" filterable>
            <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" :disabled="dict.dictValue==4||dict.dictValue==6||dict.dictValue==-1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="收货地址" required v-if="item.status == 1">
          <div style="margin-bottom: 10px;">
            <el-select
              v-model="selectedProvince"
              placeholder="请选择省"
              style="width: 32%; margin-right: 1%"
              @change="onProvinceChange"
              clearable
            >
              <el-option
                v-for="item in provinceOptions"
                :key="item.value"
                :label="item.label"
                :value="item"
              />
            </el-select>

            <el-select
              v-model="selectedCity"
              placeholder="请选择市"
              style="width: 32%; margin-right: 1%"
              @change="onCityChange"
              :disabled="!selectedProvince"
              clearable
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.value"
                :label="item.label"
                :value="item"
              />
            </el-select>

            <el-select
              v-model="selectedDistrict"
              placeholder="请选择区"
              style="width: 32%;"
              @change="onDistrictChange"
              :disabled="!selectedCity"
              clearable
            >
              <el-option
                v-for="item in districtOptions"
                :key="item.value"
                :label="item.label"
                :value="item"
              />
            </el-select>
          </div>

          <el-input
            v-model="detailAddress"
            placeholder="请输入详细地址（街道、门牌号等）"
            style="width: 100%"
            clearable
          />
        </el-form-item>

        <!-- 其他状态显示只读的地址信息 -->
        <el-form-item label="收货地址" v-else>
          <el-input
            v-model="editForm.userAddress"
            placeholder="请输入"
            disabled
          />
        </el-form-item>

        <!-- 修改：快递信息改为下拉选择 -->
        <el-form-item label="快递名称" prop="deliveryName">
          <el-select v-model="editSelectedExpress" placeholder="请选择快递名称" value-key="name" clearable>
            <el-option v-for="item in expressOption" :key="item.name" :label="item.name" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司编号" prop="deliveryCode">
          <el-input v-model="editForm.deliveryCode" placeholder="快递公司编号" disabled />
        </el-form-item>
        <el-form-item label="快递单号" prop="deliverySn">
          <el-input v-model="editForm.deliverySn" placeholder="请输入快递单号" />
        </el-form-item>

        <!-- 代服账号选择表格 - 使用同一个数据源 -->
        <!-- <el-form-item label="代服账号" prop="loginAccount">
          <div style="border: 1px solid #e6ebf5; border-radius: 4px; padding: 10px;">
            <el-table ref="editAccountTable" :data="tableData" highlight-current-row
              @current-change="handleEditAccountSelectionChange" style="width: 100%" size="small" max-height="300">

              <el-table-column type="index" width="60" label="序号" align="center"></el-table-column>
              <el-table-column prop="loginAccount" label="登录账号" align="center" width="120"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="monthlyCard" label="月结账号" align="center" width="120"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="expressProductCode" label="物流产品" align="center" width="120" show-overflow-tooltip>
                <template slot-scope="scope">
                  <dict-tag :options="expressOptions" :value="scope.row.expressProductCode" />
                </template>
              </el-table-column>
              <el-table-column prop="senderName" label="寄件人姓名" align="center" width="100"></el-table-column>
              <el-table-column prop="senderPhone" label="寄件人手机" align="center" width="120"></el-table-column>
              <el-table-column prop="senderProvince" label="寄件人省" align="center" width="100"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="senderCity" label="寄件人市" align="center" width="100"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="senderDistrict" label="寄件人区" align="center" width="100"
                show-overflow-tooltip></el-table-column>
              <el-table-column prop="senderAddress" label="寄件人地址" align="center" min-width="150"
                show-overflow-tooltip></el-table-column>

            </el-table>

            <el-pagination small layout="prev, pager, next" :total="total" :page-size="queryParams.pageSize"
              :current-page="queryParams.pageNum" @current-change="handlePageChange"
              style="margin-top: 10px; text-align: center;">
            </el-pagination>

            <div style="margin-top: 10px; color: #909399; font-size: 12px; text-align: center;">
              提示：点击表格行选择代服账号
            </div>

            <div v-if="editSelectedRow"
              style="margin-top: 10px; padding: 8px; background: #f5f7fa; border-radius: 4px;">
              <span style="color: #67C23A;">已选择：</span>
              <span>{{ editSelectedRow.loginAccount }} ({{ editSelectedRow.senderName }})</span>
            </div>
          </div>
        </el-form-item> -->

        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getExpress,mandatoryRefunds,getCitys,finishOrder, listIntegralOrder, sendgoods, getIntegralOrder, delIntegralOrder, addIntegralOrder, updateIntegralOrder, exportIntegralOrder, getOrderUserPhone, getOrderLogs } from "@/api/his/integralOrder";
import { getExpressList } from "@/api/his/express";
import { listAccount } from "@/api/his/dfAccount";
export default {
  name: "integralOrder",
  data() {
    return {
      deliveryStatusOptions:[],
      selectedExpress: null,
      expressOption: [],
      expressDialog: {
        title: "物流信息",
        open: false,
      },
      editOrder: {
        title: "修改订单",
        open: false,
      },
      editForm: {
        orderId: null,
        status: null,
        userAddress: null, // 这个字段将存储拼接后的完整地址
        remark: "",
        loginAccount: null,
        // 新增快递相关字段
        deliveryName: null,
        deliveryCode: null,
        deliverySn: null
      },
      editRules: {
        deliveryName: [
          { required: false, message: '请输入快递名称', trigger: 'blur' }
        ],
        deliveryCode: [
          { required: false, message: '请输入快递公司编号', trigger: 'blur' }
        ],
        deliverySn: [
          { required: false, message: '请输入快递单号', trigger: 'blur' }
        ]
      },
      item: null,
      express: null,
      traces: [],
      rules: {
        deliveryCode: [
          { required: true, message: '请输入快递公司编号', trigger: 'blur' }
        ],
        deliveryName: [
          { required: true, message: '请输入快递名称', trigger: 'blur' }
        ],
        deliverySn: [
          { required: true, message: '请输入快递单号', trigger: 'blur' }
        ],
        selectedAccount: [  // 添加这一项
          { required: true, message: '请选择代服账号', trigger: 'change' }
        ]
      },
      sendVisible: false,
      form: {
        deliveryCode: null,
        deliveryName: null,
        deliverySn: null,
        orderId: null,
        loginAccount: null  // 在 form 中也添加这个字段
      },
      tableData: [], // 清空模拟数据，改为空数组
      selectedRow: null,
      editSelectedRow: null, // 修改订单弹窗选中的行
      queryParams: { // 查询参数
        pageNum: 1,
        pageSize: 10
      },
      total: 0, // 总条数,
      expressOptions: [], // 物流产品字典
      editSelectedExpress: null,
      // 地址选择相关数据
      provinceOptions: [], // 省列表
      cityOptions: [], // 市列表
      districtOptions: [], // 区列表
      selectedProvince: null, // 选中的省
      selectedCity: null, // 选中的市
      selectedDistrict: null, // 选中的区
      detailAddress: '', // 详细地址
      deliveryTypeOptions:[],
      // 操作记录相关数据
      orderLogs: [], // 订单操作记录
      logsLoading: false, // 操作记录加载状态
      syncLoading: false, // 同步物流信息按钮加载状态
      tableLoading: false // 物流信息表格加载状态
    }
  },
  created() {
    this.getDicts("sys_integral_order_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("df_account_express").then(response => {
      this.expressOptions = response.data;
    });
    this.getDicts("sys_store_order_delivery_status").then(response => {
          this.deliveryStatusOptions = response.data;
    });
    this.getDicts("sys_delivery_type").then(response => {
              this.deliveryTypeOptions = response.data;
            });
  },
  watch: {
    selectedExpress(newVal) {
      console.log('选中的快递:', newVal); // 调试用
      if (newVal && newVal.name && newVal.code) {
        this.form.deliveryName = newVal.name;
        this.form.deliveryCode = newVal.code;
      } else {
        this.form.deliveryName = '';
        this.form.deliveryCode = '';
      }
    },
    // 新增：修改订单弹窗的快递选择监听
    editSelectedExpress(newVal) {
      console.log('修改订单弹窗选中的快递:', newVal);
      if (newVal && newVal.name && newVal.code) {
        this.editForm.deliveryName = newVal.name;
        this.editForm.deliveryCode = newVal.code;
      } else {
        this.editForm.deliveryName = '';
        this.editForm.deliveryCode = '';
      }
    },
    'editOrder.open': function (newVal) {
      if (!newVal) {
        // 修改订单弹窗关闭时清理选择状态
        this.editSelectedRow = null;
        if (this.$refs.editAccountTable) {
          this.$refs.editAccountTable.setCurrentRow();
        }
      }
    },
    'expressDialog.open': function (newVal) {
      if (!newVal) {
        // 查看物流弹窗关闭时清理数据
        this.express = null;
        this.traces = [];
      }
    },
  },
  methods: {
    getStepActive(status) {
      const statusMap = {
        4: 1, // 待支付 -> 激活第1步（显示到待支付）
        1: 2, // 待发货 -> 激活第2步（显示到待发货）
        2: 3, // 待收货 -> 激活第3步（显示到待收货）
        3: 4  // 已完成 -> 激活第4步（全部完成）
      };
      return statusMap[status] || 0;
    },
    handlePhone() {
      const orderId = this.item.orderId;
      getOrderUserPhone(orderId).then(response => {
        this.item.userPhone = response.userPhone;
      })
    },
    async updateOrder() {
      this.editOrder.open = true;
      this.editForm.orderId = this.item.orderId;
      this.editForm.remark = this.item.remark;
      this.editForm.status = this.item.status.toString();
      this.editForm.userAddress = this.item.userAddress.toString();
      this.editForm.loginAccount = this.item.loginAccount;

      // 设置快递字段的初始值
      this.editForm.deliveryName = this.item.deliveryName;
      this.editForm.deliveryCode = this.item.deliveryCode;
      this.editForm.deliverySn = this.item.deliverySn;

      // 重置选择状态
      this.editSelectedRow = null;
      this.editSelectedExpress = null;

      try {
        // 1. 先确保快递选项数据已加载
        if (this.expressOption.length === 0) {
          await getExpressList().then(response => {
            this.expressOption = response.data;
          });
        }

        // 2. 设置选中的快递（在快递数据加载完成后）
        if (this.item.deliveryName && this.expressOption.length > 0) {
          const currentExpress = this.expressOption.find(item =>
            item.name === this.item.deliveryName
          );
          if (currentExpress) {
            this.editSelectedExpress = currentExpress;
          }
        }

        // 3. 初始化地址选择器（只在待发货状态时执行）
        if (this.item.status == 1) {
          await this.initAddressSelector();
        }

        // 4. 等待代服账号数据加载完成
        await this.getAccountList();

        // 5. 在数据都加载完成后尝试选中对应的行
        if (this.item.loginAccount) {
          this.$nextTick(() => {
            this.selectCurrentAccount();
          });
        }
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    },
    // 初始化地址选择器
    async initAddressSelector() {
      // 重置地址选择器
      this.provinceOptions = [];
      this.cityOptions = [];
      this.districtOptions = [];
      this.selectedProvince = null;
      this.selectedCity = null;
      this.selectedDistrict = null;
      this.detailAddress = '';

      // 只有在待发货状态时才初始化地址选择器
      if (this.item.status == 1) {
        // 获取省份数据
        try {
          const response = await getCitys(); // 假设getCitys是您导入的方法
          this.provinceOptions = response.data || [];

          // 如果现有地址不为空，尝试解析并设置初始值
          if (this.item.userAddress) {
            this.parseExistingAddress(this.item.userAddress);
          }
        } catch (error) {
          console.error('获取地址数据失败:', error);
        }
      }
    },

    // 解析现有地址
    parseExistingAddress(address) {
      if (!address || this.item.status != 1) return;

      // 假设地址格式为 "省 市 区 详细地址"
      const parts = address.split(' ');
      if (parts.length >= 4) {
        const provinceName = parts[0];
        const cityName = parts[1];
        const districtName = parts[2];
        this.detailAddress = parts.slice(3).join(' '); // 剩余部分作为详细地址

        // 设置省份
        const province = this.provinceOptions.find(p => p.label === provinceName);
        if (province) {
          this.selectedProvince = province;
          this.onProvinceChange(province);

          // 设置城市
          const city = province.children?.find(c => c.label === cityName);
          if (city) {
            this.selectedCity = city;
            this.onCityChange(city);

            // 设置区域
            const district = city.children?.find(d => d.label === districtName);
            if (district) {
              this.selectedDistrict = district;
            }
          }
        }
      } else {
        // 如果格式不匹配，将整个地址作为详细地址
        this.detailAddress = address;
      }
    },
    // 省份选择变化
    onProvinceChange(province) {
      this.selectedCity = null;
      this.selectedDistrict = null;
      this.cityOptions = province?.children || [];
      this.districtOptions = [];
    },

    // 城市选择变化
    onCityChange(city) {
      this.selectedDistrict = null;
      this.districtOptions = city?.children || [];
    },

    // 区域选择变化
    onDistrictChange(district) {
      // 可以在这里处理区域选择后的逻辑
    },
    // 选中当前账号（修改订单弹窗使用）
    selectCurrentAccount() {
      if (!this.item.loginAccount || !this.tableData || this.tableData.length === 0) {
        console.log('无法选中账号：数据未就绪');
        return;
      }

      const currentAccount = this.tableData.find(item =>
        item.loginAccount === this.item.loginAccount
      );

      if (currentAccount) {
        this.editSelectedRow = currentAccount;
        this.$nextTick(() => {
          if (this.$refs.editAccountTable) {
            this.$refs.editAccountTable.setCurrentRow(currentAccount);
            console.log('成功选中代服账号:', currentAccount.loginAccount);
          }
        });
      } else {
        console.log('未找到对应的代服账号:', this.item.loginAccount);
      }
    },
    //修改订单状态
    submitEditForm() {
      // 只有在待发货状态（status=1）时才更新地址
      if (this.item.status == 1) {
        // 拼接完整地址
        const province = this.selectedProvince ? this.selectedProvince.label : '';
        const city = this.selectedCity ? this.selectedCity.label : '';
        const district = this.selectedDistrict ? this.selectedDistrict.label : '';
        const detail = this.detailAddress || '';

        // 使用空格拼接四个字段
        this.editForm.userAddress = `${province} ${city} ${district} ${detail}`.trim();
      } else {
        // 其他状态保持原地址不变
        this.editForm.userAddress = this.item.userAddress;
      }

      this.$refs["editForm"].validate(valid => {
        if (valid) {
          updateIntegralOrder(this.editForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("操作成功");
              this.editOrder.open = false;
              this.getDetails(this.item.orderId);
            }
          });
        }
      });
    },
    sendCancel() {
      this.sendVisible = false;
      this.form = {
        deliveryCode: null,
        deliveryName: null,
        deliverySn: null,
        orderId: null,
        loginAccount: null
      };
      this.selectedExpress = null;
      this.selectedRow = null;
      if (this.$refs.accountTable) {
        this.$refs.accountTable.setCurrentRow();
      }
    },
    showSend() {
      // 重置表单和选择状态
      this.form = {
        deliveryCode: null,
        deliveryName: null,
        deliverySn: null,
        orderId: null,
        loginAccount: null
      };
      this.selectedExpress = null;
      this.selectedRow = null;

      // 获取快递公司信息
      getExpressList().then(response => {
        this.expressOption = response.data;
      });

      // 获取代服账号列表
      this.getAccountList();

      this.sendVisible = true;
    },
    showExpress() {
      this.expressDialog.open = true;
      this.loadExpressInfo();
    },
    // 加载物流信息
    loadExpressInfo() {
      this.tableLoading = true;
      getExpress(this.item.orderId).then(response => {
        this.express = response.data;
        if (this.express != null && this.express.Traces != null) {
          this.traces = this.express.Traces
        } else {
          this.traces = [];
        }
        this.tableLoading = false;
      }).catch(error => {
        this.traces = [];
        this.tableLoading = false;
        console.error('获取物流信息失败:', error);
      });
    },
    // 同步物流信息
    syncExpressInfo() {
      this.syncLoading = true;
      this.loadExpressInfo();
      this.syncLoading = false;
    },
    sendGoods() {
      // 手动验证所有必填字段
      // if (!this.selectedRow) {
      //   this.msgError('请选择代服账号');
      //   return;
      // }

      if (!this.form.deliveryName || !this.form.deliveryCode) {
        this.msgError('请选择快递公司');
        return;
      }

      if (!this.form.deliverySn) {
        this.msgError('请输入快递单号');
        return;
      }

      // 所有验证通过，直接发送
      this.form.orderId = this.item.orderId;
      sendgoods(this.form).then(response => {
        this.msgSuccess("发货成功");
        this.sendVisible = false;
        getIntegralOrder(this.item.orderId).then(response => {
          this.item = response.data;
          this.$parent.$parent.getList();
        });

        this.form = {
          deliveryCode: null,
          deliveryName: null,
          deliverySn: null,
          orderId: null,
          loginAccount: null
        };
        this.selectedRow = null;
      });
    },
    getDetails(orderId) {
      this.item = null;
      this.orderLogs = []; // 清空操作记录
      getIntegralOrder(orderId).then(response => {
        this.item = response.data;
        this.prod = [JSON.parse(this.item.itemJson)][0];
        // 获取操作记录
        this.getOrderLogsData();
      });
    },
    // 代服账号选择变化
    handleAccountSelectionChange(currentRow, oldRow) {
      this.selectedRow = currentRow;
      if (currentRow) {
        this.form.loginAccount = currentRow.loginAccount;
      }
    },
    // 修改订单弹窗的代服账号选择
    handleEditAccountSelectionChange(currentRow, oldRow) {
      this.editSelectedRow = currentRow;
      if (currentRow) {
        this.editForm.loginAccount = currentRow.loginAccount;
      }
    },
    // 获取代服账号列表
    getAccountList() {
      return new Promise((resolve, reject) => {
        listAccount(this.queryParams).then(response => {
          this.tableData = response.rows || response.data || [];
          this.total = response.total || 0;
          resolve(this.tableData); // 数据加载完成
        }).catch(error => {
          this.tableData = [];
          reject(error);
        });
      });
    },
    handlePageChange(page) {
      this.queryParams.pageNum = page;
      this.getAccountList();
    },
    // 取消订单
    applyRefund() {
      this.$confirm('确定要取消该订单吗？取消后订单将无法恢复。', '取消订单确认', {
        confirmButtonText: '确定取消',
        cancelButtonText: '再想想',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }).then(() => {
        this.cancelOrder();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },

    // 执行取消订单请求
    cancelOrder() {
      const orderCode = this.item.orderCode;
      mandatoryRefunds(orderCode).then(response => {
        if (response.code === 200) {
          this.msgSuccess("取消订单成功");
          // 刷新订单详情
          this.getDetails(this.item.orderId);
          // 刷新父组件列表（如果有）
          if (this.$parent && this.$parent.$parent && this.$parent.$parent.getList) {
            this.$parent.$parent.getList();
          }
        } else {
          this.msgError(response.msg || "取消订单失败");
        }
      }).catch(error => {
        this.msgError("取消订单失败");
        console.error('取消订单失败:', error);
      });
    },
    // 完成订单
    handleFinishOrder() {
      this.$confirm('确定要完成该订单吗？完成后订单状态将变为已完成。', '完成订单确认', {
        confirmButtonText: '确定完成',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确定
        this.executeFinishOrder();
      }).catch(() => {
        // 用户点击取消
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },

    // 执行完成订单请求
    executeFinishOrder() {
      const orderCode = this.item.orderCode;
      console.log("请问请问",orderCode)
      finishOrder(orderCode).then(response => {
        if (response.code === 200) {
          this.msgSuccess("订单完成成功");
          // 刷新订单详情
          this.getDetails(this.item.orderId);
          // 刷新父组件列表（如果有）
          if (this.$parent && this.$parent.$parent && this.$parent.$parent.getList) {
            this.$parent.$parent.getList();
          }
        } else {
          this.msgError(response.msg || "订单完成失败");
        }
      }).catch(error => {
        this.msgError("订单完成失败");
        console.error('完成订单失败:', error);
      });
    },
    // 获取订单操作记录
    getOrderLogsData() {
      if (!this.item || !this.item.orderId) {
        return;
      }

      this.logsLoading = true;
      getOrderLogs(this.item.orderId).then(response => {
        if (response.code === 200) {
          // 按照时间升序排列
          this.orderLogs = response.data.sort((a, b) => {
            return new Date(a.changeTime) - new Date(b.changeTime);
          });
        } else {
          this.orderLogs = [];
        }
        this.logsLoading = false;
      }).catch(error => {
        this.orderLogs = [];
        this.logsLoading = false;
        console.error('获取操作记录失败:', error);
      });
    }
  }
}
</script>
<style>
.contentx {
  height: 100%;
  background-color: #fff;
  padding: 0px 20px 20px;


  margin: 20px;
}

.el-descriptions-item__label.is-bordered-label {
  font-weight: normal;
}

.el-descriptions-item__content {
  max-width: 150px;
  min-width: 100px;
}

.desct {
  padding-top: 20px;
  padding-bottom: 20px;
  color: #524b4a;
  font-weight: bold;
}

.operate-container {
  background: #F2F6FC;
  height: 60px;
  margin: -20px -20px 0;
  line-height: 60px;
}

.order-content {
  margin: 10px;

}

.operate-button-container {
  float: right;
  margin-right: 20px
}
</style>
