import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Picker, ScrollView, Button } from '@tarojs/components'
import { getPublicReleaseList, techReject, getAssistUnaudited, publicAssistAdviceList } from '../../utils/servers/servers';
import dayjs from 'dayjs';
import {
  AtSearchBar,
  AtTabs,
  AtTabsPane,
  AtIcon,
  AtModal,
  AtModalHeader,
  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/modal.scss";

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

class Examine extends Component {

  constructor(props) {
    super(props);
    this.state = {
      typeList: [
        { title: '审核', type: 1 },
        { title: '查看公出', type: 2 },
        { title: '协单审核', type: 3 },
        { title: '他人公出', type: 4 }],
      current: 0,
      sonTypes: [
        { lable: '技术员公出', value: 5 },
        { lable: '营销员公出', value: 4 },
      ],
      type: 1,
      current: 0,
      title: "审核",
      selcotype: 4,
      isPickerRender: false,
      validDates: '',
      list: [],
      pageNo: 1,
      listState: 'LOADING',
      starts: { title: '审核中', id: 1, color: '#1d4fea' },
      clockInStarts: '',
      rangeEndVal: '',
      rangeStartVal: '',
      rangeEndMinuteVal: '',
      rangeStartMinuteVal: '',
      id: "",
      rmk: "",
      isOpen: false,
      isOpinion: false,
      opinion: [],
      isFill: true,

    }
    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
        })
      }
    })

    this.getPublicReleaseList();
    this.assistUnaudited();
  }

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

  // 协单未审核查询
  assistUnaudited() {
    getAssistUnaudited({}).then(v => {
      if (v.error.length === 0) {
        let newList = this.state.typeList
        newList[0].num = v.data.unaudited
        newList[1].num = 0
        newList[2].num = v.data.assistUnaudited
        newList[3].num = v.data.otherUnaudited
        this.setState({
          typeList: newList
        })
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  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) {
    const { current } = this.state
    this.setState({
      listState: 'LOADING'
    })
    let data = {
      pageNo: pageNo,
      pageSize: 10,
      type: current === 0
        ? 1 : current === 1
          ? 2 : current === 2
            ? 6 : current === 3 && 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'
      })
    })
  }

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

  publicAssistAdviceList(t, obj) {
    publicAssistAdviceList({
      id: obj.id,
      type: t == "我的公出" ? 1 : 0,
    }).then(v => {
      if (v.error.length === 0) {
        this.setState({
          info: obj,
          opinion: v.data,
          isOpinion: true,
          isFill: t == "我的协单" ? true : false
        })
      } 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>
        <View className='tab'>
          {
            this.state.typeList.map((v, i) =>
              <View
                className={this.state.current == i ? 'titems' : 'titem'}
                key={i}
                onClick={() => {
                  this.setState({
                    current: i,
                    type: v.type,
                    title: v.title,
                    list: [],
                    pageNo: 1,
                  }, () => {
                    this.assistUnaudited();
                    this.getPublicReleaseList();
                  })
                }}
              >
                {v.title}
                {v.num > 0 && <View className='tips'></View>}
              </View>
            )
          }
        </View>
        {
          this.state.current === 3 &&
          <View className='navs'>
            {
              this.state.sonTypes.map((it) =>
                <View className={this.state.selcotype == it.value ? 'nitems' : 'nitem'}
                  key={it.value}
                  onClick={() => {
                    this.setState({
                      list: [],
                      pageNo: 1,
                      selcotype: it.value,
                    }, () => {
                      this.getPublicReleaseList();
                    })
                  }}
                >{it.lable}</View>
              )
            }
          </View>
        }
        <MyList
          type={this.state.type}
          title={this.state.title}
          sonType={this.state.selcotype}
          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,
            })
          }}
          opinion={(t, e) => {
            this.publicAssistAdviceList(t, e)
            this.setState({
              id: e.id,
            });
          }}
        />
        <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>
        }
        {/* 填写协单意见 */}
        {
          this.state.isOpinion &&
          <AtModal
            isOpened={this.state.isOpinion}
          >
            <AtModalHeader>公出企业-协单意见</AtModalHeader>
            <AtModalContent>
              <View style={{ margin: "0 0 10px", color: "#6190E8" }}>{this.state.info.userNames}</View>
              {
                this.state.isFill &&
                <AtTextarea
                  value={this.state.remarks}
                  onChange={e => {
                    this.setState({ remarks: e })
                  }}
                  maxLength={200}
                  placeholder='请填写协单意见~'
                />
              }
              <View className='historicalClock'>
                {
                  this.state.opinion.length > 0
                    ? this.state.opinion.map(item =>
                      <View key={item.id} className='item'>
                        <View className='head'>
                          <View className='spot' />
                          <View className='clockTime' style={{ color: "#6190E8" }}>
                            {item.aname}
                          </View>
                        </View>
                        <View className='clockContent'>
                          <View className='verticalLine' />
                          <View className='rightContent'>
                            <View className='contentItem'>
                              <AtIcon className='atIcon' value='clock' size='15' color='#999999' />
                              操作时间:{item.createTime}
                            </View>
                            <View className='contentItem'>
                              <AtIcon className='atIcon' value='message' size='15' color='#999999' />
                              评价:{item.remarks || "暂无"}
                            </View>
                          </View>
                        </View>
                      </View>
                    )
                    : <View style={{ textAlign: "center" }}>暂无协单意见</View>
                }
              </View>
            </AtModalContent>
            {
              this.state.isFill
                ? <AtModalAction>
                  <Button type='secondary' onClick={() => { this.setState({ isOpinion: false }) }}>取消</Button>
                  <Button type='primary' onClick={this.onOpinion.bind(this)}>确定</Button>
                </AtModalAction>
                : <AtModalAction>
                  <Button type='secondary' onClick={() => { this.setState({ isOpinion: false }) }}>确定</Button>
                </AtModalAction>
            }
          </AtModal>
        }
      </View>
    )
  }
}

export default Examine
