<template>
  <div class="main">
    <div class="banner">
      <div class="order-information">
        <div class="header">接单中心</div>
        <div class="condition-scarch">
          <ul>
            <li>
              <div class="label">收货地址：</div>
              <el-cascader placeholder="请输入收获区域" size="large" :options="addressData" v-model="form.address">
              </el-cascader>
              <el-input
                style="width: 1.4583rem; margin-left: 0.0521rem"
                size="large"
                v-model="form.addressInfo"
                placeholder="详细地址街道..."
              />
              <div class="search-btn" @click="searchOrder">搜索</div>
            </li>
            <li>
              <div class="label">成交价：</div>
              <div class="price-whel">
                <div
                  v-for="(item, index) in priceWhel"
                  :key="index"
                  @click="priceWhelChange(index)"
                  :class="priceWhelIndex === index ? 'active' : ''"
                >
                  {{ item }}
                </div>
              </div>
            </li>
            <li>
              <div class="label">收货时间：</div>
              <div class="price-whel">
                <div
                  v-for="(item, index) in addressTime"
                  :key="index"
                  @click="addressTimeChange(index)"
                  :class="addressTimeIndex === index ? 'active' : ''"
                >
                  {{ item }}
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div class="tabs">
        <div :class="active === 0 ? 'standard active' : 'standard'" @click="tabSort(0)">综合排序</div>
        <div :class="active === 1 ? 'standard active' : 'standard'" @click="tabSort(1)">按配送时间</div>
        <div :class="active === 2 ? 'standard active' : 'standard'" @click="tabSort(2)">按下单时间</div>
        <div :class="active === 3 ? 'standard active sort' : 'standard sort'" @click="tabSort(3)">
          按订单金额
          <div v-if="active == 3" class="sort-box">
            <div :class="activeSort == 0 ? 'ascending-orde active-sort' : 'ascending-orde'" @click="priceSort(0)">
              <el-icon><CaretTop /></el-icon>
            </div>
            <div @click="priceSort(1)" :class="activeSort == 1 ? 'descending active-sort' : 'descending'">
              <el-icon><CaretBottom /></el-icon>
            </div>
          </div>
          <div v-else class="sort-box">
            <div class="ascending-orde">
              <el-icon><CaretTop /></el-icon>
            </div>
            <div class="descending">
              <el-icon><CaretBottom /></el-icon>
            </div>
          </div>
        </div>
      </div>
      <div class="line-items" v-loading="loading">
        <div class="item" v-for="(item, index) in orderList" :key="item.id" @click.stop="goToOrderInfo(item.orderNo)">
          <div class="header">
            <div class="address">
              【{{ item.province }} {{ item.city }} {{ item.district }}】{{ item.street }}{{ item.detail }}
            </div>
            <div class="map-box" @click.stop="showMap(item)">
              <div class="icon">
                <el-icon><MapLocation /></el-icon>
              </div>
              <div class="map">查看地图</div>
            </div>
            <div class="time">下单时间：{{ item.createTime }}</div>
          </div>
          <div class="order-info">
            <div class="image">
              <img :src="item.image" style="width: 100%; height: 100%" />
              <div class="tag">普通订单</div>
            </div>
            <div class="iine-info">
              <div class="receipt-time">
                <div class="label">
                  收货时间：<span class="time">{{ item.deliveryDate }} {{ item.deliveryTime }}</span>
                  <span class="timeout"
                    >离接单结束还剩：{{ setTimeOutEvent(item.deliveryDate, item.deliveryTime) }}</span
                  >
                </div>
              </div>
              <div class="goods-type">
                <div class="label">
                  商品类型：<span class="type">{{ item.productType }}</span>
                </div>
              </div>
              <div class="content">
                <div class="label">
                  商品总数：<span class="number">{{ item.totalNum }}</span>
                </div>
              </div>
              <div class="audit-information">
                <div class="label">
                  审核信息：<span class="information">{{
                    item.audit == 1 ? '需要完成下单方审核鲜花实拍图' : '审核'
                  }}</span>
                </div>
              </div>
              <div class="order-description">
                <div class="label">
                  订单描述：<span class="description">{{ item.remark }}</span>
                </div>
              </div>
            </div>
            <div class="submit-box">
              <placerBtn :goodsinfo="item" />
            </div>
          </div>
        </div>
      </div>
      <el-empty v-if="!orderList.length" description="无数据" style="background-color: #fff" />
      <div class="page">
        <div style="display: flex; justify-content: center">
          <el-pagination
            @current-change="currentChange"
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pages.pageSize"
          />
        </div>
        <div class="txt">为了提高查询效率，仅显示近期订单</div>
      </div>
    </div>
  </div>
  <delivery-map v-if="isMapFlog" @closeChange="closeChangeEvent" :goodsinfo="goodsInfo"></delivery-map>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import { CaretTop, CaretBottom, MapLocation } from '@element-plus/icons-vue'
import { useCounterStore } from '@/stores/nav'
//@ts-ignore
import { regionData, CodeToText } from 'element-china-area-data' // 地址数据
import { getReceiveOrderList } from '@/server/orderApi'
import { linkNavigateTo } from '~/utils/util'

const userIndex = useCounterStore()
onMounted(() => {
  userIndex.increment(4)
  getReceiveOrderListEvent()
})
const addressData: any = regionData // 解决地址数据报错的问题
const loading = <any>ref(false)
const priceWhel = <any>ref(['不限', '100元以下', '100-200元', '200-300元', '300-400元', '400元以上'])
const addressTime = <any>ref(['不限', '今天', '1-3天', '4-7天', '1周以上'])
const active = ref(0)
const activeSort = ref(0)
const form = <any>ref({
  address: [],
  addressInfo: '',
  max: '', // 最高价
  min: '', //最低价
  maxTime: '', // 最晚收货时间
  minTime: '', // 最早收货时间
  deliveryTimeSort: false, // 收货时间排序
  createTimeSort: false, // 下单时间排序
  priceOrder: null, // 订单金额排序
})

const pages = <any>ref({
  page: 1, // 页码
  pageSize: 3, //每条页数
})
const orderList = <any>ref([])
const currentChange = (page: any) => {
  console.log(page)
  pages.value.page = page
  getReceiveOrderListEvent()
}
// 成交价变化
const priceWhelIndex = <any>ref(0)
const priceWhelChange = (index: number) => {
  if (priceWhelIndex.value === index) return
  priceWhelIndex.value = index
  console.log(index)
  switch (index) {
    case 0:
      form.value.max = ''
      form.value.min = ''
      break
    case 1:
      form.value.max = 100
      form.value.min = 0
      break
    case 2:
      form.value.max = 200
      form.value.min = 100
      break
    case 3:
      form.value.max = 300
      form.value.min = 200
      break
    case 4:
      form.value.max = 400
      form.value.min = 300
      break
    case 5:
      form.value.max = ''
      form.value.min = 400
      break
  }
  getReceiveOrderListEvent()
}
const addressTimeIndex = <any>ref(0)
// 收货时间变化
const addressTimeChange = (index: number) => {
  if (addressTimeIndex.value === index) return
  addressTimeIndex.value = index
  console.log(index)

  switch (index) {
    case 0:
      form.value.maxTime = ''
      form.value.minTime = ''
      break
    case 1:
      form.value.maxTime = '今天'
      form.value.minTime = '今天'
      break
    case 2:
      form.value.maxTime = formatTime(3)
      form.value.minTime = formatTime()
      break
    case 3:
      form.value.maxTime = formatTime(7)
      form.value.minTime = formatTime(4)
      break
    case 4:
      form.value.maxTime = ''
      form.value.minTime = formatTime(7)
      break
  }
  getReceiveOrderListEvent()
}
const total = <any>ref(null)
const getReceiveOrderListEvent = async () => {
  // console.log(CodeToText);

  loading.value = true
  const data: any = {
    limit: pages.value.pageSize, // 每页条数
    page: pages.value.page, // 页码
    maxPrice: form.value.max, // 最大金额
    minPrice: form.value.min, // 最小金额
    minReceiveDate: form.value.minTime, // 最早收货时间
    maxReceiveDate: form.value.maxTime, // 最晚收货时间
    deliveryTimeSort: form.value.deliveryTimeSort, // 收货时间排序
    createTimeSort: form.value.createTimeSort, // 下单时间排序
    receiveAddressProvince: form.value.address.length ? CodeToText[form.value.address[0]] : '',
    receiveAddressCity: form.value.address.length ? CodeToText[form.value.address[1]] : '',
    receiveAddressDistrict: form.value.address.length ? CodeToText[form.value.address[2]] : '',
    receiveAddressDetail: form.value.addressInfo,
  }
  console.log(data, 'data')

  // 删除多余字段
  for (const key in data) {
    if (!data[key]) {
      delete data[key]
    }
  }
  if (active.value === 3) {
    data.otPrice = activeSort.value ? 'desc' : 'asc' // priceOrder:form.value.priceOrder,
  }
  const res = await getReceiveOrderList(data)
  orderList.value = res.list
  total.value = res.total
  loading.value = false
  console.log(res)
}
// 格式化时间
const formatTime = (DAY: any = 0) => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  date.setDate(day + DAY) // 设置日期对象的天数，会自动处理超出当月天数的情况
  const updatedYear = date.getFullYear()
  const updatedMonth = date.getMonth() + 1
  const updatedDay = date.getDate()
  return `${updatedYear}-${updatedMonth}-${updatedDay}`
}

// 排序
const tabSort = (index: any) => {
  if (active.value === index) return
  active.value = index
  switch (index) {
    case 0:
      form.value.deliveryTimeSort = false
      form.value.createTimeSort = false
      break
    case 1:
      form.value.deliveryTimeSort = true
      form.value.createTimeSort = false
      break
    case 2:
      form.value.deliveryTimeSort = false
      form.value.createTimeSort = true
      break
    case 3:
      form.value.deliveryTimeSort = false
      form.value.createTimeSort = false
      break
  }
  getReceiveOrderListEvent()
}
const priceSort = (index: any) => {
  // form.value.priceOrder = 'asc' : form.value.priceOrder = 'desc'
  activeSort.value = index
  getReceiveOrderListEvent()
}
// 搜索订单
const searchOrder = () => {
  getReceiveOrderListEvent()
  console.log(form.value)
}
// 前往详情页
const goToOrderInfo = (id: any) => {
  console.log(id)
  linkNavigateTo('/homeIndex/orderdetails', { GoodsId: id })
}
// 接单
import { merchantOffers } from '@/server/orderApi'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const submitEvent = async (monry: any, orderNo: any) => {
  const data: any = {
    merId: userStore.$state.userInfos.id,
    offerAmount: monry,
    orderNo: orderNo,
  }
  console.log(data)
  const res = await merchantOffers(data)
}
// 报价
import { ElMessage, ElMessageBox } from 'element-plus'
const instantlyQuote = async (monry: any, orderNo: any) => {
  ElMessageBox.prompt('请输入金额', 'Tip', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /^(?!$)(?=^[0-9]{1,6}$)(?!^0+$)^[1-9][0-9]{0,4}$|100000$/,
    inputErrorMessage: '请输入正确的金额',
  })
    .then(({ value }) => {
      if (value <= monry) {
        return ElMessage({
          type: 'error',
          message: `涨价金额不能小于当前金额`,
        })
      }
      const data: any = {
        merId: userStore.$state.userInfos.id,
        offerAmount: value,
        orderNo: orderNo,
      }
      console.log(data)
      merchantOffers(data)
      ElMessage({
        type: 'success',
        message: `请求成功`,
      })
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Input canceled',
      // })
    })
}
const isMapFlog = <any>ref(false)
const goodsInfo = <any>ref({})
const showMap = (item: any) => {
  goodsInfo.value = item
  isMapFlog.value = true
}
const closeChangeEvent = (e: boolean) => {
  isMapFlog.value = e
}
// 计算时间
const setTimeOutEvent = (date: any, time: any) => {
  // console.log(date,time,'deliveryTime');
  if (time == '不限时段') {
    time = '23:00'
  }
  const strTime = `${date} ${time}`
  // console.log(strTime)

  var currentTime = new Date()
  var deliveryDate = new Date(strTime)

  var difference = deliveryDate.getTime() - currentTime.getTime()
  // console.log(difference, deliveryDate)

  if (difference <= 0) {
    return '已过期'
  }

  var days = Math.floor(difference / (1000 * 60 * 60 * 24))
  difference -= days * (1000 * 60 * 60 * 24)

  var hours = Math.floor(difference / (1000 * 60 * 60))
  difference -= hours * (1000 * 60 * 60)

  var minutes = Math.floor(difference / (1000 * 60))
  difference -= minutes * (1000 * 60)

  // console.log(days, hours, minutes, seconds)
  if (days) {
    return `${days}天`
  } else if (hours) {
    return `${hours}小时`
  } else {
    ;`${minutes}分钟`
  }
}
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  .banner {
    width: 6.25rem;
    margin: 0 auto;
    .order-information {
      width: 100%;
      // height: 3.4896rem;
      margin-top: 0.026rem;
      background-color: #fff;
      .header {
        // background-color: #f3f4f8;
        height: 0.2083rem;
        color: #252b3a;
        font-size: 0.0833rem;
        line-height: 0.2083rem;
        padding: 0 0.2604rem;
        display: flex;
        align-items: center;
        font-weight: 700;
        border-bottom: 1px solid #e1e1e3;
      }
      .header::before {
        content: ' ';
        display: block;
        background-color: #ff4e8d;
        width: 0.0156rem;
        height: 0.0833rem;
        margin-right: 0.026rem;
      }
      .condition-scarch {
        padding: 0.1042rem 0.3542rem;
        ul {
          li {
            list-style: none;
            display: flex;
            align-items: center;
            color: #252b3a;
            font-size: 0.0729rem;
            margin: 0.1042rem 0;
            .label {
              width: 0.3646rem;
              text-align: right;
            }
            .search-btn {
              width: 0.4167rem;
              height: 0.1771rem;
              color: #fff;
              text-align: center;
              font-size: 0.0729rem;
              line-height: 0.1771rem;
              border-radius: 0.1042rem;
              background: linear-gradient(90deg, #ff94d4 0%, #ffddbe 100%);
              margin-left: 0.0521rem;
              cursor: pointer;
            }
            .price-whel {
              display: flex;
              align-items: center;
              div {
                margin-right: 0.2135rem;
                cursor: pointer;
              }
              .active {
                color: #ff4e8d;
              }
              // div:focus,
              // div:hover {
              //   color: #ff4e8d;
              // }
            }
          }
        }
      }
    }
    .tabs {
      width: 100%;
      height: 0.2083rem;
      background-color: #fff;
      display: flex;
      margin-top: 0.2344rem;
      margin-bottom: 0.1302rem;
      .standard {
        width: 0.7292rem;
        height: 100%;
        color: #252b3a;
        font-size: 0.0729rem;
        text-align: center;
        line-height: 0.2083rem;
        border-radius: 0.0313rem;
        cursor: pointer;
      }
      .active {
        color: #fff;
        background: linear-gradient(90deg, #ff94d4 0%, #ffddbe 100%);
      }
      .sort {
        display: flex;
        justify-content: center;
        .sort-box {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-left: 0.0365rem;
          color: #b1b6c1;
          div {
            line-height: 0;
            display: inline-block;
          }
          .active-sort {
            color: #fff;
          }
          .descending {
            margin-top: -5px;
          }
        }
      }
    }
    .line-items {
      margin-top: 0.1719rem;
      .item {
        position: relative;
        padding: 0.1198rem 0.1771rem;
        background-color: #fff;
        margin: 0.0521rem 0;
        .header {
          display: flex;
          align-items: center;
          .address {
            width: 2.8125rem;
            color: #252b3a;
            font-size: 0.0833rem;
            font-weight: 600;
            overflow: hidden; /* 隐藏溢出的部分 */
            white-space: nowrap; /* 将文本折叠成单行 */
            text-overflow: ellipsis; /* 添加省略号 */
          }
          .time {
            color: #8a8e99;
            font-size: 0.0625rem;
          }
          .map-box {
            display: flex;
            color: #ff4e8d;
            margin-right: 0.0521rem;
            cursor: pointer;
          }
        }
        .order-info {
          display: flex;
          width: 100%;
          padding: 0.0781rem 0 0 0.0521rem;
          .image {
            width: 0.7292rem;
            height: 0.7292rem;
            background-color: #d9d9d9;
            position: relative;
            .tag {
              position: absolute;
              bottom: 0;
              width: 100%;
              height: 0.125rem;
              color: #fff;
              text-align: center;
              line-height: 0.125rem;
              background: linear-gradient(90deg, #ff94d4 0%, #ffddbe 100%);
            }
          }
          .iine-info {
            // width: 4.1667rem;
            margin-left: 0.0521rem;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            .label {
              color: #8a8e99;
              font-size: 0.0625rem;
            }
            .receipt-time {
              .time {
                color: #ff4e8d;
                font-size: 0.0729rem;
                font-weight: 600;
                margin-right: 0.1042rem;
              }
            }
            .goods-type {
              .type {
                color: #252b3a;
              }
            }
            .content {
              .number {
                color: #ff4e8d;
                font-size: 0.0729rem;
                font-weight: 600;
              }
            }
            .audit-information {
              .information {
                color: #252b3a;
              }
            }
            .order-description {
              .description {
                color: #252b3a;
              }
            }
          }
          .submit-box {
            position: absolute;
            right: .1563rem;
            bottom: .1563rem;
            // height: 100%;
            display: flex;
            // flex-direction: column;
            align-items: end;
            margin-left: 0.2604rem;
            .submit {
              width: 0.5833rem;
              height: 0.1667rem;
              color: #fff;
              margin: 0 10px;
              text-align: center;
              line-height: 0.1667rem;
              background: linear-gradient(90deg, #ff94d4 0%, #ffddbe 100%);
            }
            .submit-tow {
              width: 0.5833rem;
              height: 0.1667rem;
              color: #ff94d4;
              margin: 0 10px;
              text-align: center;
              line-height: 0.1667rem;
              border: 1px solid #ff94d4;
              // background: linear-gradient(90deg, #ff94d4 0%, #ffddbe 100%);
            }
          }
        }
      }
    }
    .page {
      height: 1.0417rem;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-content: center;
      .txt {
        text-align: center;
        color: #252b3a;
        margin-top: 0.1563rem;
      }
    }
  }
}
</style>
