<template>
  <div>
    <el-row :gutter="24">
      <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">
        <vab-query-form style="float: right">
          <vab-query-form-right-panel :span="24">
            <el-form :inline="true" :model="queryForm" @submit.prevent>
              <el-form-item class="ml10">
                <ms-date-range-picker
                  v-model="order_time_range"
                  @update:modelValue="order_time_range = $event"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  icon="el-icon-search"
                  type="primary"
                  @click="fetchData"
                >
                  {{ __('查询') }}
                </el-button>
              </el-form-item>
            </el-form>
          </vab-query-form-right-panel>
        </vab-query-form>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
        <top-num
          background="white"
          :bottom-text="__('商品数量')"
          :count-config="productNumConfig"
          icon="product-hunt-line"
          :title="__('商品数量')"
          :unit-text="__('个')"
        />
      </el-col>
      <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
        <top-num
          background="white"
          :bottom-text="__('商品访客数')"
          :count-config="visitsUserConfig"
          icon="user-4-line"
          :title="__('商品访客数')"
          :unit-text="__('人')"
        />
      </el-col>
      <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
        <top-num
          background="white"
          :bottom-text="__('商品销量')"
          :count-config="orderItemNumConfig"
          icon="numbers-line"
          :title="__('商品销量')"
          :unit-text="__('个')"
        />
      </el-col>
      <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24">
        <top-num
          background="white"
          :bottom-text="__('商品浏览量')"
          :count-config="accessItemNumConfig"
          icon="user-search-line"
          :title="__('商品浏览量')"
          :unit-text="__('PV')"
        />
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <el-card v-loading="loading" class="box-card">
            <template #header>
              <vab-icon icon="layout-grid-line" />
              {{ __('商品统计') }}
              <el-radio-group
                v-model="interviewTime"
                class="radio-inline"
                size="small"
                style="float: right"
                @change="getAccessItemUserTimeLineFunEvt"
              >
                <el-radio-button :label="7">{{ __('7天') }}</el-radio-button>
                <el-radio-button :label="30">{{ __('30天') }}</el-radio-button>
                <el-radio-button :label="90">{{ __('3个月') }}</el-radio-button>
                <el-radio-button :label="180">{{ __('半年') }}</el-radio-button>
              </el-radio-group>
            </template>
            <ms-chart
              :init-options="initOptions"
              :option="accessItemUserTimeLineOption"
              style="width: 100%"
              theme="ms-echarts-theme"
            />
          </el-card>
        </div>
      </el-col>
    </el-row>

    <div class="order-info-container" style="background: #fff; padding: 20px">
      <vab-query-form>
        <vab-query-form-right-panel :span="24">
          <el-form :inline="true" :model="queryForm" @submit.native.prevent>
            <el-form-item>
              <Area v-model="queryArea" :clearable="true" />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="queryForm.product_name"
                clearable
                :placeholder="__('请输入商品名字')"
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="queryForm.product_id"
                clearable
                :placeholder="__('请输入产品SPU编码')"
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item>
              <div class="block">
                <el-date-picker
                  v-model="queryForm.order_st_time"
                  :placeholder="__('开始时间')"
                  style="width: 120px"
                  type="date"
                  value-format=" yyyy-MM-dd"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <div class="block">
                <el-date-picker
                  v-model="queryForm.order_ed_time"
                  :placeholder="__('截止时间')"
                  style="width: 120px"
                  type="date"
                  value-format=" yyyy-MM-dd"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <tree-select
                ref="treeSelect"
                :checked-keys="defaultCheckedKeys"
                clearable
                :data="data"
                :default-props="defaultProps"
                :height="300"
                :node-key="nodeKey"
                :placeholder="__('截止时间')"
                size="small"
                style="width: 160px"
                :width="100"
                @change="change"
              />
            </el-form-item>
            <el-form-item v-if="false">
              <el-input
                v-model.trim="queryForm.da_address"
                clearable
                :placeholder="__('请输入地址')"
                style="width: 100px"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                icon="el-icon-search"
                type="primary"
                @click="queryData"
              >
                {{ __('查询') }}
              </el-button>

              <el-button
                v-if="false"
                icon="el-icon-search"
                :type="getBntType(1)"
                @click="theDay(1)"
              >
                {{ __('全部') }}
              </el-button>
              <el-button
                icon="el-icon-search"
                :type="getBntType(2)"
                @click="theDay(2)"
              >
                {{ __('当天') }}
              </el-button>
              <el-button
                v-if="false"
                icon="el-icon-search"
                :type="getBntType(3)"
                @click="theDay(3)"
              >
                {{ __('本周') }}
              </el-button>
              <el-button
                icon="el-icon-search"
                :type="getBntType(4)"
                @click="theDay(4)"
              >
                {{ __('本月') }}
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-right-panel>
      </vab-query-form>

      <el-table
        v-loading="listLoading"
        border
        :data="list"
        :height="tableConfig.height"
      >
        <el-table-column
          align="center"
          :label="__('货品编号')"
          prop="item_id"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          :label="__('商品图片')"
          prop="order_item_image"
          show-overflow-tooltip
          width="150px"
        >
          <template slot-scope="scope">
            <el-image
              v-show="scope.row.order_item_image"
              :preview-src-list="[scope.row.order_item_image]"
              :src="scope.row.order_item_image"
              style="width: 35px; height: 35px"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="__('商品名称')"
          prop="item_name"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          :label="__('商品价格单价')"
          prop="item_unit_price"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          :label="__('销售数量')"
          prop="item_total"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <el-button type="text" @click="showTable(row, selectBntIndex)">
              <h2>{{ row.item_total }}</h2>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="queryForm.pageNum"
        :layout="layout"
        :page-size="queryForm.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
      <edit ref="edit" @fetch-data="fetchData" />
      <alyticsTable ref="alyticsTable" />
    </div>
  </div>
</template>

<script>
import { translateTitle as __ } from '@/utils/i18n'

import { getList } from '@/api/order/info'
import Edit from './components/OrderInfoEdit'
import Area from '@/components/VabArea/area'
import TreeSelect from '@/components/treeSelect'
import { getTree } from '@/api/base/product/category'
import alyticsTable from './components/AnalyticsTable'
import TopNum from '@/components/MsWidget/TopNum'
import MsDateRangePicker from '@/components/MsDateRangePicker'
import MsChart from '@/extra/VabChart'

import {
  getAccessItemTimeLine,
  getAccessItemUserTimeLine,
  getAccessItemNum,
  getAccessItemUserNum,
  listAccessItem,
} from '@/api/analytics/access/history'

import {
  getOrderItemNumTimeLine,
  listOrderItemNum,
  getOrderItemNum,
} from '@/api/analytics/order'
import { getProductNum } from '@/api/analytics/product'

import moment from 'dayjs'
import { formatTimeLine, formatTimeLineRange } from '@/utils'

export default {
  name: 'OrderInfo',
  components: {
    Edit,
    Area,
    TreeSelect,
    alyticsTable,
    TopNum,
    MsDateRangePicker,
    MsChart,
  },
  data() {
    return {
      tableConfig: {
        height: window.innerHeight - 220 - 90,
      },
      selectBntIndex: 1,
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      nodeKey: 'id',
      list: [],
      data: [], // 产品规格数据
      defaultCheckedKeys: [],
      value1: '',
      queryArea: {
        province: {},
        city: {},
        district: {},
      },
      listLoading: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      order_time_range: ['', ''],
      queryForm: {
        pageNo: 1,
        pageSize: 20,
        intraday_id: 1,
      },

      interviewTime: 7,
      productNumConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
        //month : 10,
      },
      visitsUserConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      accessItemNumConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      orderItemNumConfig: {
        startVal: 0,
        endVal: 0,
        decimals: 0,
        prefix: '',
        suffix: '',
        separator: ',',
        duration: 8000,

        today: 0,
        yestoday: 0,
        daym2m: 0,
      },
      accessItemUserTimeLineOption: {
        tooltip: { trigger: 'axis' },
        legend: { data: ['商品浏览量', '商品访客数', '商品销量'] },
        grid: { right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', boundaryGap: false, data: [] },
        yAxis: { type: 'value' },
        series: [
          { name: '商品浏览量', type: 'line', data: [] },
          { name: '商品访客数', type: 'line', data: [] },
          { name: '商品销量', type: 'line', data: [] },
        ],
      },
      columnLoading: false,
      polylineLoading: false,
      loading: false,
      initOptions: { renderer: 'svg' },
      itemList: [],
      itemAccessList: [],
      listAccessLoading: true,
      selectRows: '',
      userList: [],
      queryAccessForm: {
        item_id: '',
        stime: '',
        etime: '',
      },
    }
  },
  created() {
    this.fetchData()
    this.getTree()
  },
  methods: {
    __,
    test(ev) {
      this.order_time_range = ev
      console.info(ev)
    },
    async getAccessItemUserTimeLineFunRange(timeRange) {
      this.loading = true
      const params = { stime: timeRange.stime, etime: timeRange.etime }
      const { data } = await getAccessItemUserTimeLine(params)
      formatTimeLineRange(data, timeRange.days, timeRange.etime)
      const { data: accessData } = await getAccessItemTimeLine(params)
      formatTimeLineRange(accessData, timeRange.days, timeRange.etime)
      const { data: itemData } = await getOrderItemNumTimeLine(params)
      formatTimeLineRange(itemData, timeRange.days, timeRange.etime)
      this.accessItemUserTimeLineOption.xAxis.data = data.map(
        (item) => item.time
      )
      this.accessItemUserTimeLineOption.series[0].data = accessData.map(
        (item) => item.num
      )
      this.accessItemUserTimeLineOption.series[1].data = data.map(
        (item) => item.num
      )
      this.accessItemUserTimeLineOption.series[2].data = itemData.map(
        (item) => item.num
      )
      this.loading = false
    },
    async getProductNumFun(params) {
      const { data } = await getProductNum(params)
      data.today = data.current
      data.yestoday = data.pre
      Object.assign(this.productNumConfig, data)
    },
    async getAccessItemNumFun(params) {
      const { data } = await getAccessItemNum(params)
      data.today = data.current
      data.yestoday = data.pre
      Object.assign(this.accessItemNumConfig, data)
    },
    async getAccessItemUserNumFun(params) {
      const { data } = await getAccessItemUserNum(params)
      data.today = data.current
      data.yestoday = data.pre
      Object.assign(this.visitsUserConfig, data)
    },
    async getOrderItemNumFun(params) {
      const { data } = await getOrderItemNum(params)
      data.today = data.current
      data.yestoday = data.pre
      Object.assign(this.orderItemNumConfig, data)
    },
    async getAccessItemUserTimeLineFunEvt() {
      console.info(this.interviewTime)
      await this.getAccessItemUserTimeLineFun(parseInt(this.interviewTime))
    },
    async getAccessItemUserTimeLineFun(days) {
      this.loading = true
      const start = new Date(
        moment(
          moment()
            .subtract(days - 1, 'days')
            .format('YYYY-MM-DD')
        )
      )
      const end = new Date()

      const params = { stime: start.getTime(), etime: end.getTime() }

      console.info(params)

      const { data } = await getAccessItemUserTimeLine(params)
      formatTimeLine(data, days)
      const { data: accessData } = await getAccessItemTimeLine(params)
      formatTimeLine(accessData, days)
      const { data: itemData } = await getOrderItemNumTimeLine(params)
      formatTimeLine(itemData, days)
      this.accessItemUserTimeLineOption.xAxis.data = data.map(
        (item) => item.time
      )
      this.accessItemUserTimeLineOption.series[0].data = accessData.map(
        (item) => item.num
      )
      this.accessItemUserTimeLineOption.series[1].data = data.map(
        (item) => item.num
      )
      this.accessItemUserTimeLineOption.series[2].data = itemData.map(
        (item) => item.num
      )
      this.loading = false
    },
    async listOrderItemNumFun() {
      if (this.order_time_range.length > 0) {
        if (this.order_time_range[0]) {
          this.queryForm.stime = this.order_time_range[0].getTime()
        }
        if (this.order_time_range[1]) {
          this.queryForm.etime = this.order_time_range[1].getTime()
        }
      } else {
        this.queryForm.stime = null
        this.queryForm.etime = null
      }
      const params = this.queryForm
      this.listLoading = true
      const { data: itemList } = await listOrderItemNum(params)
      this.itemList = itemList
      this.listLoading = false
    },
    async getListAccessItem() {
      if (this.order_time_range.length > 0) {
        if (this.order_time_range[0]) {
          this.queryAccessForm.stime = this.order_time_range[0].getTime()
        }
        if (this.order_time_range[1]) {
          this.queryAccessForm.etime = this.order_time_range[1].getTime()
        }
      } else {
        this.queryAccessForm.stime = null
        this.queryAccessForm.etime = null
      }
      const params = this.queryAccessForm
      this.listAccessLoading = true
      const { data: itemList } = await listAccessItem(params)
      this.itemAccessList = itemList
      this.listAccessLoading = false
    },

    theDay(intraday_id) {
      this.selectBntIndex = intraday_id
      this.queryForm.intraday_id = intraday_id
      this.fetchData()
    },
    showTable(row, intraday_id) {
      let query = Object.assign({}, this.queryForm)
      query.queryArea = this.queryArea
      this.$refs['alyticsTable'].showTable(row, intraday_id, query)
    },
    async getTree() {
      const { data } = await getTree()
      this.data = data
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.fetchData()
    },
    queryData() {
      this.queryForm.pageNum = 1

      this.selectBntIndex = 0
      this.queryForm.intraday_id = 1

      this.fetchData()
    },
    change(id) {
      this.queryForm.category_id = id
    },
    getBntType(selectBntIndex) {
      if (selectBntIndex == this.selectBntIndex) {
        return 'primary'
      }
      return ''
    },
    async fetchData() {
      this.listLoading = true

      if (this.order_time_range.length > 0) {
        if (this.order_time_range[0]) {
          this.queryForm.stime = this.order_time_range[0].getTime()
        }
        if (this.order_time_range[1]) {
          this.queryForm.etime = this.order_time_range[1].getTime()
        }
      } else {
        this.queryForm.stime = null
        this.queryForm.etime = null
      }

      const params = this.queryForm
      this.getProductNumFun(params)
      this.getAccessItemNumFun(params)
      this.getAccessItemUserNumFun(params)
      this.getOrderItemNumFun(params)

      let days = 30
      if (this.queryForm.stime && this.queryForm.etime) {
        days =
          (this.queryForm.etime - this.queryForm.stime) / (1000 * 3600 * 24)
        const timeRange = {
          days: days,
          stime: this.queryForm.stime,
          etime: this.queryForm.etime,
        }

        this.interviewTime = days

        this.getAccessItemUserTimeLineFunRange(timeRange)
      } else {
        this.getAccessItemUserTimeLineFun(this.interviewTime)
      }

      //this.listOrderItemNumFun()
      //this.getListAccessItem()

      const province = this.queryArea.province
      const city = this.queryArea.city
      const district = this.queryArea.district
      if (
        province.code != undefined &&
        city.code != undefined &&
        district.code != undefined
      ) {
        this.queryForm.district_id_str =
          province.code + ',' + city.code + ',' + district.code
      } else if (
        province.code != undefined &&
        city.code == undefined &&
        district.code == undefined
      ) {
        this.queryForm.district_id_str = province.code
      } else if (
        province.code != undefined &&
        city.code != undefined &&
        district.code == undefined
      ) {
        this.queryForm.district_id_str = province.code + ',' + city.code
      } else {
        this.queryForm.district_id_str = ''
      }
      const { data } = await getList(this.queryForm)
      this.list = data.items
      this.total = data.records

      this.listLoading = false
    },
  },
}
</script>
