<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户昵称" prop="userNickname">
              <el-input v-model="queryParams.userNickname" placeholder="请输入用户昵称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="真实姓名" prop="userRealName">
              <el-input v-model="queryParams.userRealName" placeholder="请输入真实姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="账号ID" prop="userAccountId">
              <el-input v-model="queryParams.userAccountId" placeholder="请输入账号ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单编号" prop="orderSn">
              <el-input v-model="queryParams.orderSn" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </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-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['physical:order:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:order:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['physical:order:remove']">删除</el-button>
          </el-col>-->
          <!--          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:order:export']">导出</el-button>
          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" v-if="true" />
        <el-table-column type="expand" label="商品明细" width="80">
          <template #default="props">
            <div class="order-items-expand">
              <el-table :data="props.row.physicalOrderItemVoList || []" border style="width: 100%" size="small">
                <el-table-column label="商品名称" prop="name" min-width="150" />
                <el-table-column label="单价 (元)" prop="price" width="100" align="right">
                  <template #default="scope">
                    <span>¥{{ scope.row.price }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="数量" prop="quantity" width="80" align="center" />
                <el-table-column label="小计" prop="totalPrice" width="100" align="right">
                  <template #default="scope">
                    <span class="text-primary">¥{{ scope.row.totalPrice }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="所属商家" prop="merchantName" min-width="120" />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户昵称" align="center" prop="userNickname" />
        <el-table-column label="真实姓名" align="center" prop="userRealName" />
        <el-table-column label="身份证号" align="center" prop="userIdCard" />
        <el-table-column label="账号ID" align="center" prop="userAccountId" />
        <el-table-column label="订单编号" align="center" prop="orderSn" />
        <el-table-column label="订单总金额" align="center" prop="totalAmount" />
        <el-table-column label="订单状态" align="center" prop="status" 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 label="物流单号" align="center" prop="waybillNumber" />
        <el-table-column label="用户收货地址" align="center" prop="userAddress" />
        <el-table-column label="创建人" align="center" prop="createdBy" />
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="flex flex-col gap-1">
              <el-tooltip content="录入物流订单号" placement="top">
                <el-button link type="success" icon="Edit" @click="handleInputWaybillNumber(scope.row)" v-hasPermi="['physical:order:edit']">
                  录入单号
                </el-button>
              </el-tooltip>
              <el-tooltip content="修改地址" placement="top">
                <el-button link type="success" icon="Edit" @click="handleEditAddress(scope.row)" v-hasPermi="['physical:order:edit']">
                  修改地址
                </el-button>
              </el-tooltip>
              <el-tooltip content="发货" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleShipment(scope.row)" v-hasPermi="['physical:order:edit']">
                  发货
                </el-button>
              </el-tooltip>
            </div>
          </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-card>
    <!-- 添加或修改商城订单主对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="userNickname">
          <el-input v-model="form.userNickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="userRealName">
          <el-input v-model="form.userRealName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="userIdCard">
          <el-input v-model="form.userIdCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="账号ID" prop="userAccountId">
          <el-input v-model="form.userAccountId" placeholder="请输入账号ID" />
        </el-form-item>
        <el-form-item label="用户收货地址" prop="userAddress">
          <el-input v-model="form.userAddress" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单总金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="录入物流订单号" v-model="waybillDialog.visible" width="400px" append-to-body>
      <el-form ref="waybillFormRef" :model="waybillForm" label-width="100px">
        <el-form-item label="物流单号" required>
          <el-input v-model="waybillForm.waybillNumber" placeholder="请输入物流单号" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitWaybillForm">确 定</el-button>
          <el-button @click="cancelWaybill">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="修改收货地址" v-model="addressDialog.visible" width="500px" append-to-body>
      <el-form ref="addressFormRef" :model="addressForm" label-width="100px">
        <el-form-item label="省份" required>
          <el-select v-model="addressForm.provinceName" placeholder="请选择省份" @change="handleProvinceChange" style="width: 100%">
            <el-option v-for="item in provinces" :key="item.code" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>

        <el-form-item label="城市" required>
          <el-select v-model="addressForm.cityName" placeholder="请选择城市" @change="handleCityChange" style="width: 100%">
            <el-option v-for="item in cities" :key="item.code" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>

        <el-form-item label="区县" required>
          <el-select v-model="addressForm.districtName" placeholder="请选择区县" style="width: 100%">
            <el-option v-for="item in districts" :key="item.code" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系人" required>
          <el-input v-model="addressForm.receiverName" placeholder="请输入联系人姓名" />
        </el-form-item>

        <el-form-item label="联系方式" required>
          <el-input v-model="addressForm.mobilePhone" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item label="详细地址" required>
          <el-input v-model="addressForm.detailAddress" placeholder="请输入详细地址" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitAddressForm">确 定</el-button>
          <el-button @click="cancelAddress">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
import { listOrder, getOrder, delOrder, addOrder, updateOrder, updateOrderSelective, sendShipment } from '@/api/system/physical/order';

import { OrderVO, OrderQuery, OrderForm } from '@/api/system/physical/order/types';
import { RegionVO } from '@/api/system/physical/region/types';
import { selectCityList } from '@/api/system/physical/region';
import { selectPhysicalOrderAddress, updateOrderAddress } from '@/api/system/physical/orderAddress';
import { OrderAddressForm } from '@/api/system/physical/orderAddress/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const orderList = ref<OrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const addressFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();
const waybillFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderForm = {
  id: undefined,
  userNickname: undefined,
  userRealName: undefined,
  userIdCard: undefined,
  userAccountId: undefined,
  userAddress: undefined,
  orderSn: undefined,
  totalAmount: undefined,
  status: undefined,
  createdBy: undefined,
  createdAt: undefined,
  updatedBy: undefined,
  updatedAt: undefined
};
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userNickname: undefined,
    userRealName: undefined,
    userIdCard: undefined,
    userAccountId: undefined,
    userAddress: undefined,
    orderSn: undefined,
    totalAmount: undefined,
    status: undefined,
    createdBy: undefined,
    createdAt: undefined,
    updatedBy: undefined,
    updatedAt: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    userNickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    userAccountId: [{ required: true, message: '账号ID不能为空', trigger: 'blur' }],
    userAddress: [{ required: true, message: '用户收货地址不能为空', trigger: 'blur' }],
    orderSn: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
    totalAmount: [{ required: true, message: '订单总金额不能为空', trigger: 'blur' }],
    status: [
      {
        required: true,
        message: '订单状态不能为空',
        trigger: 'change'
      }
    ],
    createdBy: [{ required: true, message: '创建人不能为空', trigger: 'blur' }]
  }
});

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

/** 查询商城订单主列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrder(queryParams.value);
  orderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  orderFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加商城订单主';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改商城订单主';
};

/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateOrder(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addOrder(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商城订单主编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delOrder(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/order/export',
    {
      ...queryParams.value
    },
    `order_${new Date().getTime()}.xlsx`
  );
};
/** 获取订单状态文本 */
const getOrderStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    no_shipped: '待发货',
    pending_payment: '待支付',
    paid: '已支付',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  };
  return statusMap[status] || status;
};

/** 获取订单状态标签类型 */
const getOrderStatusType = (status: string): 'success' | 'warning' | 'info' | 'danger' | 'primary' | '' => {
  const typeMap: Record<string, 'success' | 'warning' | 'info' | 'danger' | 'primary' | ''> = {
    pending_payment: 'warning',
    paid: 'success',
    shipped: 'success',
    completed: 'success',
    cancelled: 'info'
  };
  return typeMap[status] || '';
};

onMounted(() => {
  getList();
});
const waybillDialog = reactive({
  visible: false,
  currentOrderId: undefined as string | number | undefined
});

const waybillForm = reactive({
  waybillNumber: ''
});
/** 录入物流单号按钮操作 */
const handleInputWaybillNumber = (row: OrderVO) => {
  waybillForm.waybillNumber = '';
  waybillDialog.currentOrderId = row.id;
  waybillDialog.visible = true;
};
/** 取消录入物流单号 */
const cancelWaybill = () => {
  waybillForm.waybillNumber = '';
  waybillDialog.visible = false;
  waybillDialog.currentOrderId = undefined;
};
/** 提交录入物流单号 */
const submitWaybillForm = async () => {
  if (!waybillForm.waybillNumber) {
    proxy?.$modal.msgError('请输入物流单号');
    return;
  }
  buttonLoading.value = true;
  try {
    await updateOrderSelective({
      id: waybillDialog.currentOrderId,
      waybillNumber: waybillForm.waybillNumber
    } as OrderForm);
    proxy?.$modal.msgSuccess('录入成功');
    waybillDialog.visible = false;
    waybillDialog.currentOrderId = undefined;
    waybillForm.waybillNumber = '';
    await getList();
  } finally {
    buttonLoading.value = false;
  }
};
/** 发货按钮操作 */
const handleShipment = async (row: OrderVO) => {
  const orderId = row.id;
  await proxy?.$modal.confirm('确认要对该订单进行发货操作吗？');
  buttonLoading.value = true;
  try {
    await sendShipment({ id: orderId } as OrderForm);
    proxy?.$modal.msgSuccess('发货成功');
    await getList();
  } finally {
    buttonLoading.value = false;
  }
};

const addressDialog = reactive({
  visible: false,
  currentOrderId: undefined as string | number | undefined,
  orderSn: '',
  addressId: undefined as string | number | undefined
});

const addressForm = reactive({
  provinceName: '',
  cityName: '',
  districtName: '',
  receiverName: '',
  mobilePhone: '',
  detailAddress: ''
});

const provinces = ref<RegionVO[]>([]);
const cities = ref<RegionVO[]>([]);
const districts = ref<RegionVO[]>([]);
/** 修改地址按钮操作 */
const handleEditAddress = async (row: OrderVO) => {
  addressDialog.currentOrderId = row.id;
  addressDialog.orderSn = row.orderSn;
  addressForm.provinceName = '';
  addressForm.cityName = '';
  addressForm.districtName = '';
  addressForm.receiverName = '';
  addressForm.mobilePhone = '';
  addressForm.detailAddress = '';

  provinces.value = [];
  cities.value = [];
  districts.value = [];
  await loadProvinces();
  if (row.orderSn) {
    try {
      const res = await selectPhysicalOrderAddress(row.orderSn);
      if (res.data) {
        addressDialog.addressId = res.data.id;
        addressForm.provinceName = res.data.provinceName || '';
        addressForm.cityName = res.data.cityName || '';
        addressForm.districtName = res.data.districtName || '';
        addressForm.receiverName = res.data.receiverName || '';
        addressForm.mobilePhone = res.data.mobilePhone || '';
        addressForm.detailAddress = res.data.detailAddress || '';
        if (addressForm.provinceName) {
          const province = provinces.value.find((item) => item.name === addressForm.provinceName);
          if (province) {
            const cityRes = await selectCityList(province.code, '2');
            cities.value = cityRes.data || [];
            if (addressForm.cityName) {
              const city = cities.value.find((item) => item.name === addressForm.cityName);
              if (city) {
                const districtRes = await selectCityList(city.code, '3');
                districts.value = districtRes.data || [];
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('获取地址失败:', error);
    }
  }
  addressDialog.visible = true;
};

/** 加载省份列表 */
const loadProvinces = async () => {
  const res = await selectCityList('', '1');
  provinces.value = res.data || [];
};

/** 省份切换 */
const handleProvinceChange = async (provinceName: string) => {
  cities.value = [];
  districts.value = [];
  addressForm.cityName = '';
  addressForm.districtName = '';

  if (!provinceName) return;

  const province = provinces.value.find((item) => item.name === provinceName);
  if (province) {
    const res = await selectCityList(province.code, '2');
    cities.value = res.data || [];
  }
};

/** 城市切换 */
const handleCityChange = async (cityName: string) => {
  districts.value = [];
  addressForm.districtName = '';

  if (!cityName) return;

  const city = cities.value.find((item) => item.name === cityName);
  if (city) {
    const res = await selectCityList(city.code, '3');
    districts.value = res.data || [];
  }
};

/** 取消修改地址 */
const cancelAddress = () => {
  addressDialog.visible = false;
  addressDialog.currentOrderId = undefined;
  addressFormRef.value?.resetFields();
};

/** 提交修改地址 */
const submitAddressForm = async () => {
  if (!addressForm.provinceName || !addressForm.cityName || !addressForm.districtName) {
    proxy?.$modal.msgError('请选择省市区');
    return;
  }
  if (!addressForm.receiverName) {
    proxy?.$modal.msgError('请输入联系人姓名');
    return;
  }
  if (!addressForm.mobilePhone) {
    proxy?.$modal.msgError('请输入联系方式');
    return;
  }
  if (!addressForm.detailAddress) {
    proxy?.$modal.msgError('请输入详细地址');
    return;
  }
  buttonLoading.value = true;
  try {
    const fullAddress = `${addressForm.provinceName}${addressForm.cityName}${addressForm.districtName}${addressForm.detailAddress}`;
    await updateOrderAddress({
      orderSn: addressDialog.orderSn,
      provinceName: addressForm.provinceName,
      provinceCode: provinces.value.find((p) => p.name === addressForm.provinceName)?.code || '',
      cityName: addressForm.cityName,
      cityCode: cities.value.find((c) => c.name === addressForm.cityName)?.code || '',
      districtName: addressForm.districtName,
      districtCode: districts.value.find((d) => d.name === addressForm.districtName)?.code || '',
      receiverName: addressForm.receiverName,
      mobilePhone: addressForm.mobilePhone,
      detailAddress: addressForm.detailAddress,
      userAddress: fullAddress,
      status: 'normal',
      id: addressDialog.addressId,
      currentOrderId: addressDialog.currentOrderId
    } as OrderAddressForm);
    proxy?.$modal.msgSuccess('地址修改成功');
    addressDialog.visible = false;
    addressDialog.currentOrderId = undefined;
    await getList();
  } finally {
    buttonLoading.value = false;
  }
};
</script>
