import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Picker, ScrollView, } from '@tarojs/components'
import { AtTabs, AtTabsPane, AtIcon, } from 'taro-ui';
import { getRecordList, } from '../../utils/servers/servers';
import dayjs from 'dayjs';
import { getAccountName, removeNull } from '../../utils/tools';
import { accountLtate, } from '../../utils/tools/config'
import ListBottomStart from "../../components/common/listBottomStart";
import AuditModal from "../../components/common/auditModal";

import './index.less';
import 'taro-ui/dist/style/components/tabs.scss';
import "taro-ui/dist/style/components/flex.scss";
import "taro-ui/dist/style/components/action-sheet.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/modal.scss";

class Examine extends Component {

  constructor(props) {
    super(props);
    this.state = {
      typeList: [
        { title: '未审核' },
        { title: '已审核' }],
      current: 0,
      starts: {},
      list: [],
      visible: false,
    }
  }

  componentDidShow() {
    this.setState({
      visible: false,
    })
    this.getPublicReleaseList();
  }

  async componentDidMount() {
    await this.getPublicReleaseList();
  }

  onPullDownRefresh() {
    this.getPublicReleaseList();
  }

  onReachBottom() {
    this.getPublicReleaseList(true);
  }

  onTabItemTap(obj) {
    if (obj.index === 1) {
      this.onTabTap();
    }
  }

  onPickerHide() {
    this.setState({
      isPickerRender: false,
    });
  }


  async onSetPickerTime(val) {
    let data = val.detail;
    await this.setState({
      rangeStartMinuteVal: dayjs(data.selectStartTime).format("YYYY-MM-DD"),
      rangeEndMinuteVal: dayjs(data.selectEndTime).format("YYYY-MM-DD")
    })
    await this.getMyList(1);
  }

  async onTabTap() {
    await this.getMyList(1);
  }

  async getPublicReleaseList(lv) {
    await this.getMyList(lv ? this.state.pageNo + 1 : 1);
    Taro.stopPullDownRefresh();
  }

  async getMyList(pageNo) {
    this.setState({
      listState: 'LOADING'
    })
    let data = {
      pageNo: pageNo,
      pageSize: 10,
      startTime: this.state.rangeStartMinuteVal || undefined,
      endTime: this.state.rangeEndMinuteVal || undefined,
      status: isNaN(parseInt(this.state.starts.id)) ? undefined : String(this.state.starts.id),
      examineStatus: this.state.current,
      processStatus: 1,
    }
    let msg = await getRecordList(removeNull(data));
    if (msg.error.length === 0) {
      if (msg.data.totalCount === 0) {
        this.setState({
          listState: 'NO_DATA'
        })
      } else if (msg.data.totalCount === this.state.list.length && pageNo !== 1) {
        Taro.showToast({ title: '没有更多数据了', icon: 'none' });
        this.setState({
          listState: 'NO_MORE_DATA'
        })
      } else {
        if (msg.data.totalCount === (pageNo === 1 ? msg.data.list : this.state.list.concat(msg.data.list)).length) {
          this.setState({
            listState: 'NO_MORE_DATA'
          })
        }
      }
      this.setState({
        list: pageNo === 1 ? msg.data.list : this.state.list.concat(msg.data.list),
        pageNo: msg.data.list.length === 0 ? this.state.pageNo : msg.data.pageNo
      })
    } else {
      Taro.showToast({ title: msg.error[0].message, icon: 'none' });
      this.setState({
        listState: msg.error[0].field === '403' ? 'NO_DATA' : 'RELOAD'
      })
    }
    Taro.stopPullDownRefresh();
  }

  onPageScroll(event) {
    let touchMove = event.scrollTop;
    if (touchMove >= 37) {
      this.setState({
        openSearch: true
      })
    } else {
      this.setState({
        openSearch: false
      })
    }
  }


  render() {
    const { list } = this.state
    return (
      <View className='indexPage' >
        <View className='searchContent'>
          <ScrollView className={this.state.openSearch ? 'searchBottomLOL' : ''} scrollX style={{ width: '100%' }}>
            <View className='searchBottom'>
              <View className='searchItem' style={{ paddingLeft: '5px' }}>
                <Picker
                  value={this.state.starts.id}
                  range={accountLtate} rangeKey='title' mode='selector'
                  onChange={(e) => {
                    this.setState({
                      starts: accountLtate[e.detail.value],
                    }, () => {
                      this.getPublicReleaseList();
                    })
                  }}>
                  {
                    !this.state.starts.title ?
                      <View className='shortValuecontent'>
                        <View className='selectTitle'>状态</View>
                        <View className='iconContent'><AtIcon value='chevron-down' size='10' color='#FFFFFF' /></View>
                      </View> :
                      <View className='shortValuecontent'>
                        <View className='selectValue'>
                          {this.state.starts.title}
                        </View>
                        <View className='iconContent' />
                      </View>
                  }
                </Picker>
                {
                  this.state.starts.title &&
                  <View className='searchSelectContent'>
                    <View className='selectIcon'
                      onClick={(e) => {
                        e.stopPropagation();
                        this.setState({
                          starts: {}
                        }, () => {
                          this.getPublicReleaseList();
                        })
                      }}>
                      <AtIcon value='close-circle' size='10' color='#FFFFFF' />
                    </View>
                  </View>
                }
              </View>
              <View className='searchItem' onClick={() => {
                this.setState({
                  isPickerRender: true
                })
              }}>
                <View>
                  {
                    !this.state.rangeStartMinuteVal ?
                      <View className='valuecontent'>
                        <View className='selectTitle'>开始及结束时间</View>
                        <View className='iconContent' ><AtIcon value='chevron-down' size='10' color='#FFFFFF' /></View>
                      </View> :
                      <View className='valuecontent'>
                        <View className='selectValue' >
                          {this.state.rangeStartMinuteVal + "~" + this.state.rangeEndMinuteVal}
                        </View>
                        <View className='iconContent' />
                      </View>
                  }
                </View>
                {
                  this.state.rangeStartMinuteVal &&
                  <View className='searchSelectContent'>
                    <View className='selectIcon'
                      onClick={(e) => {
                        e.stopPropagation();
                        this.setState({
                          rangeStartMinuteVal: '',
                          rangeEndMinuteVal: '',
                        }, () => {
                          this.getPublicReleaseList();
                        })
                      }}>
                      <AtIcon value='close-circle' size='10' color='#FFFFFF' />
                    </View>
                  </View>
                }
              </View>
            </View>
          </ScrollView>
        </View>
        <AtTabs
          swipeable={false}
          current={this.state.current || 0}
          tabList={this.state.typeList}
          onClick={(current) => {
            this.setState({
              list: [],
              pageNo: 1,
              current,
            }, () => {
              this.getMyList();
            })
          }}>
          {
            this.state.typeList?.map((item, index) =>
              <AtTabsPane
                current={this.state.current}
                index={index}
              >
                <View className='list'>
                  {
                    list?.map((item) =>
                      <View className='item' key={item.id}
                        onClick={() => {
                          Taro.navigateTo({
                            url: '/pages/draftsdetail/index?id=' + item.id
                          })
                        }}
                      >
                        {item.status == 1 && <View className='lbt' onClick={e => { e.stopPropagation(); this.setState({ visible: true, id: item.id }) }}>查看审核详情</View>}
                        <View className='line'>报销类型：{getAccountName(item.type, item.typeOther)}</View>
                        <View className='line'>报销金额（元）：{item.totalAmount}</View>
                        <View className='line'>报销人：{item.aname}</View>
                        <View className='line'>报销时间：{item.createTimeStr}</View>
                        <View className='lines'
                          style={{ color: accountLtate[item.status].color }}
                        >{item.status == 1 && `[${item.examineName}]`}{accountLtate[item.status].title}</View>
                      </View>
                    )
                  }
                  <ListBottomStart
                    state={this.state.listState}
                    reload={() => {
                      this.getPublicReleaseList(true)
                    }}
                  />
                </View>
              </AtTabsPane>
            )
          }
        </AtTabs>
        <timePicker
          config={{
            endDate: true,
            column: "day",
            dateLimit: false,
            limitStartTime: dayjs().subtract(3, 'year').format('YYYY-MM-DD '),
            limitEndTime: dayjs().add(3, 'year').format('YYYY-MM-DD ')
          }}
          isPartition
          pickerShow={this.state.isPickerRender}
          onconditionaljudgment={(v) => {
          }}
          onhidepicker={() => {
            this.onPickerHide()
          }}
          onsetpickertime={(v) => {
            this.onSetPickerTime(v)
          }}>
        </timePicker>
        {this.state.visible &&
          <AuditModal
            id={this.state.id}
            isOpened={this.state.visible}
            onClose={() => {
              this.setState({
                visible: false
              })
            }}
          />}
      </View >
    )
  }
}

export default Examine
