<!--
 * @Descripttion: (订单/tb_order)
 * @version: (1.0)
 * @Author: (lwh)
 * @Date: (2023-08-29)
 * @LastEditors: (lwh)
 * @LastEditTime: (2023-08-29)
-->
<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 搜索框 queryParams.需要搜索的字段 -->
      <el-form :model="queryParams" label-position="left" style="margin:15px;" inline ref="queryForm" v-show="showSearch"
        @submit.prevent>
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="queryParams.orderNumber" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="售后类型" prop="refundType">
          <el-select v-model="queryParams.refundType" placeholder="请选择售后类型" clearable @change="handleQuery">
            <el-option v-for="item in  refund_type " :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商家审核状态" prop="merchantAuditStatus">
          <el-select v-model="queryParams.merchantAuditStatus" placeholder="请选择商家审核状态" clearable @change="handleQuery">
            <el-option v-for="item in  merchant_audit_status " :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="售后单状态" prop="orderRefundStatus">
          <el-select v-model="queryParams.orderRefundStatus" placeholder="请选择售后单状态" clearable @change="handleQuery">
            <el-option v-for="item in  order_refund_status " :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker v-model="dateRange" style="width: 240px" type="daterange" range-separator="-"
            start-placeholder="开始日期" end-placeholder="结束日期" :default-time="defaultTime2"
            @change="handleQuery"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
          <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 工具按钮 -->
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['business:order:addOrUpdate']" plain icon="plus"
          @click="AddDialogVisible = true">
          {{ $t('btn.add') }}
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" v-hasPermi="['business:order:delete']" plain icon="delete"
          @click="handleDelete">
          {{ $t('btn.delete') }}
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['business:order:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格渲染  prop="对应的字段"-->
    <el-table v-loading="loading" :data="dataList" ref="tableRef" border highlight-current-row
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />

      <el-table-column prop="goodsInfo" label="商品信息 / 单价与数量" width="500">
        <template #default="scope">
          <div class="order-num-box">
            <div>订单号：<b>{{ scope.row.orderNumber }}</b></div>
            <el-link class="copy" type="primary" @click="copyText(scope.row.orderNumber)">复制订单号</el-link>
          </div>
          <div class="goods-info-box" v-for="(item, idx) in scope.row.goodsInfoList" :key="idx">
            <el-image preview-teleported :hide-on-click-modal="true" lazy class="table-td-thumb" fit="contain"
              :src="item.goodsPicture?.split(',')[0]" :preview-src-list="item.goodsPicture?.split(',')">
              <div><el-icon :size="15">
                  <document />
                </el-icon></div>
            </el-image>

            <div>
              <div class="goods-info-text m2">
                {{ item.goodsName }}
              </div>
              <div>
                <el-tag type="info" v-if="item.goodsSpecName">{{ item.goodsSpecName }}</el-tag>
              </div>
            </div>

            <div class="price-box">
              <div>￥ {{ item.goodsPrice }}</div>
              <div>× {{ item.goodsTotalNum }}</div>
            </div>
          </div>

        </template>
      </el-table-column>
      <!-- <el-table-column prop="goodsInfo" label="单价/数量" width="150">
        <template #default="scope">
          <div>￥ {{ scope.row.goodsInfo.goodsPrice }}</div>
          <div>× {{ scope.row.goodsTotalNum }}</div>
        </template>
      </el-table-column> -->
      <el-table-column prop="payPrice" label="实付款" width="150">
        <template #default="scope">
          <div>￥ {{ scope.row.payPrice }}</div>
          <div>(含运费：￥ {{ scope.row.expressPrice }})</div>
        </template>
      </el-table-column>
      <el-table-column prop="goodsInfo" label="买家信息" width="200">
        <template #default="scope">
          <div class="goods-info-box">
            <div class="avatar">
              <el-avatar shape="circle" :size="50" :src="scope.row.customerAvatar" />
            </div>
            <div>
              <div class="goods-info-text m2">
                {{ scope.row.customerNickName }}
              </div>
              <div>
                {{ scope.row.customerMobilePhoneNumber }}
              </div>
            </div>

          </div>
        </template>
      </el-table-column>
      <el-table-column prop="refundType" label="售后类型" width="150">
        <template #default="scope">
          <dict-tag :options="refund_type" :value="scope.row.refundType" />
        </template>
      </el-table-column>
      <el-table-column prop="orderRefundStatus" label="售后单状态" width="150">
        <template #default="scope">
          <dict-tag :options="order_refund_status" :value="scope.row.orderRefundStatus" />
        </template>
      </el-table-column>
      <el-table-column prop="deliveryStatus" label="处理进度" width="200">
        <template #default="scope">
          <div v-if="scope.row.orderRefundStatus == 1 || scope.row.orderRefundStatus == 3">
            <div class="status-box">商家审核: &nbsp;<dict-tag :options="merchant_audit_status"
                :value="scope.row.merchantAuditStatus" /></div>
            <div class="status-box">用户发货: &nbsp;<dict-tag :options="is_customer_send" :value="scope.row.isCustomerSend" />
            </div>
            <div class="status-box">商家收货: &nbsp;<dict-tag :options="is_merchant_receive"
                :value="scope.row.isMerchantReceive" />
            </div>
          </div>
          <div v-if="scope.row.orderRefundStatus == 2">-- 商家已拒绝 --</div>
          <div v-if="scope.row.orderRefundStatus == 4">-- 售后单已取消 --</div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="申请时间" :show-overflow-tooltip="true" width="200" />


      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <!-- <el-button type="primary" size="small" icon="edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:order:addOrUpdate']">编辑</el-button> -->
          <el-button type="primary" size="small" icon="view" @click="handleDetail(scope.row)">详情</el-button>

          <!-- 审核售后订单 -->
          <el-button type="warning" size="small"
            v-if="scope.row.merchantAuditStatus == 1 && scope.row.orderRefundStatus == 1"
            @click="handleAuditOrderRefund(scope.row)" icon="check">审核</el-button>
          <!-- 确认收货 -->
          <el-button type="warning" size="small"
            v-if="scope.row.isCustomerSend == 2 && scope.row.orderRefundStatus == 1"
            @click="handleConfirmsReceipt(scope.row)" icon="check">确认收货</el-button>
          <el-button type="danger" size="small" icon="delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:order:delete']">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </div>

  <!-- 审核售后订单 -->
  <AuditOrderRefundDialog v-model="AuditOrderRefundDialogVisible" :data="AuditOrderRefundDialogRow"
    :done="() => resetQuery()">
  </AuditOrderRefundDialog>
</template>
<script setup name="order">
import { ElMessageBox } from 'element-plus'
import modal from '@/plugins/modal.js'
import { exportOrderRefund, orderRefundList, confirmsReceipt, delOrderRefund } from '@/api/business/OrderManage/OrderRefunds/orderRefund.js'
import AuditOrderRefundDialog from "./components/AuditOrderRefundDialog.vue";
import useClipboard from 'vue-clipboard3'

const AuditOrderRefundDialogVisible = ref(false);
const AuditOrderRefundDialogRow = ref({});

const { proxy } = getCurrentInstance()

// 选中categoryId数组数组
const ids = ref([])
// 非单选禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 数据列表
const dataList = ref([])
// 总记录数
const total = ref(0)
// 是否加载
const loading = ref(true)
// 路由
const router = useRouter();

const { toClipboard } = useClipboard()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
})
const { queryParams } = toRefs(data)

// 业务参数
const dateRange = ref([])
const defaultTime2 = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
] // '12:00:00', '08:00:00'

// 业务方法
const copyText = async (val) => {
  try {
    await toClipboard(val)
    proxy.$modal.msgSuccess('复制成功！')
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('当前浏览器不支持')
  }
}

// 审核修改订单
function handleAuditOrderRefund(row) {
  AuditOrderRefundDialogVisible.value = true
  AuditOrderRefundDialogRow.value = row
}


function resetStatusQuery() {
  queryParams.value.deliveryStatus = null;
  queryParams.value.receiptStatus = null;
  queryParams.value.payStatus = null;
  queryParams.value.orderStatus = null;
}

/** 确认收货按钮操作 */
function handleConfirmsReceipt(row) {
  const Ids = row.orderRefundGuid

  ElMessageBox.confirm("是否确认确认收货？", "系统提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning",
  })
    .then(function () {
      return confirmsReceipt({ orderRefundGuid: Ids })
    })
    .then(() => {
      handleQuery()
      modal.msgSuccess("确认收货成功")
    })
    .catch(() => { })
}



// 字典获取
const refund_type = ref([]);
async function getrefund_type() {
  await proxy.getDicts('refund_type').then((res) => {
    refund_type.value = res.data
  })
}
getrefund_type()
// 字典获取
const refund_reason = ref([]);
async function getrefund_reason() {
  await proxy.getDicts('refund_reason').then((res) => {
    refund_reason.value = res.data
  })
}
getrefund_reason()
// 字典获取
const goods_receive_status = ref([]);
async function getgoods_receive_status() {
  await proxy.getDicts('goods_receive_status').then((res) => {
    goods_receive_status.value = res.data
  })
}
getgoods_receive_status()
// 字典获取
const merchant_audit_status = ref([]);
async function getmerchant_audit_status() {
  await proxy.getDicts('merchant_audit_status').then((res) => {
    merchant_audit_status.value = res.data
  })
}
getmerchant_audit_status()
// 字典获取
const is_customer_send = ref([]);
async function getis_customer_send() {
  await proxy.getDicts('is_customer_send').then((res) => {
    is_customer_send.value = res.data
  })
}
getis_customer_send()
// 字典获取
const order_refund_status = ref([]);
async function getorder_refund_status() {
  await proxy.getDicts('order_refund_status').then((res) => {
    order_refund_status.value = res.data
  })
}
getorder_refund_status()
// 字典获取
const is_merchant_receive = ref([]);
async function getis_merchant_receive() {
  await proxy.getDicts('is_merchant_receive').then((res) => {
    is_merchant_receive.value = res.data
  })
}
getis_merchant_receive()


//基础方法

// 查询数据
function getList() {
  loading.value = true
  console.log(dateRange?.value[1])
  orderRefundList(proxy.addDateRange(queryParams.value, dateRange.value)).then((res) => {
    if (res.code == 200) {
      loading.value = false;
      dataList.value = res.data.result;
      total.value = res.data.totalNum;
    }
  });
}


// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.orderRefundId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 重置查询操作 */
function resetQuery() {
  resetStatusQuery()
  dateRange.value = []
  proxy.resetForm('queryForm')
  handleQuery()
}
/** 搜索按钮操作 */
function handleQuery() {
  getList()
}
/** 删除按钮操作 */
function handleDelete(row) {
  const Ids = row.orderRefundId || ids.value

  ElMessageBox.confirm("是否确认删除？", "系统提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning",
  })
    .then(function () {
      return delOrderRefund(Ids)
    })
    .then(() => {
      handleQuery()
      modal.msgSuccess("删除成功")
    })
    .catch(() => { })
}

/** 导出按钮操作 */
function handleExport(row) {
  const Ids = row.orderRefundId || ids.value
  const name = ref("所有")

  if (Ids.length != 0) {
    let str = ''
    for (const key in Ids) {
      str += Ids[key] + ','
    }
    str = str.slice(0, str.length - 1)
    queryParams.value.ids = str
    name.value = "选中"
  }

  ElMessageBox.confirm('是否确认导出' + name.value + '数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(function () {
      return exportOrderRefund(queryParams.value)
    })
    .then((response) => {
      proxy.download(response.data.path)
    })
}



// 详情
function handleDetail(row) {
  router.push("/orders/orderRefundsDetail?orderRefundId=" + row.orderRefundId)
  // DetailDialogVisible.value = true
  // DetailDialogRow.value = row
}

handleQuery()
</script>

<style lang="scss" scoped>
.goods-info-box {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}

.goods-info-text {
  width: 250px;
  margin-bottom: 10px;
}

.m2 {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.avatar {
  margin-right: 15px;
}

.status-box {
  display: flex;
  align-items: center;
  margin-bottom: 2px;
}

.price-box {
  width: 60px;
}

.order-num-box {
  display: flex;
  position: relative;

  .copy {
    position: absolute;
    right: 0%;
  }
}</style>