import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Picker, ScrollView, Button, Image } from '@tarojs/components'
import { getProjectList, listRecord, batchExamineRecord } from '../../utils/servers/servers';
import dayjs from 'dayjs';
import {
  AtTabs,
  AtTabsPane,
  AtIcon,
  AtSearchBar,
  AtButton,
  AtModal,
  AtModalContent,
  AtModalAction,
  AtTextarea,
} from 'taro-ui';

import sels from "../../image/sels.png";
import sel from "../../image/sel.png";

import './index.less';
import "taro-ui/dist/style/components/search-bar.scss";
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 './myList';
import DateTimePicker from '../../components/common/DateTimePicker';

class Examine extends Component {

  constructor(props) {
    super(props);
    this.state = {
      typeList: [
        { title: '全部', type: 0 },
        { title: '待审核', type: 1 },
        { title: '已审核', type: 2 },
        { title: '已驳回', type: 3 }],
      seltype: {},
      current: 0,
      tlist: [{ title: '我的打卡', type: 0 }],
      tabs: 0,
      list: [],
      sublist: [],
      pageNum: 1,
      listState: 'LOADING',
      isPickerRender: false,
      rangeEndMinuteVal: '',
      rangeStartMinuteVal: '',
      isVopen: false,
      content: "",
      examineTime: "",
      time: "",

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

  componentDidShow() {
    let roles = Taro.getStorageSync('roles');
    // 项目经理  技术总监
    if (roles.includes("manage") || roles.includes("Inspector")) {
      this.setState({
        tlist: [{ title: '我的打卡', type: 0 }, { title: '审核', type: 1 }]
      })
    }
    this.getPublicReleaseList();
  }

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

  onPullDownRefresh() {
    this.getPublicReleaseList();
  }

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

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

  onOK = ({ time }) => {
    this.setState({
      time,
      examineTime: dayjs(time).format("YYYY-MM-DD HH:mm:ss"),
    });
  }


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

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

  async getMyList(pageNum) {
    this.setState({
      listState: 'LOADING'
    })
    let data = {
      processStatus: this.state.current != 0 ? this.state.current : "",
      pageNum: pageNum,
      pageSize: 10,
      roleType: this.state.tabs,
      startTime: this.state.rangeStartMinuteVal || undefined,
      endTime: this.state.rangeEndMinuteVal || undefined,
      projectName: this.state.searchValue || undefined,
    }
    for (let i in data) {
      if (!data[i] && data[i] != 0) {
        delete data[i]
      }
    }
    let msg = await listRecord(data);
    if (msg.code === 200) {
      if (msg.total === 0) {
        this.setState({
          listState: 'NO_DATA'
        })
      } else if (msg.total === this.state.list.length && pageNum !== 1) {
        !this.state.isOpen && Taro.showToast({ title: '没有更多数据了', icon: 'none' });
        this.setState({
          listState: 'NO_MORE_DATA'
        })
      } else {
        if (msg.total === (pageNum === 1 ? msg.rows : this.state.list.concat(msg.rows)).length) {
          this.setState({
            listState: 'NO_MORE_DATA'
          })
        }
      }
      this.setState({
        list: pageNum === 1 ? msg.rows : this.state.list.concat(msg.rows),
        pageNum: msg.rows.length === 0 ? this.state.pageNum : msg.next - 1
      })
    } else {
      Taro.showToast({ title: msg.msg, icon: 'none' });
      this.setState({
        // listState: msg.error[0].field === '403' ? 'NO_DATA' : 'RELOAD'
      })
    }
    Taro.stopPullDownRefresh();
  }

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

  onChecked(item) {
    let list = this.state.sublist
    list.includes(item.id)
      ? list = list.filter(function (value) {
        return value !== item.id;
      }, this)
      : list.push(item.id)
    this.setState({
      sublist: list
    })
  }

  onAllCheck() {
    const { list, } = this.state
    let nlist = this.state.sublist
    if (list.length == nlist.length) {
      nlist = []
    } else {
      nlist = list.map(i => i.id)
    }
    this.setState({
      sublist: nlist
    })
  }

  // 同意/驳回
  agree(sta) {
    if (!this.state.opinion) {
      Taro.showToast({ title: "请填写审批意见", icon: "none" });
      return;
    }
    let data = {
      id: this.state.sublist.toString(),
      processStatus: sta,
      content: this.state.opinion,
      examineTime: "",
    }
    for (let i in data) {
      if (!data[i] && data[i] != 0) {
        delete data[i]
      }
    }
    batchExamineRecord(data)
      .then((v) => {
        this.setState({
          isVopen: false
        })
        if (v.code === 200) {
          Taro.showToast({
            title: "操作成功",
            icon: "none",
          });
          this.getMyList(1);
        } else {
          Taro.showToast({ title: v.msg, icon: "none" });
        }
      })
      .catch((err) => {
        Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
        // console.log(err);
      });
  }


  render() {
    const { isVopen } = this.state
    return (
      <View className='indexPage' >
        <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.seltype.type}
                  range={this.state.typeList} rangeKey='title' mode='selector'
                  onChange={(e) => {
                    this.setState({
                      seltype: this.state.typeList[e.detail.value],
                      current: this.state.typeList[e.detail.value].type,
                    }, () => {
                      this.getPublicReleaseList();
                    })
                  }}>
                  {
                    !this.state.seltype.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.seltype.title}
                        </View>
                        <View className='iconContent' />
                      </View>
                  }
                </Picker>
                {
                  this.state.seltype.title &&
                  <View className='searchSelectContent'>
                    <View className='selectIcon'
                      onClick={(e) => {
                        e.stopPropagation();
                        this.setState({
                          seltype: {},
                          current: 0,
                        }, () => {
                          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' 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>

          <AtTabs
            swipeable={false}
            current={this.state.tabs || 0}
            tabList={this.state.tlist}
            onClick={(tabs) => {
              this.setState({
                list: [],
                pageNum: 1,
                tabs: this.state.tlist[tabs].type,
              }, () => {
                this.getPublicReleaseList();
              })
            }}
          >

            {
              this.state.typeList?.map((item, index) =>
                <AtTabsPane
                  current={this.state.tabs}
                  index={index}
                >
                  <MyList
                    type={this.state.tabs}
                    title={item.title}
                    typelist={this.state.typeList}
                    seeView={this.state.tabs}
                    list={this.state.list}
                    listState={this.state.listState}
                    onRefresh={() => {
                      this.getProjectList(true);
                    }}
                    sublist={this.state.sublist}
                    onChecked={e => { this.onChecked(e) }}
                  />
                </AtTabsPane>
              )
            }

          </AtTabs>
        </View>
        {
          this.state.list.length > 0 && this.state.tabs == 1 &&
          <View className='bottom'>
            <View className='lbt'>
              {
                this.state.seltype.type == 1 &&
                <View className='lbtxt'
                  onClick={() => {
                    this.onAllCheck()
                  }}
                >
                  <Image className='lbtck' src={this.state.list.length == this.state.sublist.length ? sels : sel} />
                  全选
                </View>
              }
            </View>
            <DateTimePicker
              onOk={this.onOK}
              initValue={dayjs().format("YYYY/MM/DD HH:mm:ss")}
            />
            <Button
              disabled={this.state.sublist.length == 0}
              className='rbt'
              type='primary'
              onClick={() => { this.setState({ isVopen: true }) }}
            >批量审核</Button>
          </View>
        }
        <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>

        <AtModal
          width="90%"
          isOpened={isVopen}
          onClose={() => { this.setState({ isVopen: false }) }}
        >
          <AtModalContent>
            <View className='tips'>
              <View className="tit">审批意见</View>
              <AtTextarea
                count={false}
                value={this.state.opinion}
                onChange={(value) => {
                  this.setState({
                    opinion: value,
                  });
                }}
                maxLength={100}
                placeholder="请填写审批意见"
              />
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button
              onClick={() => { this.agree(3) }}>驳回</Button>
            <Button
              onClick={() => { this.agree(2) }}>同意</Button>
          </AtModalAction>
        </AtModal>

      </View>
    )
  }
}

export default Examine
