<script lang="ts" setup>

import { useFormGroup } from '@idux/cdk'
import { TableColumn } from '@idux/components/table'
import { TablePagination } from '@idux/components/table/src/types'
import Charts from '@/components/echarts/Charts.vue'
import DisposeRecodeDetail from '@/pages/dispose-recode/DisposeRecodeDetail.vue'
import DisposeRecodeApi from '@/pages/dispose-recode/dispose-recode-api.ts'
import Times from '@/common/utils/times.ts'

const disposeRecodeDetail = ref<InstanceType<typeof DisposeRecodeDetail> | null>(null)
const disposeRecode = ref<HTMLElement | undefined>(undefined)
const chartOption = reactive<Echarts.Option>({
  aria: {
    enabled: true,
    decal: {
      show: true
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    show: true,
    top: 0,
  },
  grid: {
    outerBounds: {
      left: 0,
      right: 0,
      bottom: 0,
      top: 0
    }
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  yAxis: [
    {
      axisLine: {
        show: true
      },
      type: 'value'
    }
  ],
  series: []
})

const formGroup = useFormGroup<DisposeRecodeTypes.SearchParam>({
  keywords: [ '' ],
})

const datasource = ref<DisposeRecodeTypes.DisposeRecodeData[]>()
const columns: TableColumn[] = [
  {
    title: '来源地',
    dataKey: 'origin',
  },
  {
    title: '清运公司',
    dataKey: 'clearingCompany',
  },
  {
    title: '消纳场名称',
    dataKey: 'disposalSite',
  },
  {
    title: '车牌号',
    dataKey: 'licensePlate',
  },
  {
    title: '联系人',
    dataKey: 'contact',
  },
  {
    title: '联系电话',
    dataKey: 'contactPhone',
  },
  {
    title: '进场磅重（吨）',
    dataKey: 'inWeight',
  },
  {
    title: '出场磅重（吨）',
    dataKey: 'outWeight',
  },
  {
    title: '净重（吨）',
    dataKey: 'suttleWeight',
  },
  {
    title: '进场时间',
    dataKey: 'inTime',
  },
  {
    title: '出场时间',
    dataKey: 'outTime',
  },
  {
    title: '操作',
    key: 'action',
    customCell: 'action',
  }
]

const pagination = reactive<TablePagination>({
  pageIndex: 1,
  pageSize: 3,
  total: 100,
  size: 'sm',
  showTotal: true,
  onChange(pageIndex: number, pageSize: number) {
    pagination.pageIndex = pageIndex
    pagination.pageSize = pageSize
    searchHandler()
  }
})

const tableSpin = ref(false)

function searchHandler() {
  tableSpin.value = true
  DisposeRecodeApi.paging({
    ...formGroup.getValue(),
    current: pagination.pageIndex ?? 1,
    size: pagination.pageSize ?? 10,
  })
      .then(res => {
        pagination.pageIndex = res.data.current
        pagination.pageSize = res.data.size
        pagination.total = res.data.total
        datasource.value = res.data.records
      })
      .finally(() => {
        tableSpin.value = false
      })
}

function exportHandler() {
  DisposeRecodeApi.exportData([ '2025-01-01', '2025-01-31' ])
}

const monthValue = ref<Date>(new Date())

function renderChart() {
  DisposeRecodeApi.statistics(Times.format(monthValue.value, Times.FMT.month))
      .then(res => {
        chartOption.xAxis[0].data = res.data.xAxis
        let series = []
        for (let seriesKey in res.data.series) {
          series.push({
            name: seriesKey,
            type: 'bar',
            data: res.data.series[seriesKey],
          })
        }
        chartOption.series = series
      })
}

onMounted(() => {
  searchHandler()
  renderChart()
})
</script>

<template>
  <div ref="disposeRecode" class="dispose-recode">
    <div class="title">垃圾处置记录</div>
    <div class="desc">管理和分析垃圾处置数据</div>
    <IxCard class="graph-card">
      <template #header>
        <div class="graph-tool">
          <div>垃圾处置量统计</div>
          <IxDatePicker v-model:value="monthValue" type="month" @change="renderChart"/>
        </div>
      </template>
      <Charts :option="chartOption"/>
    </IxCard>
    <IxCard class="table-card">
      <template #header>
        <div class="table-tool">
          <div>垃圾处置记录</div>
          <IxForm :control="formGroup" class="search-form" layout="inline" @submit.prevent="searchHandler">
            <IxTooltip placement="top" title="输入内容回车搜索">
              <IxFormItem messageTooltip>
                <IxInput clearable control="keywords" placeholder="请输入" @clear="searchHandler"/>
              </IxFormItem>
            </IxTooltip>
            <IxFormItem messageTooltip>
              <IxButton icon="search" mode="primary" type="submit"/>
            </IxFormItem>
          </IxForm>
          <IxButton icon="download" mode="primary" @click="exportHandler">导出</IxButton>
        </div>
      </template>
      <IxTable :columns="columns" :dataSource="datasource" :pagination="pagination" autoHeight class="data-table" getKey="id">
        <template #action="{record}">
          <IxButton class="detail-btn" icon="eye" mode="text" @click="disposeRecodeDetail?.open(record)">查看</IxButton>
        </template>
      </IxTable>
    </IxCard>
    <DisposeRecodeDetail ref="disposeRecodeDetail" :container="disposeRecode"/>
  </div>
</template>

<style lang="stylus" scoped>
.dispose-recode {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;

  .title {
    font-size: 1.75rem;
    font-weight bold
    color #1F2937
  }

  .desc {
    color #687280
    margin-top 1rem
  }

  .graph-card {
    padding 0 1rem
    margin 1rem 0
    flex 1
    display flex
    flex-direction column

    .graph-tool {
      display: flex;
      justify-content: space-between;
      align-items center
      padding 1rem
      border-bottom 1px solid #E5E7EB

      & > div:nth-child(1) {
        flex 9
        color #1D2129
        font-weight 600
        font-size 1.25rem
      }

      & > :deep(.ix-date-picker):nth-child(2) {
        flex 1
        display flex
      }
    }

    & > :deep(.ix-card-body) {
      flex 1
      width 100%

      & > div:first-child {
        height: 100%;
        width 100%;
      }
    }
  }


  .table-card {
    display flex
    flex-direction column
    flex 1
    padding 1rem

    .table-tool {
      display: flex;
      justify-content: space-between;
      align-items center
      padding 1rem
      border-bottom 1px solid #E5E7EB

      & > div:nth-child(1) {
        flex 17
        color #1D2129
        font-weight 600
        font-size 1.25rem
      }


      .search-form {
        flex 6

        :deep(.ix-form-item):nth-child(1) {
          flex 7
        }

        :deep(.ix-form-item):nth-child(2) {
          flex 1
        }
      }

      & > :deep(.ix-button ) {
        flex 1
      }
    }

    & > :deep(.ix-card-body) {
      flex 1
      padding 0
    }

    .data-table {
      :deep(.ix-table-thead .ix-table-cell) {
        color: #6B7280
        background-color: #F9FAFB
        font-weight 500
      }

      :deep(.ix-table-thead th:not(:last-child))::before {
        width 0;
      }

      .detail-btn {
        color var(--ix-button-primary-bg-color)
      }
    }
  }

}
</style>
