<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Danh sách khách hàng cần đối soát cước</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Đối soát cước</a></li>
          <li class="breadcrumb-item active" aria-current="page">Khách hàng cần đối soát</li>
        </ol>
      </div>
    </div>
    <div class="row row-sm">

      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <!-- Search Card -->
        <div class="card card-search shadow-none">
          <form class="card-body" @submit.prevent="searchRefresh">
            <div class="row">
              <div class="col-lg-4 col-md-4 mb-3">
                <label>Tìm kiếm khách hàng</label>
                <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                  placeholder="Tên khách hàng hoặc số điện thoại..." />
              </div>
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Ngày tạo đơn</label>
                <VueDatePicker ref="createDatePicker" v-model="date" :enable-time-picker="false" range multi-calendars
                  auto-apply :format="format" @update:model-value="handleDate">
                  <template #left-sidebar>
                    <LeftSidebar @change-date="onChangeDate"></LeftSidebar>
                  </template>
                </VueDatePicker>
              </div>
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Mức ưu tiên</label>
                <v-select label="Name" :options="priorityOptions" v-model="searchModel.Search.PredicateObject.Priority"
                  :reduce="(option) => option.Id"></v-select>
              </div>
            </div>
            <div class="row">
              <div class="col-lg mb-3">
                <button type="submit" class="btn btn-dark" :disabled="loading">
                  <i v-show="!loading" class="fe fe-search"></i>
                  <span v-show="loading" class="spinner-border spinner-border-sm"></span>
                  <span>Tìm kiếm</span>
                </button>
              </div>
            </div>
          </form>
        </div>

        <!-- Results Card -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body">
            <div class="table-responsive border-top mg-b-10">
              <table class="table table-vcenter mb-0" style="min-height:300px">
                <thead>
                  <tr>
                    <th class="wd-lg-20p min-width-1"><span>Thông tin khách hàng</span></th>
                    <th class="wd-lg-10p min-width-1 text-center"><span>Số đơn</span></th>
                    <th class="wd-lg-15p min-width-1 text-end"><span>Tổng cước</span></th>
                    <th class="wd-lg-10p min-width-1 text-end"><span>Phí dự kiến</span></th>
                    <th class="wd-lg-15p min-width-1 text-end"><span>Tiền thực chuyển</span></th>
                    <th class="wd-lg-10p min-width-1 text-center"><span>Mức ưu tiên</span></th>
                    <th class="wd-lg-10p min-width-1 text-center"><span>Ngày cũ nhất</span></th>
                    <th class="wd-lg-10p"></th>
                  </tr>
                </thead>
                <tbody v-if="loading">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-default">
                      <span class="spinner-border spinner-border-sm"></span>
                    </td>
                  </tr>
                </tbody>
                <tbody v-if="!loading && items.length <= 0">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-danger">
                      Không tìm thấy bản ghi nào!
                    </td>
                  </tr>
                </tbody>
                <tbody v-if="!loading && items.length > 0" class="tx-13">
                  <tr v-for="item in items" :key="item.CustomerId">
                    <!-- Thông tin khách hàng -->
                    <td class="text-wrap align-top">
                      <div>
                        <div class="fw-semibold">{{ item.CustomerName }}</div>
                        <div class="text-muted tx-12">
                          <i class="fe fe-phone me-1"></i>{{ item.CustomerPhone }}
                        </div>
                        <div class="text-muted tx-12" v-if="item.CustomerEmail">
                          <i class="fe fe-mail me-1"></i>{{ item.CustomerEmail }}
                        </div>
                        <div v-if="item.HasDefaultBankAccount" class="text-success tx-12">
                          <i class="fe fe-credit-card me-1"></i>{{ item.DefaultBankAccountInfo }}
                        </div>
                      </div>
                    </td>

                    <!-- Số đơn -->
                    <td class="text-center align-top">
                      <span class="tag tag-blue">{{ item.PendingOrderCount }}</span>
                    </td>

                    <!-- Tổng cước -->
                    <td class="text-end align-top">
                      <span class="fw-semibold">{{ formatCurrency(item.PendingShippingFeeAmount) }}</span>
                    </td>

                    <!-- Phí dự kiến -->
                    <td class="text-end align-top">
                      <span class="text-warning">{{ formatCurrency(item.EstimatedFeeAmount) }}</span>
                    </td>

                    <!-- Tiền thực chuyển -->
                    <td class="text-end align-top">
                      <span class="fw-semibold text-success">{{ formatCurrency(item.EstimatedNetAmount) }}</span>
                    </td>

                    <!-- Mức ưu tiên -->
                    <td class="text-center align-top">
                      <span :class="getPriorityTagClass(item.PriorityColor)">
                        {{ item.PriorityStr }}
                      </span>
                    </td>

                    <!-- Ngày cũ nhất -->
                    <td class="text-center align-top">
                      <span class="text-muted tx-12">{{ formatDate(item.OldestOrderDate) }}</span>
                    </td>

                    <!-- Thao tác -->
                    <td class="align-top pt-2">
                      <button v-if="item.CanCreateReconciliation" type="button" class="btn btn-sm btn-primary"
                        @click="createReconciliation(item)" :disabled="loading">
                        <i class="fe fe-plus me-1"></i>
                        Tạo đối soát
                      </button>
                      <span v-else class="text-muted tx-12">
                        <i>Không thể tạo đối soát</i>
                      </span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <pager ref="ctrlPager" v-show="!loading && items.length > 0" @PageSizeChanged="PageSizeChanged"
              @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total" :TotalCurrent="items.length">
            </pager>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import reconciliationService from '@/services/reconciliationService'
import { ReconciliationType } from '@/infrastructure/utilities/reconciliationConstants'
import LeftSidebar from "@/components/daterange/left-sidebar.vue"
import DatepickerInstance from "@vuepic/vue-datepicker"

const router = useRouter()
const toast = useToast()

// Reactive data
const loading = ref(false)
const items = reactive([])
const date = ref()
const createDatePicker = ref(DatepickerInstance)

const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 25
  },
  Sort: {
    Predicate: '',
    Reverse: true
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      CreatedStart: null,
      CreatedEnd: null,
      Priority: null
    }
  }
})

const priorityOptions = reactive([
  { Id: null, Name: "Tất cả" },
  { Id: 1, Name: "Thấp" },
  { Id: 2, Name: "Trung bình" },
  { Id: 3, Name: "Cao" }
])

const ctrlPager = ref()

// Methods
const formatCurrency = (amount) => {
  if (!amount) return '0 ₫'
  return new Intl.NumberFormat('vi-VN', {
    style: 'currency',
    currency: 'VND'
  }).format(amount)
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('vi-VN')
}

const getPriorityTagClass = (color) => {
  const colorMap = {
    'red': 'tag tag-red',
    'orange': 'tag tag-orange',
    'green': 'tag tag-green',
    'blue': 'tag tag-blue'
  }
  return colorMap[color] || 'tag tag-gray'
}

const createReconciliation = (customer) => {
  router.push({
    name: 'create-shipping-fee-reconciliation-for-customer',
    params: { customerId: customer.CustomerId }
  })
}

async function searchRefresh() {
  searchModel.Pagination.PageIndex = 1
  ctrlPager.value.Refresh()
  search()
}

async function search() {
  loading.value = true
  items.splice(0, items.length)

  try {
    const searchResult = await reconciliationService.getCustomersForReconciliation(searchModel, ReconciliationType.ShippingFee)
    if (searchResult.Items != null && searchResult.Items.length > 0) {
      searchResult.Items.forEach(customer => {
        items.push(customer)
      })
    }
    searchModel.Pagination.Total = searchResult.TotalRecord
  } catch (error) {
    console.error('Error loading customers:', error)
    toast.error('Có lỗi xảy ra khi tải danh sách khách hàng')
  } finally {
    loading.value = false
  }
}

function PageSizeChanged(pagesize) {
  searchModel.Pagination.PageSize = pagesize
  searchModel.Pagination.PageIndex = 1
  search()
}

function PageIndexChanged(pageIndex) {
  searchModel.Pagination.PageIndex = pageIndex
  search()
}

const format = (dates) => {
  let start = dates[0]
  let end = dates[1]
  const dayStart = start.getDate()
  const monthStart = start.getMonth() + 1
  const yearStart = start.getFullYear()
  const dayEnd = end.getDate()
  const monthEnd = end.getMonth() + 1
  const yearEnd = end.getFullYear()

  return `${dayStart}/${monthStart}/${yearStart} - ${dayEnd}/${monthEnd}/${yearEnd}`
}

async function onChangeDate(newDates) {
  date.value = newDates
  createDatePicker.value.closeMenu()
  handleDate(newDates)
}

function handleDate(modelData) {
  if (modelData != null) {
    searchModel.Search.PredicateObject.CreatedStart = modelData[0]
    searchModel.Search.PredicateObject.CreatedEnd = modelData[1]
  } else {
    searchModel.Search.PredicateObject.CreatedStart = null
    searchModel.Search.PredicateObject.CreatedEnd = null
  }
}

onMounted(() => {
  search()
})
</script>

<style scoped>
.table th {
  border-top: none;
  font-weight: 600;
  color: #495057;
}

.tag {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
  font-weight: 500;
  line-height: 1;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
  border-radius: 0.25rem;
}

.tag-red {
  color: #fff;
  background-color: #dc3545;
}

.tag-orange {
  color: #fff;
  background-color: #fd7e14;
}

.tag-green {
  color: #fff;
  background-color: #198754;
}

.tag-blue {
  color: #fff;
  background-color: #0d6efd;
}

.tag-gray {
  color: #fff;
  background-color: #6c757d;
}

.badge {
  font-size: 0.75rem;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.spinner-border {
  width: 2rem;
  height: 2rem;
}
</style>
