import { Text, View } from '@tarojs/components'
import classnames from 'classnames'
import dayjs from 'dayjs'
import { memo, useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { ArrangedForm, OrderForm, PaymentAmountForm, ReturnGoodsOrderForm } from './config'
import { ProductRankApi, PurchaserRankApi, SaleOrderDataFormApi, SalesmanRankApi } from '@/api/statistic/saleStatistic'
import { dataUnit, formatPriceDiv, setPriceUnit } from '@/common/format'
import { getFilterData } from '@/common/util'
import Cell from '@/components/cell'
import Divider from '@/components/Divider'
import Iconfont from '@/components/iconfont/iconfont'
import LayoutBlock from '@/components/layoutBlock'
import SelectMarketingDepartment from '@/components/SelectMarketingDepartment'
import SelectSaleRankingIndicators from '@/components/SelectSaleRankingIndicators'
import SelectSaleType from '@/components/SelectSaleType'
import type { ChangedValue } from '@/components/SelectTimePicker'
import SelectTimePicker from '@/components/SelectTimePicker'
import type { TablePropsType } from '@/components/table'
import Table from '@/components/table'
import ToolTip from '@/components/toolTips'
import IconText from '@/components/iconText'
import SelectGroup from '@/components/SelectGroup'

// 处理金额(后端单位分，转元)
const priceformat = (val: number) => {
  return dataUnit(val / 100)
}

const defaultLimit = 10

const FilterTimeOptions = {
  0: {
    name: '今天',
    date_min: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(1, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  1: {
    name: '昨日',
    date_min: `${dayjs(new Date())
      .add(-1, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  2: {
    name: '近7日',
    date_min: `${dayjs(new Date())
      .add(-7, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  3: {
    name: '近30日',
    date_min: `${dayjs(new Date())
      .add(-30, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
  4: {
    name: '近90日',
    date_min: `${dayjs(new Date())
      .add(-90, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
    date_max: `${dayjs(new Date())
      .add(0, 'day')
      .format('YYYY-MM-DD')} 00:00:00`,
  },
}

// 需要传进来的数据示例

// 需要传进来的表头数据示例
const productRankingColumns = [
  {
    key: 'index',
    title: '编号',
    dataIndex: 'index',
    width: '20%',
  },
  {
    key: 'product_name',
    title: '面料名称',
    dataIndex: 'product_name',
    width: '20%',
    ellipsis: {
      isEllipsis: true,
      rows: 2,
    },
  },
  {
    key: 'roll',
    title: '匹数',
    dataIndex: 'roll',
    width: '30%',
  },
  {
    key: 'sales_amount',
    title: '交易金额',
    dataIndex: 'sales_amount',
    width: '30%',
    render: (text: string) => <Text className={styles.amount}>{text}</Text>,
  },
]

// 需要传进来的表头数据示例
const purchaserRankingColumns = [
  {
    key: 'index',
    title: '编号',
    dataIndex: 'index',
    width: '20%',
  },
  {
    key: 'purchaser_name',
    title: '客户名称',
    dataIndex: 'purchaser_name',
    width: '20%',
    ellipsis: {
      isEllipsis: true,
      rows: 2,
    },
  },
  {
    key: 'roll',
    title: '交易匹数',
    dataIndex: 'roll',
    width: '30%',
  },
  {
    key: 'sales_amount',
    title: '交易金额',
    dataIndex: 'sales_amount',
    width: '30%',
    render: (text: string) => <Text className={styles.amount}>{text}</Text>,
  },
]

// 需要传进来的表头数据示例
const salesmanRankingColumns = [
  {
    key: 'index',
    title: '编号',
    dataIndex: 'index',
    width: '20%',
  },
  {
    key: 'sale_user_name',
    title: '业务员名称',
    dataIndex: 'sale_user_name',
    width: '25%',
    ellipsis: {
      isEllipsis: true,
      rows: 2,
    },
  },
  {
    key: 'roll',
    title: '销售匹数',
    dataIndex: 'roll',
    width: '25%',
  },
  {
    key: 'sales_amount',
    title: '销售金额',
    dataIndex: 'sales_amount',
    width: '30%',
    render: (text: string) => <Text className={styles.amount}>{text}</Text>,
  },
]

const tabsConfig = [
  {
    name: '面料',
    key: 0,
  },
  {
    name: '客户',
    key: 1,
  },
  {
    name: '业务员',
    key: 2,
  },
]

interface RankingBlockPropsType {
  saleType?: number | null
  saleDepartmentId?: number | null
  date_min?: string
  date_max?: string
}
// 销售排行
const RankingBlock = (props: RankingBlockPropsType) => {
  const { saleType, saleDepartmentId, date_min, date_max } = props

  const { fetchData: fetchProductRank } = ProductRankApi()
  const { fetchData: fetchPurchaserRank } = PurchaserRankApi()
  const { fetchData: fetchSalesmanRank } = SalesmanRankApi()

  const [limit, setLimit] = useState(defaultLimit)

  const [indicator, setIndicator] = useState<number | null>(1)

  // 切换排行指标
  const onChangeIndicators = useCallback((indicators: number) => {
    console.log('indicators', indicators)
    if (indicators === -1) {
      setIndicator(null)
    }
    else {
      setIndicator(indicators)
    }
  }, [])

  const [currentKey, setCurrentKey] = useState(tabsConfig[0].key)

  const handleClickTab = (event) => {
    const key = event.target.dataset.key
    if (key === currentKey) { return }
    setCurrentKey(key)
    setLimit(defaultLimit)
  }
  const [currentTable, setCurrentTable] = useState<TablePropsType>({
    columns: productRankingColumns,
  })
  const getData = useCallback(
    async(tabKey: number) => {
      let res: any
      const payload = {
        limit,
        sale_type: saleType,
        sale_department_id: saleDepartmentId,
        date_min,
        date_max,
        data_form_status: indicator,
      }
      if (tabKey === 0) {
        res = await fetchProductRank(getFilterData(payload))
      }
      else if (tabKey === 1) {
        res = await fetchPurchaserRank(getFilterData(payload))
      }
      else {
        res = await fetchSalesmanRank(getFilterData(payload))
      }
      if (res.data) {
        console.log('排名', res.data)
        if (tabKey === 0) {
          setCurrentTable(() => ({
            columns: productRankingColumns,
            dataSource: {
              list: res.data.list.map((item, index: number) => ({
                key: index,
                index: index + 1,
                product_name: item.product_name || '--',
                sales_amount: `￥${priceformat(item.sales_amount)}`,
                roll: dataUnit(item.roll),
              })),
              total: res.data.total,
            },
          }))
        }
        else if (tabKey === 1) {
          setCurrentTable(() => ({
            columns: purchaserRankingColumns,
            dataSource: {
              list: res.data.list.map((item, index: number) => ({
                key: index,
                index: index + 1,
                purchaser_name: item.purchaser_name || '--',
                sales_amount: `￥${priceformat(item.sales_amount)}`,
                roll: dataUnit(item.roll),
              })),
              total: res.data.total,
            },
          }))
        }
        else {
          setCurrentTable(() => ({
            columns: salesmanRankingColumns,
            dataSource: {
              list: res.data.list.map((item, index: number) => ({
                key: index,
                index: index + 1,
                sale_user_name: item.sale_user_name || '--',
                sales_amount: `￥${priceformat(item.sales_amount)}`,
                roll: dataUnit(item.roll),
              })),
              total: res.data.total,
            },
          }))
        }
      }
    },
    [limit, saleType, saleDepartmentId, date_min, date_max, indicator],
  )

  useEffect(() => {
    getData(currentKey)
  }, [currentKey, getData])

  const handleLoadMore = () => {
    console.log('loadmore')
    // TODO（优化）：结合接口的offset 和 limit 分段请求接口然后通过 push 将旧数据和新数据拼接起来
    setLimit(v => v + defaultLimit)
  }

  return (
    <>
      {/* 销售排行 */}
      <LayoutBlock circle flexDirection="col" customStyle={{ padding: 0 }}>
        <View className={classnames(styles.rankingIndicatorTitle, 'flex-row justify-between')} style={{ position: 'relative' }}>
          <View className="flex-row items-center">
            <Iconfont name="icon-paiming" size={32}></Iconfont>
            <Text className={styles.title}>销售排行</Text>
          </View>
          <View style={{ width: '90px' }}>
            <SelectSaleRankingIndicators onChange={onChangeIndicators} dropDownStyle={{ padding: '16rpx 0' }}></SelectSaleRankingIndicators>
          </View>
        </View>
        <View style={{ padding: '0 32rpx' }}>
          <Divider direction="horizontal" customStyles={{ margin: '10rpx 0 20rpx 0' }}></Divider>
          <View className={styles.rankingTabs} onClick={handleClickTab}>
            {tabsConfig.map((item) => {
              return (
                <View data-key={item.key} className={classnames(styles.rankingTab, item.key === currentKey ? styles.active : '')} key={item.key}>
                  {item.name}
                </View>
              )
            })}
          </View>
          <Table columns={currentTable.columns} dataSource={currentTable.dataSource} onLoadMore={handleLoadMore}></Table>
        </View>
      </LayoutBlock>
    </>
  )
}
const RankingBlockWithMemo = memo<RankingBlockPropsType>(RankingBlock)

// 销售统计
const SaleStatistic = () => {
  const { fetchData } = SaleOrderDataFormApi()

  const [saleType, setSaleType] = useState<number | null>(null)
  const [saleDepartmentId, setSaleDepartmentId] = useState<number | null>(null)
  const [dateRange, setDateRange] = useState({
    date_min: FilterTimeOptions[0].date_min,
    date_max: FilterTimeOptions[0].date_max,
  })

  const getData = async() => {
    const res = await fetchData(
      getFilterData({
        sale_type: saleType,
        sale_department_id: saleDepartmentId,
        date_min: dateRange.date_min,
        date_max: dateRange.date_max,
      }),
    )
    if (res.data) {
      // 订单
      OrderForm.summary.value = setPriceUnit(res.data.order_number)
      OrderForm.summary.total = setPriceUnit(res.data.total_roll)
      OrderForm.form.processed_order_number.value = setPriceUnit(res.data.processed_order_number)
      OrderForm.form.processing_order_number.value = setPriceUnit(res.data.processing_order_number)
      // 配布
      ArrangedForm.summary.total = setPriceUnit(formatPriceDiv(res.data.arranged_amount_sum))
      ArrangedForm.summary.value = setPriceUnit(res.data.arranged_number)
      ArrangedForm.form.not_shipped_amount_sum.value = setPriceUnit(formatPriceDiv(res.data.not_shipped_amount_sum) as number)
      ArrangedForm.form.not_shipped_number.value = setPriceUnit(res.data.not_shipped_number)
      ArrangedForm.form.not_shipped_order_number.value = setPriceUnit(res.data.not_shipped_order_number)
      ArrangedForm.form.shipped_amount_sum.value = setPriceUnit(formatPriceDiv(res.data.shipped_amount_sum) as number)
      ArrangedForm.form.shipped_number.value = setPriceUnit(res.data.shipped_number)
      ArrangedForm.form.shipped_order_number.value = setPriceUnit(res.data.shipped_order_number)
      ArrangedForm.form.wait_collect_amount_sum.value = setPriceUnit(formatPriceDiv(res.data.wait_collect_amount_sum) as number)
      ArrangedForm.form.wait_collect_number.value = setPriceUnit(res.data.wait_collect_number)
      ArrangedForm.form.wait_collect_order_number.value = setPriceUnit(res.data.wait_collect_order_number)
      // 货款
      PaymentAmountForm.summary.value = setPriceUnit(formatPriceDiv(res.data.payment_amount_sum) as number)
      PaymentAmountForm.form.amount_received_sum.value = setPriceUnit(formatPriceDiv(res.data.amount_received_sum) as number)
      PaymentAmountForm.form.amount_unreceived_sum.value = setPriceUnit(formatPriceDiv(res.data.amount_unreceived_sum) as number)
      // 退货
      ReturnGoodsOrderForm.summary.value = setPriceUnit(res.data.return_goods_order_number)
      ReturnGoodsOrderForm.form.return_amount_sum.value = setPriceUnit(formatPriceDiv(res.data.return_amount_sum) as number)
      ReturnGoodsOrderForm.form.return_goods_number.value = setPriceUnit(res.data.return_goods_number)
      console.log(res.data)
    }
  }

  const onChangeTimePicker = useCallback((value: ChangedValue) => {
    console.log(value)
    setDateRange({
      date_max: value[1],
      date_min: value[0],
    })
  }, [])

  const onChangeSaleType = useCallback((saleType: number) => {
    console.log('saleType', saleType)
    // 全部
    if (saleType === -1) {
      setSaleType(null)
    }
    else {
      setSaleType(saleType)
    }
  }, [])

  const onChangeDepartment = useCallback((department: number) => {
    console.log('department', department)
    // 全部
    if (department === -1) {
      setSaleDepartmentId(null)
    }
    else {
      setSaleDepartmentId(department)
    }
  }, [])

  const selectSaleTypeRef = useRef<any>(null)
  const selectMarketingDepartmentRef = useRef<any>(null)
  const selectTimePickerRef = useRef<any>(null)
  useEffect(() => {
    getData()
  }, [saleType, saleDepartmentId, dateRange])
  return (
    <View className={styles.saleStatistic}>
      <View className={styles['saleStatistic--filterBar']}>
        <SelectGroup>
          <SelectSaleType onChange={onChangeSaleType} defaultValue={-1} onCloseOverlay={() => true} ref={selectSaleTypeRef}></SelectSaleType>
          <SelectMarketingDepartment onChange={onChangeDepartment} onCloseOverlay={() => true} ref={selectMarketingDepartmentRef}></SelectMarketingDepartment>
          <SelectTimePicker onChange={onChangeTimePicker} onCloseOverlay={() => true} defaultValue={0} timeOptions={FilterTimeOptions} ref={selectTimePickerRef}></SelectTimePicker>
        </SelectGroup>
      </View>
      <View className={styles['saleStatistic--content']}>
        <LayoutBlock circle flexDirection="col" customStyle={{ padding: '20rpx 32rpx' }}>
          <View className="flex-row items-center">
            <IconText iconName="icon-guanlidingdan" iconSize={32} svg text="订单" textClassName={styles.title}></IconText>
          </View>
          <Divider direction="horizontal" customStyles={{ margin: '20rpx 0 10rpx 0 ' }}></Divider>
          <View className={styles.totalSummary}>
            <Text className={styles['totalSummary--title']}>{OrderForm.summary.summaryTitle}</Text>
            {/* <ToolTip placement="top" content={OrderForm.summary.tips}>
              <View className="flex-row items-center">
                <Text className={styles['totalSummary--title']}>{OrderForm.summary.summaryTitle}</Text>
                <Iconfont name="icon-tishi" size={36} color="#707070"></Iconfont>
              </View>
            </ToolTip> */}
            <View className={classnames(styles['totalSummary--current'], OrderForm.summary.value.cls)}>{OrderForm.summary.value.num}</View>
            <View className={classnames(styles['totalSummary--totalNum'])}>
              （共 <Text className={OrderForm.summary.total.cls}>{OrderForm.summary.total.num}</Text>
              匹）
            </View>
          </View>
          {Object.entries(OrderForm.form).map(([key, value]) => {
            return (
              <Cell
                key={key}
                title={
                  <Text className={styles.title}>{value.cellTitle}</Text>
                  // <ToolTip placement="top-start" content={value.tips}>
                  //   <View className="flex-row items-center">
                  //     <Text className={styles.title}>{value.cellTitle}</Text>
                  //     <Iconfont name="icon-tishi" size={36}></Iconfont>
                  //   </View>
                  // </ToolTip>
                }
                desc={value.value.num}
                customDescClassName={value.value.cls}
                customClassName={styles['cell-desc']}
              ></Cell>
            )
          })}
        </LayoutBlock>
        <LayoutBlock circle flexDirection="col" customStyle={{ padding: '20rpx 32rpx' }}>
          <View className="flex-row items-center">
            <IconText iconName="icon-guanlidingdan" iconSize={32} svg text="配布" textClassName={styles.title}></IconText>
          </View>
          <Divider direction="horizontal" customStyles={{ margin: '20rpx 0 10rpx 0 ' }}></Divider>
          <View className={styles.totalSummary}>
            <Text className={styles['totalSummary--title']}>{ArrangedForm.summary.summaryTitle}</Text>
            {/* <ToolTip placement="top" content={ArrangedForm.summary.tips}>
              <View className="flex-row items-center">
                <Text className={styles['totalSummary--title']}>{ArrangedForm.summary.summaryTitle}</Text>
                <Iconfont name="icon-tishi" size={36} color="#707070"></Iconfont>
              </View>
            </ToolTip> */}
            <View className={classnames(styles['totalSummary--current'], ArrangedForm.summary.value.cls)}>{ArrangedForm.summary.value.num}</View>
            <View className={classnames(styles['totalSummary--totalNum'])}>
              （共计 <Text className={ArrangedForm.summary.total.cls}>{ArrangedForm.summary.total.num}</Text>）
            </View>
          </View>
          {Object.entries(ArrangedForm.form).map(([key, value], index) => {
            return (
              <>
                <Cell
                  key={key}
                  title={
                    <Text className={styles.title}>{value.cellTitle}</Text>
                    // <ToolTip placement="top-start" content={value.tips}>
                    //   <View className="flex-row items-center">
                    //     <Text className={styles.title}>{value.cellTitle}</Text>
                    //     <Iconfont name="icon-tishi" size={36}></Iconfont>
                    //   </View>
                    // </ToolTip>
                  }
                  desc={value.value.num}
                  customDescClassName={value.value.cls}
                  customClassName={styles['cell-desc']}
                ></Cell>
                {((index + 1) % 3 === 0 && (index + 1) !== 9) ? <Divider direction="horizontal" customStyles={{ margin: '10rpx 0' }}></Divider> : null}
              </>
            )
          })}
        </LayoutBlock>
        <LayoutBlock circle flexDirection="col" customStyle={{ padding: '20rpx 32rpx' }}>
          <View className="flex-row items-center">
            <IconText iconName="icon-daikuan" iconSize={32} svg text="货款" textClassName={styles.title}></IconText>
          </View>
          <Divider direction="horizontal" customStyles={{ margin: '20rpx 0 10rpx 0 ' }}></Divider>
          <View className={styles.totalSummary}>
            <Text className={styles['totalSummary--title']}>{PaymentAmountForm.summary.summaryTitle}</Text>
            {/* <ToolTip placement="top" content={PaymentAmountForm.summary.tips}>
              <View className="flex-row items-center">
                <Text className={styles['totalSummary--title']}>{PaymentAmountForm.summary.summaryTitle}</Text>
                <Iconfont name="icon-tishi" size={36} color="#707070"></Iconfont>
              </View>
            </ToolTip> */}
            <View className={classnames(styles['totalSummary--current'], PaymentAmountForm.summary.value.cls)}>{PaymentAmountForm.summary.value.num}</View>
          </View>
          {Object.entries(PaymentAmountForm.form).map(([key, value]) => {
            return (
              <Cell
                key={key}
                title={
                  <Text className={styles.title}>{value.cellTitle}</Text>
                  // <ToolTip placement="top-start" content={value.tips}>
                  //   <View className="flex-row items-center">
                  //     <Text className={styles.title}>{value.cellTitle}</Text>
                  //     <Iconfont name="icon-tishi" size={36}></Iconfont>
                  //   </View>
                  // </ToolTip>
                }
                desc={value.value.num}
                customDescClassName={value.value.cls}
                customClassName={styles['cell-desc']}
              ></Cell>
            )
          })}
        </LayoutBlock>
        <LayoutBlock circle flexDirection="col" customStyle={{ padding: '20rpx 32rpx' }}>
          <View className="flex-row items-center">
            <IconText iconName="icon-tuikuan" iconSize={32} svg text="退货" textClassName={styles.title}></IconText>
          </View>
          <Divider direction="horizontal" customStyles={{ margin: '20rpx 0 10rpx 0 ' }}></Divider>
          <View className={styles.totalSummary}>
            <Text className={styles['totalSummary--title']}>{ReturnGoodsOrderForm.summary.summaryTitle}</Text>
            {/* <ToolTip placement="top" content={ReturnGoodsOrderForm.summary.tips}>
              <View className="flex-row items-center">
                <Text className={styles['totalSummary--title']}>{ReturnGoodsOrderForm.summary.summaryTitle}</Text>
                <Iconfont name="icon-tishi" size={36} color="#707070"></Iconfont>
              </View>
            </ToolTip> */}
            <View className={classnames(styles['totalSummary--current'], ReturnGoodsOrderForm.summary.value.cls)}>
              {ReturnGoodsOrderForm.summary.value.num}
            </View>
          </View>
          {Object.entries(ReturnGoodsOrderForm.form).map(([key, value]) => {
            return (
              <Cell
                key={key}
                title={
                  <Text className={styles.title}>{value.cellTitle}</Text>
                  // <ToolTip placement="top-start" content={value.tips}>
                  //   <View className="flex-row items-center">
                  //     <Text className={styles.title}>{value.cellTitle}</Text>
                  //     <Iconfont name="icon-tishi" size={36}></Iconfont>
                  //   </View>
                  // </ToolTip>
                }
                desc={value.value.num}
                customDescClassName={value.value.cls}
                customClassName={styles['cell-desc']}
              ></Cell>
            )
          })}
        </LayoutBlock>
        <RankingBlockWithMemo saleType={saleType} saleDepartmentId={saleDepartmentId} date_min={dateRange.date_min} date_max={dateRange.date_max}></RankingBlockWithMemo>
      </View>
    </View>
  )
}

export default SaleStatistic
