import React, { useState, useEffect } from 'react'
import Taro, { useDidShow, useRouter, useReachBottom } from '@tarojs/taro'
import { View, Picker, Input, Image } from '@tarojs/components'
import moment from 'moment'
import './index.scss'
import NoData from '@/components/no-data/noData'
import request from '@/services/request'
import { getReportList } from '@/services/api';
import chevronDown from '../../static/img/patrolView/chevron-down.png'
import searchIcon from '../../static/img/patrolView/search.png'
import cardImg from '../../static/img/patrolView/card-img.png'
import patrolIcon from '../../static/img/patrolView/patrol.svg'
import patrolActiveIcon from '../../static/img/patrolView/patrol-active.svg'
import conserveIcon from '../../static/img/patrolView/conserve.svg'
import conserveActiveIcon from '../../static/img/patrolView/conserve-active.svg'

function Index() {
  const userInfo = Taro.getStorageSync('userInfo') || {};
  const isAdmin = userInfo && userInfo.username === 'SuperAdmin' ? true : false
  const router = useRouter()
  const { params: { filter, kind, } } = router

  const isPatrol = kind === 'patrol' || kind == 'conserve' ? true : false
  const isRoad = kind === 'road' ? true : false
  const isAnomaly = kind === 'anomaly' ? true : false
  const isWait = kind === 'wait' ? true : false
  const ishandle = kind == 'handle' ? true : false

  const [reportType, setReportType] = useState(kind || 'patrol')
  const [datePicker, setDatePicker] = useState('')
  const [listData, setListData] = useState([])
  const [filterText, setFilterText] = useState('')
  const [systemInfo, setSystemInfo] = useState('')
  const [page, setPage] = useState(0)
  const [num, setNum] = useState(Math.random())
  const [typeSearchList, setTypeSearchList] = useState(['全部', '待处理', '不处理', '已处理'])
  const [typeSearch, setTypeSearch] = useState('全部')

  const limit = 10

  useEffect(() => {
    if (isRoad) {
      Taro.setNavigationBarTitle({ title: '在建项目' })
    } else if (isAnomaly) {
      Taro.setNavigationBarTitle({ title: '异常反馈' })
    } else if (ishandle) {
      Taro.setNavigationBarTitle({ title: '已办事项' })
    } else if (kind == 'conserve') {
      Taro.setNavigationBarTitle({ title: '养护上报' })
    } else if (isWait) {
      Taro.setNavigationBarTitle({ title: '待办事项' })
    } else {
      Taro.setNavigationBarTitle({ title: '巡查上报' })
    }
  }, [])

  useEffect(() => {
    setPage(0)
    setNum(Math.random())
  }, [reportType, datePicker, typeSearch])

  useEffect(() => {
    getList(page == 0 ? true : false)
  }, [num])

  function dealError(error) {
    Taro.showToast({
      title: error,
      icon: 'none',
      duration: 1500
    });
    throw new Error(error);
  }
  const getList = (isInit) => {
    Taro.showLoading({ title: '加载中' })
    let handleState = ''
    if (typeSearch != '全部') {
      handleState = typeSearch
    } else {
      handleState = isWait 
      ? isAdmin ? '待处理' : '待处理,已指派'
      : ishandle 
        ? isAdmin ? '已处理,已指派,不处理' : '已处理' 
        : ''
    }
    const data = {
      limit,
      page,
      startTime: datePicker ? datePicker + ' 00:00:00' : '',
      endTime: datePicker ? datePicker + ' 23:59:59' : '',
      keyword: filterText,
      reportType: isWait || ishandle ? 'anomaly' : reportType,
      userId: filter === 'my' && !ishandle ? userInfo.id : '',
      handleState: handleState,
      performerId: (isWait || ishandle) && !isAdmin ? userInfo.id : '', // 超管查看所有
    }
    request.get(getReportList(), data).then(res => {
      Taro.hideLoading()
      if (res.statusCode == 200) {
        if (res.data.length === 0) {
          Taro.showToast({
            title: '没有更多了',
            icon: 'none'
          })
        }
        const temp = isInit ? [] : listData
        const nextListData = temp.concat(res.data)
        setListData(nextListData)
      } else {
        dealError(res.data.message || '请求出错');
      }
    }, err => {
      dealError(err.message || '请求出错');
    });
  }

  // 监听上拉触底
  useReachBottom(() => {
    setPage(page + 1)
    setNum(Math.random())
  })

  useDidShow(() => {
    setPage(0)
    setNum(Math.random())
    let refresh = Taro.getStorageSync('refresh'); // 返回列表需要刷新
    if (refresh) {
      Taro.removeStorageSync('refresh'); // 返回列表需要刷新
    }
    Taro.getSystemInfo({
      success: (res) => {
        // windows | mac为pc端
        // android | ios为手机端
        setSystemInfo(res.platform);
      }
    });
  })

  const onDateChange = e => {
    setDatePicker(e.detail.value);
  }

  const handleConfirm = e => {
    setPage(0)
    setNum(Math.random())
  }

  const handleInput = e => {
    setFilterText(e.detail.value);
    if (!e.detail.value) {
      setPage(0)
      setNum(Math.random())
    }
  }

  const handleDetail = index => {
    Taro.navigateTo({ url: `/packages/patrol/index?type=view&id=${listData[index].id}&kind=${kind == 'wait' || kind == 'handle' ? 'anomaly' : kind}&wait=${kind == 'wait' ? 'wait' : ''}&handle=${kind == 'handle' ? 'handle' : ''}&videoShow=${kind == 'wait' || kind == 'handle' ? 'videoShow' : ''}` })
  }
  const setType = (e) => {
    setTypeSearch(e.detail.value == 1 ? '待处理' : e.detail.value == 2 ? '不处理' : e.detail.value == 3 ? '已处理' : '全部')
  }
  return (
    <View>
      {/* {
        isPatrol ?
          <View className='type-box'>
            <View className='item' onClick={() => setReportType('patrol')}>
              <Image className='type-img' src={reportType == 'patrol' ? patrolActiveIcon : patrolIcon} />
              <View style={{ color: reportType == 'patrol' ? '#346FC2' : '#999999' }}>巡查</View>
            </View>
            <View className='line'></View>
            <View className='item' onClick={() => setReportType('conserve')}>
              <Image className='type-img' src={reportType == 'conserve' ? conserveActiveIcon : conserveIcon} />
              <View style={{ color: reportType == 'conserve' ? '#346FC2' : '#999999' }}>养护</View>
            </View>
          </View>
          : ""
      } */}

      <View className='filter-box' style={{ top: isPatrol && false ? "40px" : '0' }}>
        <View className='filter-item' style={{ width: '270rpx' }}>
          <View style={{ float: 'left', marginLeft: '20rpx', color: '#333' }}>日期：</View>
          <Picker
            className='picker'
            style={{ overflow: 'hidden', float: 'left' }}
            mode='date'
            end={(systemInfo == 'windows' || systemInfo == 'mac')
              ? moment().add(1, 'd').format('YYYY-MM-DD')
              : moment().format('YYYY-MM-DD')} onChange={onDateChange}
          >
            <View className='filter-name'>{datePicker || '请选择'}</View>
            <Image className='filter-img' src={chevronDown} />
          </Picker>
        </View>
        {
          kind == 'anomaly' ? <View style={{ display: 'flex', lineHeight: '98rpx', marginRight: '20rpx' }}>
            <View style={{ color: '#333' }}>状态：</View>
            <Picker range={typeSearchList} onChange={setType}>
              <View style={{ float: 'left' }}>{typeSearch}</View>
              <Image style={{ display: 'block', width: '14rpx', height: '8rpx', float: 'left', marginTop: '44rpx', marginLeft: '10rpx' }} src={chevronDown} />
            </Picker>
          </View> : ''
        }
        <View class='head-search'>
          <Image className='search-img' src={searchIcon} />
          <Input class='heard-search-input' value={filterText} placeholder={
            isRoad ? '请输入项目名称' : '请输入道路名称'} onConfirm={handleConfirm} onInput={handleInput} />
        </View>
      </View>

      <View style={{ marginTop: isPatrol && false ? '110px' : "80px" }}>
        {
          listData && listData.length > 0 ? listData && listData.map((e, index) => {
            return (
              <View className='cardBox' key={index} onClick={() => handleDetail(index)}>
                <View className='card-item' >
                  <Image className='card-bg' src={cardImg} />
                  <View className='card-position'>
                    <View className='card-title'>{e.road || e.projectName}</View>
                    <View style={{ float: 'left', width: '100%', fontSize: '28rpx', marginTop: '16rpx' }}>
                      <View style={{ float: 'left' }}>填报人：</View>
                      <View style={{ float: 'left' }}>{e.user && e.user.name}</View>
                    </View>
                    <View className='card-date'>{moment(e.time).format('YYYY-MM-DD HH:mm:ss')}</View>
                  </View>
                </View>
              </View>
            )
          }) : <NoData top='400rpx'></NoData>
        }
      </View>
    </View>
  )
}
export default Index
