<!--
 * @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="name">
          <el-input v-model="queryParams.name" placeholder="请输入收货人姓名" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="收货人手机号" prop="phone">
          <el-input v-model="queryParams.phone" placeholder="请输入收货人手机号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsTrackingNumber">
          <el-input v-model="queryParams.logisticsTrackingNumber" placeholder="请输入物流单号" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-select v-model="queryParams.payType" placeholder="请选择支付方式" clearable @change="handleQuery">
            <el-option v-for="item in  pay_type " :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配送方式" prop="deliveryType">
          <el-select v-model="queryParams.deliveryType" placeholder="请选择配送方式" clearable @change="handleQuery">
            <el-option v-for="item in  delivery_type " :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="结束日期"></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="450">
        <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">{{ 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="payType" label="支付方式" width="150">
        <template #default="scope">
          <dict-tag :options="pay_type" :value="scope.row.payType" />
        </template>
      </el-table-column>
      <el-table-column prop="deliveryType" label="配送方式" width="150">
        <template #default="scope">
          <dict-tag :options="delivery_type" :value="scope.row.deliveryType" />
        </template>
      </el-table-column>
      <el-table-column prop="deliveryStatus" label="交易状态" width="200">
        <template #default="scope">
          <div class="status-box">付款状态: &nbsp;<dict-tag :options="pay_status" :value="scope.row.payStatus" /></div>
          <div class="status-box">发货状态: &nbsp;<dict-tag :options="delivery_status" :value="scope.row.deliveryStatus" />
          </div>
          <div class="status-box">收货状态: &nbsp;<dict-tag :options="receipt_status" :value="scope.row.receiptStatus" />
          </div>
          <div class="status-box">订单状态: &nbsp;<dict-tag :options="order_status" :value="scope.row.orderStatus" /></div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" :show-overflow-tooltip="true" width="200" />


      <el-table-column label="操作" width="250" 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="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>

  <!-- 添加 -->
  <AddDialog v-model="AddDialogVisible" :done="() => resetQuery()"></AddDialog>
  <!-- 编辑 -->
  <EditDialog v-model="EditDialogVisible" :data="EditDialogRow" :done="() => resetQuery()"></EditDialog>
  <!-- 详情 -->
  <DetailDialog v-model="DetailDialogVisible" :data="DetailDialogRow" :done="() => resetQuery()"></DetailDialog>
</template>
<script setup name="order">
import { ElMessageBox } from 'element-plus'
import modal from '@/plugins/modal.js'
import { exportOrder, orderList, delOrder } from '@/api/business/OrderManage/Orders/order.js'
import AddDialog from "./components/AddDialog.vue";
import EditDialog from "./components/EditDialog.vue";
import DetailDialog from "./components/DetailDialog.vue";
import useClipboard from 'vue-clipboard3'

const AddDialogVisible = ref(false);
const EditDialogVisible = ref(false);
const EditDialogRow = ref({});
const DetailDialogVisible = ref(false);
const DetailDialogRow = 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 copyText = async (val) => {
  try {
    await toClipboard(val)
    proxy.$modal.msgSuccess('复制成功！')
  } catch (e) {
    console.log(e)
    proxy.$modal.msgError('当前浏览器不支持')
  }
}

// 字典获取
const pay_type = ref([]);
async function getpay_type() {
  await proxy.getDicts('pay_type').then((res) => {
    pay_type.value = res.data
  })
}
getpay_type()
// 字典获取
const pay_status = ref([]);
async function getpay_status() {
  await proxy.getDicts('pay_status').then((res) => {
    pay_status.value = res.data
  })
}
getpay_status()
// 字典获取
const delivery_type = ref([]);
async function getdelivery_type() {
  await proxy.getDicts('delivery_type').then((res) => {
    delivery_type.value = res.data
  })
}
getdelivery_type()
// 字典获取
const delivery_status = ref([]);
async function getdelivery_status() {
  await proxy.getDicts('delivery_status').then((res) => {
    delivery_status.value = res.data
  })
}
getdelivery_status()
// 字典获取
const receipt_status = ref([]);
async function getreceipt_status() {
  await proxy.getDicts('receipt_status').then((res) => {
    receipt_status.value = res.data
  })
}
getreceipt_status()
// 字典获取
const order_status = ref([]);
async function getorder_status() {
  await proxy.getDicts('order_status').then((res) => {
    order_status.value = res.data
  })
}
getorder_status()
// 字典获取
const is_settled = ref([]);
async function getis_settled() {
  await proxy.getDicts('is_settled').then((res) => {
    is_settled.value = res.data
  })
}
getis_settled()
// 字典获取
const is_comment = ref([]);
async function getis_comment() {
  await proxy.getDicts('is_comment').then((res) => {
    is_comment.value = res.data
  })
}
getis_comment()




//基础方法

// 查询数据
function getList() {
  loading.value = true


  orderList(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.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

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

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

/** 导出按钮操作 */
function handleExport(row) {
  const Ids = row.orderId || 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 exportOrder(queryParams.value)
    })
    .then((response) => {
      proxy.download(response.data.path)
    })
}


// 修改
function handleUpdate(row) {
  EditDialogVisible.value = true
  EditDialogRow.value = row
}

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

handleQuery()
</script>

<style lang="scss">
.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>