import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Picker, ScrollView, Button } from '@tarojs/components'
import {
  selectMyUser,
  selectMyUserDetails,
  queryUserMax,
} from '../../utils/servers/servers';
import dayjs from 'dayjs';
import {
  AtSearchBar,
  AtTabs,
  AtTabsPane,
  AtIcon,
  AtRadio,
  AtModal,
  AtModalContent,
  AtModalAction,
  AtModalHeader,
  AtTextarea,
} from 'taro-ui';
import { shareType, levelType } 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/radio.scss";
import "taro-ui/dist/style/components/modal.scss";

import List from './list';
import MessageNoticebar from "../../components/common/messageNoticebar";

class Enterprise extends Component {

  constructor(props) {
    super(props);
    this.state = {
      typeList: [
        { title: '企业/渠道' },
        { title: '公出企业/渠道' }],
      current: 0,
      list: [],
      pageNo: 1,
      listState: 'LOADING',
      starts: {},
      level: {},
      isProject: false,
      isTips: false,
      value: "",
    }
    this.selectMyUser = this.selectMyUser.bind(this);
    this.getMyList = this.getMyList.bind(this);
    this.onSetPickerTime = this.onSetPickerTime.bind(this);
    this.onPickerHide = this.onPickerHide.bind(this);
    this.onAdd = this.onAdd.bind(this);
  }

  componentDidShow() {
    this.selectMyUser();
  }


  onPullDownRefresh() {
    this.selectMyUser();
  }

  onReachBottom() {
    this.selectMyUser(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 selectMyUser(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: this.state.current,
      // releaseStarts: this.state.rangeStartMinuteVal || undefined,
      // releaseEnds: this.state.rangeEndMinuteVal || undefined,
      shareType: isNaN(parseInt(this.state.starts.id)) ? undefined : String(this.state.starts.id),
      level: isNaN(parseInt(this.state.level.id)) ? undefined : String(this.state.level.id),
      name: this.state.searchValue || undefined,
    }
    for (let i in data) {
      if (!data[i]) {
        delete data[i]
      }
    }
    let msg = await selectMyUser(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
      })
    }
  }

  selectMyUserDetails(obj) {
    Taro.showLoading({
      title: '加载中...',
    })
    selectMyUserDetails({
      id: obj.id,
    }).then(v => {
      Taro.hideLoading();
      if (v.error.length === 0) {
        let newList = this.state.list
        for (var i = 0; i < newList.length; i++) {
          if (newList[i].id == obj.id) {
            newList[i].count = v.data.count
            newList[i].minPublicRelease = v.data.minPublicRelease
            newList[i].maxPublicRelease = v.data.maxPublicRelease
            newList[i].latestFollow = v.data.latestFollow
          }
        }
        this.setState({
          list: newList
        })
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }

  onHide(obj) {
    let newList = this.state.list
    for (var i = 0; i < newList.length; i++) {
      if (newList[i].id == obj.id) {
        delete newList[i].count
        delete newList[i].minPublicRelease
        delete newList[i].maxPublicRelease
        delete newList[i].latestFollow
      }
    }
    this.setState({
      list: newList
    })
  }

  onAdd() {
    const { value } = this.state
    if (!value) {
      Taro.showToast({ title: "请先选择新增企业/渠道", icon: 'none' })
      return
    } else if (value == "1") {
      queryUserMax({}).then(v => {
        if (v.error.length === 0) {
          if (v.data == 1) {
            this.setState({
              isTips: true
            })
            return
          }
          this.setState({
            isProject: false
          })
          Taro.navigateTo({
            url: "/pages/addEnterprise/index?type=" + value
          })
        } else {
          Taro.showToast({ title: v.error[0].message, icon: 'none' })
        }
      }).catch(() => {
        Taro.hideLoading()
        Taro.showToast({
          title: '系统错误,请稍后再试',
          icon: 'none'
        })
      })
    }
    else if (value == "2") {
      this.setState({
        isProject: false
      })
      Taro.navigateTo({
        url: "/pages/addEnterprise/index?type=" + value
      })
    }
  }


  render() {
    const { isProject, isTips } = this.state
    const isAdd = Taro.getStorageSync('userInfor').province
    return (
      <View className='indexPage' >
        <MessageNoticebar />
        <View className='searchContent'>
          <View className='searchTop' style={{ display: "flex", flexDirection: "row" }}>
            {
              (isAdd == "21" || isAdd == "11") &&
              <View className='sadd'
                onClick={e => {
                  e.stopPropagation()
                  this.setState({
                    isProject: true
                  })
                }}
              >新增</View>
            }
            <View style={{ width: "100%" }}>
              <AtSearchBar
                showActionButton
                placeholder='请输入企业/渠道'
                value={this.state.searchValue}
                onActionClick={() => {
                  this.selectMyUser();
                }}
                onChange={(value) => {
                  this.setState({
                    searchValue: value
                  })
                }}
                onClear={() => {
                  this.setState({
                    searchValue: ''
                  })
                }}
              />
            </View>
          </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={shareType} rangeKey='title' mode='selector'
                  onChange={(e) => {
                    this.setState({
                      starts: shareType[e.detail.value],
                    }, () => {
                      this.selectMyUser();
                    })
                  }}>
                  {
                    !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.selectMyUser();
                        })
                      }}>
                      <AtIcon value='close-circle' size='10' color='#FFFFFF' />
                    </View>
                  </View>
                }
              </View>
              <View className='searchItem' >
                <Picker
                  value={this.state.level.id}
                  range={levelType} rangeKey='title' mode='selector'
                  onChange={(e) => {
                    this.setState({
                      level: levelType[e.detail.value]
                    }, () => {
                      this.selectMyUser();
                    })
                  }}>
                  {
                    !this.state.level.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.level.title}
                        </View>
                        <View className='iconContent' />
                      </View>
                  }
                </Picker>
                {
                  this.state.level.title ?
                    <View className='searchSelectContent'>
                      <View className='selectIcon'
                        onClick={(e) => {
                          e.stopPropagation();
                          this.setState({
                            level: {},
                          }, () => {
                            this.selectMyUser();
                          })
                        }}>
                        <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.selectMyUser();
                        })
                      }}>
                      <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.selectMyUser();
            })
          }}>
          {
            this.state.typeList?.map((item, index) =>
              <AtTabsPane
                current={this.state.current}
                index={index}
              >
                <List
                  list={this.state.list}
                  listState={this.state.listState}
                  onRefresh={() => {
                    this.selectMyUser(true);
                  }}
                  getMore={e => {
                    this.selectMyUserDetails(e);
                  }}
                  onHide={e => {
                    this.onHide(e)
                  }}
                />
              </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}
          onhidepicker={() => {
            this.onPickerHide()
          }}
          onsetpickertime={(v) => {
            this.onSetPickerTime(v)
          }}>
        </timePicker>


        <AtModal
          isOpened={isTips}
          title='温馨提示'
          confirmText='确认'
          onClose={() => { this.setState({ isTips: false, }) }}
          onConfirm={() => { this.setState({ isTips: false }) }}
          content='不可添加！您的客户数已达最大值，可移除部分客户后添加！'
        />

        <AtModal
          isOpened={isProject}
          closeOnClickOverlay={false}
        >
          <AtModalHeader>新增企业/渠道</AtModalHeader>
          <AtModalContent>
            <AtRadio
              options={[
                { label: '新增企业', value: '1', },
                { label: '新增渠道', value: '2' },
              ]}
              value={this.state.value}
              onClick={e => {
                this.setState({
                  value: e
                })
              }}
            />
          </AtModalContent>
          <AtModalAction>
            <Button type='secondary' onClick={() => { this.setState({ isProject: false, }) }}>取消</Button>
            <Button type='primary' onClick={this.onAdd}>确定</Button>
          </AtModalAction>
        </AtModal>

      </View>
    )
  }
}

export default Enterprise
