<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="returnNo">
              <el-input v-model="queryParams.returnNo" placeholder="请输入退货单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="售后备注" prop="afterSalesRemarks">
              <el-input v-model="queryParams.afterSalesRemarks" placeholder="请输入售后备注" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="退货方式" prop="returnMethod">
              <el-input v-model="queryParams.returnMethod" 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="warning" plain icon="Download" @click="handleExport" v-hasPermi="['order:zhongcheReturn: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="zhongcheReturnList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="退货单号" align="center" prop="returnNo" width="180" />
        <el-table-column label="发起售后时间" align="center" prop="returnTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="退货原因" align="center" prop="returnReason" />

        <el-table-column label="售后金额" align="center" prop="afterSaleAmount" />
        <el-table-column label="退货订单状态" align="center" prop="returnStatus">
          <template #default="scope">
            <dict-tag :options="return_status" :value="scope.row.returnStatus" />
          </template>
        </el-table-column>
        <el-table-column label="商品数量" align="center" prop="returnProductNum" />
        <el-table-column label="问题描述" align="center" prop="problemDescription" />
        <el-table-column label="售后方式" align="center" prop="serviceType">
          <template #default="scope">
            <dict-tag :options="service_type" :value="scope.row.serviceType" />
          </template>
        </el-table-column>
        <el-table-column label="取件方式" align="center" prop="pickType">
          <template #default="scope">
            <dict-tag :options="pick_type" :value="scope.row.pickType" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">订单详情</el-button>
          </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="600px" append-to-body>
      <el-form ref="zhongcheReturnFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单编号" prop="returnNo">
          <el-input v-model="form.returnNo" readonly />
        </el-form-item>
        <el-form-item label="状态" prop="returnStatus">
          <el-input :value="getReturnStatusLabel(form.returnStatus)" readonly />
        </el-form-item>
        <el-form-item label="申请时间" prop="returnTime">
          <el-input v-model="form.returnTime" readonly />
        </el-form-item>
        <el-form-item label="下单客户" prop="buyerName">
          <el-input v-model="form.buyerName" readonly />
        </el-form-item>
        <el-form-item label="联系电话" prop="buyerMobile">
          <el-input v-model="form.buyerMobile" readonly />
        </el-form-item>
        <el-form-item label="退款原因" prop="returnReason">
          <el-input v-model="form.returnReason" readonly />
        </el-form-item>
        <el-form-item label="问题描述" prop="problemDescription">
          <el-input v-model="form.problemDescription" type="textarea" :rows="3" readonly />
        </el-form-item>
        <el-form-item label="售后图片" prop="voucherPhoto">
          <div style="display: flex; gap: 10px; flex-wrap: wrap;" v-if="form.voucherPhoto">
            <el-image
              v-for="(url, index) in form.voucherPhoto.split(',').filter(Boolean)"
              :key="index"
              :src="url"
              :preview-src-list="form.voucherPhoto.split(',').filter(Boolean)"
              :initial-index="index"
              fit="cover"
              style="width: 80px; height: 80px; border-radius: 5px; cursor: pointer; box-shadow: 0 0 5px 1px #ccc;"
              preview-teleported
            />
          </div>
        </el-form-item>
        <el-form-item>
          <div style="display: flex; gap: 10px; margin-top: 10px;">
            <el-button type="primary" @click="handleMerchantProcess">商家接受</el-button>
            <el-button color="#f56c6c" style="color: white;" @click="handleMerchantReject">商家拒绝</el-button>
            <el-button type="primary" @click="handleMerchantRetrieve">商家收到商品</el-button>
            <el-button type="primary" @click="handleReturnComplete">确认退款</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 接受售后补充信息对话框 -->
    <el-dialog title="填写取件信息" v-model="acceptDialog.visible" width="500px" append-to-body>
      <el-form ref="acceptFormRef" :model="acceptForm" :rules="acceptRules" label-width="100px">
        <el-form-item label="联系人" prop="name">
          <el-input v-model="acceptForm.name" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="acceptForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="省市区" prop="areaCodes">
          <el-cascader
            v-model="acceptForm.areaCodes"
            :options="chinaAreaOptions"
            :props="chinaAreaCascaderProps"
            :disabled="chinaAreaLoading"
            clearable
            placeholder="请选择省/市/区"
            style="width: 100%"
            @change="handleAreaCodesChange"
          />
        </el-form-item>
        
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="acceptForm.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="邮编" prop="zip">
          <el-input v-model="acceptForm.zip" placeholder="请输入邮编" />
        </el-form-item>
        <el-form-item label="座机号" prop="phone">
          <el-input v-model="acceptForm.phone" placeholder="请输入座机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="acceptForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAcceptForm">确 定</el-button>
          <el-button @click="acceptDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ZhongcheReturn" lang="ts">
import { listZhongcheReturn, getZhongcheReturn, delZhongcheReturn, addZhongcheReturn, updateZhongcheReturn, acceptAfterSale, rejectAfterSale, confirmReceived, refundAfterSale } from '@/api/order/zhongcheReturn';
import { ZhongcheReturnVO, ZhongcheReturnQuery, ZhongcheReturnForm } from '@/api/order/zhongcheReturn/types';
import { getChinaArea } from '@/api/system/addressArea/index';
import type { AddressAreaVo } from '@/api/system/addressArea/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { return_status } = toRefs<any>(proxy?.useDict('return_status'));
const { service_type } = toRefs<any>(proxy?.useDict('service_type'));
const { pick_type } = toRefs<any>(proxy?.useDict('pick_type'));

const chinaAreaTree = ref<AddressAreaVo | undefined>(undefined);
const chinaAreaLoading = ref(false);

const zhongcheReturnList = ref<ZhongcheReturnVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const zhongcheReturnFormRef = ref<ElFormInstance>();
const acceptFormRef = ref<ElFormInstance>();

const acceptDialog = reactive<DialogOption>({
  visible: false,
  title: '填写取件信息'
});

const acceptForm = ref<any>({});
const acceptRules = reactive({
  name: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
  mobile: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
  areaCodes: [{ required: true, message: "省市区不能为空", trigger: "change" }],
  address: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
  email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }]
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ZhongcheReturnForm = {
  id: undefined,
  orderId: undefined,
  orderNo: undefined,
  serviceType: undefined,
  returnTime: undefined,
  returnNo: undefined,
  customerId: undefined,
  customerNo: undefined,
  customerName: undefined,
  afterSaleAmount: undefined,
  returnStatus: undefined,
  returnProductNum: undefined,
  processingTime: undefined,
  returnReasonId: undefined,
  returnReason: undefined,
  problemDescription: undefined,
  voucherPhoto: undefined,
  shippingFee: undefined,
  isShippingFee: undefined,
  orderAmount: undefined,
  returnAmount: undefined,
  afterSalesRemarks: undefined,
  returnMethod: undefined,
  chargebackName: undefined,
  chargebackPhone: undefined,
  chargebackPickupTime: undefined,
  chargebackProvincial: undefined,
  chargebackCity: undefined,
  chargebackCounty: undefined,
  provincialCityCounty: undefined,
  chargebackAddress: undefined,
  pushStatus: undefined,
  logisticsId: undefined,
  logisticsName: undefined,
  logisticsNo: undefined,
  status: undefined,
  remark: undefined,
  buyerName: undefined,
  buyerMobile: undefined,
  pickType: undefined,
}
const data = reactive<PageData<ZhongcheReturnForm, ZhongcheReturnQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    serviceType: undefined,
    returnNo: undefined,
    returnStatus: undefined,
    afterSalesRemarks: undefined,
    returnMethod: undefined,
    params: {
    }
  },
  rules: {
  }
});

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

/** 查询中车售后单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listZhongcheReturn(queryParams.value);
  zhongcheReturnList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

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

/** 订单详情按钮操作 */
const handleDetail = async (row: ZhongcheReturnVO) => {
  reset();
  const _id = row.id;
  const res = await getZhongcheReturn(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "售后订单详情";
}

/** 获取状态名称 */
const getReturnStatusLabel = (val: string | undefined) => {
  if (!val) return '';
  const item = return_status.value.find((dict: any) => dict.value === val);
  return item ? item.label : val;
}

/** 商家接受 */
const handleMerchantProcess = async () => {
  if (!form.value.id) return;
  
  if (form.value.pickType === '2' || form.value.pickType === '3') {
    acceptForm.value = {
      returnId: form.value.id,
      pickType: form.value.pickType,
      name: undefined,
      provinceId: undefined,
      cityId: undefined,
      countyId: undefined,
      areaCodes: [],
      townId: undefined,
      address: undefined,
      zip: undefined,
      mobile: undefined,
      phone: undefined,
      email: undefined
    };
    acceptDialog.visible = true;
  } else {
    await proxy?.$modal.confirm("是否确认商家接受该售后？");
    buttonLoading.value = true;
    await acceptAfterSale({ returnId: form.value.id, pickType: form.value.pickType }).finally(() => buttonLoading.value = false);
    proxy?.$modal.msgSuccess("操作成功");
    dialog.visible = false;
    await getList();
  }
}

/** 提交接受售后补充信息 */
const submitAcceptForm = () => {
  acceptFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await acceptAfterSale(acceptForm.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess("操作成功");
      acceptDialog.visible = false;
      dialog.visible = false;
      await getList();
    }
  });
}

/** 商家拒绝 */
const handleMerchantReject = () => {
  if (!form.value.id) return;
  proxy?.$modal.prompt("请输入拒绝原因").then(async ({ value }) => {
    if (!value) {
      return proxy?.$modal.msgError("拒绝原因不能为空");
    }
    buttonLoading.value = true;
    await rejectAfterSale(form.value.id as string | number, value).finally(() => buttonLoading.value = false);
    proxy?.$modal.msgSuccess("已拒绝该售后");
    dialog.visible = false;
    await getList();
  }).catch(() => {});
}

/** 商家收到商品 */
const handleMerchantRetrieve = async () => {
  if (!form.value.id) return;
  await proxy?.$modal.confirm("是否确认收到退货商品？");
  buttonLoading.value = true;
  await confirmReceived(form.value.id).finally(() => buttonLoading.value = false);
  proxy?.$modal.msgSuccess("确认收货成功");
  dialog.visible = false;
  await getList();
}

/** 确认退款 */
const handleReturnComplete = async () => {
  if (!form.value.id) return;
  await proxy?.$modal.confirm("是否确认完成售后退款？");
  buttonLoading.value = true;
  await refundAfterSale(form.value.id).finally(() => buttonLoading.value = false);
  proxy?.$modal.msgSuccess("退款处理成功");
  dialog.visible = false;
  await getList();
}

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('order/zhongcheReturn/export', {
    ...queryParams.value
  }, `zhongcheReturn_${new Date().getTime()}.xlsx`)
}

const loadChinaArea = async () => {
  chinaAreaLoading.value = true;
  try {
    const res = await getChinaArea();
    chinaAreaTree.value = res.data;
  } catch (e: any) {
    proxy?.$modal.msgError(e?.message || '获取地区数据失败');
  } finally {
    chinaAreaLoading.value = false;
  }
}

const chinaAreaOptions = computed<any[]>(() => {
  const data: any = chinaAreaTree.value as any;
  if (!data) return [];
  if (Array.isArray(data)) return data;
  if (Array.isArray(data.children)) return data.children;
  return [data];
});

const chinaAreaCascaderProps = {
  value: 'areaCode',
  label: 'areaName',
  children: 'children',
  emitPath: true,
  checkStrictly: false
};

const handleAreaCodesChange = (val: any) => {
  const codes = Array.isArray(val) ? val : [];
  acceptForm.value.provinceId = codes[0];
  acceptForm.value.cityId = codes[1];
  acceptForm.value.countyId = codes[2];
}

onMounted(() => {
  getList();
  loadChinaArea();
});
</script>
