import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Picker, ScrollView, Button } from '@tarojs/components'
import { getPublicReleaseList, techReject } from '../../utils/servers/servers';
import dayjs from 'dayjs';
import {
  AtSearchBar,
  AtTabs,
  AtTabsPane,
  AtIcon,
  AtModal,
  AtModalContent,
  AtModalAction,
  AtTextarea
} from 'taro-ui';
import { clockState } from '../../utils/tools/config';

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";

import MyList from '../examine/myList';
import MessageNoticebar from "../../components/common/messageNoticebar";

class Examine extends Component {

  constructor(props) {
    super(props);
    this.state = {
      typeList: [
        { title: '我的公出' },
        { title: '我的协单' }],
      current: 0,
      isPickerRender: false,
      validDates: '',
      list: [],
      pageNo: 1,
      listState: 'LOADING',
      starts: {},
      clockInStarts: '',
      rangeEndVal: '',
      rangeStartVal: '',
      rangeEndMinuteVal: '',
      rangeStartMinuteVal: '',
      id: "",
      rmk: "",
      isOpen: false,
      coorder: [
        { title: '协单助手', type: 3 },
        { title: '技术协单', type: 2 },
        { title: '全部', type: 4 }],
      selcotype: 4,

    }
    this.getPublicReleaseList = this.getPublicReleaseList.bind(this);
    this.getMyList = this.getMyList.bind(this);
    this.onSetPickerTime = this.onSetPickerTime.bind(this);
    this.onPickerHide = this.onPickerHide.bind(this)
  }

  componentDidShow() {
    Taro.eventCenter.on('listOperation', (data) => {
      if (!isNaN(parseInt(data.index))) {
        let arr = this.state.list.concat([]);
        arr[data.index] = {
          ...arr[data.index],
          ...data
        }
        this.setState({
          list: arr
        })
      }
    })
  }

  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,
      type: '0',
      assist: this.state.current === 0 ? 0 : this.state.selcotype,
      releaseStarts: this.state.rangeStartMinuteVal || undefined,
      releaseEnds: this.state.rangeEndMinuteVal || undefined,
      status: isNaN(parseInt(this.state.starts.id)) ? undefined : String(this.state.starts.id),
      clockIn: this.state.clockInStarts || undefined,
      userName: this.state.searchValue || undefined,
    }
    for (let i in data) {
      if (!data[i]) {
        delete data[i]
      }
    }
    let msg = await getPublicReleaseList(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) {
        // 防止提示挡住驳回弹窗
        !this.state.isOpen && 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
      })
    }
  }

  submit() {
    if (!this.state.rmk) {
      Taro.showToast({ title: '请填写备注！', icon: 'none' });
      return
    }
    Taro.showLoading({ title: '正在提交...' });
    techReject({
      id: this.state.id,
      remarks: this.state.rmk,
    }).then(v => {
      Taro.hideLoading()
      if (v.error.length === 0) {
        Taro.showToast({ title: '提交成功', icon: 'none' });
        this.getPublicReleaseList();
        this.setState({
          isOpen: false,
          rmk: "",
        })
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  render() {
    return (
      <View className='indexPage' >
        <MessageNoticebar />
        <View className='searchContent'>
          <View className='searchTop'>
            <AtSearchBar
              showActionButton
              placeholder='请输入企业/渠道'
              value={this.state.searchValue}
              onActionClick={() => {
                this.getPublicReleaseList();
              }}
              onChange={(value) => {
                this.setState({
                  searchValue: value
                })
              }}
              onClear={() => {
                this.setState({
                  searchValue: ''
                })
              }}
            />
          </View>
          <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={clockState} rangeKey='title' mode='selector'
                  onChange={(e) => {
                    this.setState({
                      starts: clockState[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' >
                <Picker
                  value={this.state.clockInStarts}
                  range={['未打卡', '已打卡', '异常打卡']}
                  mode='selector'
                  onChange={(e) => {
                    this.setState({
                      clockInStarts: String(e.detail.value)
                    }, () => {
                      this.getPublicReleaseList();
                    })
                  }}>
                  {
                    !this.state.clockInStarts ?
                      <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.clockInStarts === '2'
                              ? '异常打卡' : this.state.clockInStarts === '1'
                                ? '已打卡' : this.state.clockInStarts === '0'
                                  ? '未打卡' : ''
                          }
                        </View>
                        <View className='iconContent' />
                      </View>
                  }
                </Picker>
                {
                  this.state.clockInStarts ?
                    <View className='searchSelectContent'>
                      <View className='selectIcon'
                        onClick={(e) => {
                          e.stopPropagation();
                          this.setState({
                            clockInStarts: '',
                          }, () => {
                            this.getPublicReleaseList();
                          })
                        }}>
                        <AtIcon value='close-circle' size='10' color='#FFFFFF' />
                      </View>
                    </View> : null
                }
              </View>
              {/*  */}
              {/* 多选时间框 */}
              <View className='searchItem' onClick={() => {
                this.setState({
                  isPickerRender: true
                })
              }}>
                <View>
                  {
                    !this.state.rangeStartMinuteVal ?
                      <View className='valuecontent' style={{ width: '200px' }}>
                        <View className='selectTitle' style={{ paddingLeft: '50px' }}>开始及结束时间</View>
                        <View className='iconContent' style={{ paddingLeft: '20px' }}><AtIcon value='chevron-down' size='10' color='#FFFFFF' /></View>
                      </View> :
                      <View className='valuecontent' style={{ width: '200px' }}>
                        <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.getPublicReleaseList();
            })
          }}>
          {
            this.state.typeList?.map((item, index) =>
              <AtTabsPane
                current={this.state.current}
                index={index}
              >
                {
                  this.state.current === 1 &&
                  <View className='navs'>
                    {
                      this.state.coorder.map((it) =>
                        <View className={this.state.selcotype == it.type ? 'nitems' : 'nitem'}
                          key={it.type}
                          onClick={() => {
                            this.setState({
                              list: [],
                              pageNo: 1,
                              selcotype: it.type,
                            }, () => {
                              this.getPublicReleaseList();
                            })
                          }}
                        >{it.title}</View>
                      )
                    }
                  </View>
                }
                <MyList
                  type={0}
                  title={item.title}
                  typelist={this.state.typeList}
                  seeView={this.state.current}
                  list={this.state.list}
                  listState={this.state.listState}
                  onRefresh={() => {
                    this.getPublicReleaseList(true);
                  }}
                  opens={e => {
                    this.setState({
                      id: e,
                      isOpen: true,
                    })
                  }}
                />
              </AtTabsPane>
            )
          }
        </AtTabs>
        <timePicker
          config={{
            endDate: true,
            column: "minute",
            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) => {
            // let a = dayjs(dayjs(v.detail.endTime).second(0).format('YYYY-MM-DD'));
            // let b = dayjs(dayjs().second(0).format('YYYY-MM-DD'))
            // if(a.isBefore(b)){
            //   Taro.showToast({
            //     title:'结束时间不能小于当前时间',
            //     icon:'none'
            //   })
            //   v.detail.setLv(false);
            // }
          }}
          onhidepicker={() => {
            this.onPickerHide()
          }}
          onsetpickertime={(v) => {
            this.onSetPickerTime(v)
          }}>
        </timePicker>
        {/* 驳回协单 */}
        {
          this.state.isOpen &&
          <AtModal
            isOpened={this.state.isOpen}
          >
            <AtModalContent>
              <AtTextarea
                value={this.state.rmk}
                onChange={e => {
                  this.setState({ rmk: e })
                }}
                maxLength={200}
                placeholder='请填写备注~'
              />
            </AtModalContent>
            <AtModalAction>
              <Button type='secondary' onClick={() => { this.setState({ isOpen: false }) }}>取消</Button>
              <Button type='primary' onClick={this.submit.bind(this)}>提交</Button>
            </AtModalAction>
          </AtModal>
        }
      </View>
    )
  }
}

export default Examine
