import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Picker, ScrollView, Button } from '@tarojs/components'
import {
  getPublicReleaseList,
  techReject,
  getReleasetDails,
  publicAssistAdvice,
  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 '../examine/myList';
import MessageNoticebar from "../../components/common/messageNoticebar";
import InquiryModal from "../../components/common/inquiryModal";
import PublicContent from "../egressDetails/publicContent";
import { resourceAddress } from "../../utils/config";
import { getUserByName } from "../../utils/servers/servers";

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,
      coorderPublic: [
        { title: '非公出协单', type: 9 },
        { title: '公出协单', type: 8 },
        { title: '全部', type: 0 }],
      coorder: [
        { title: '非公出协单', type: 10 },
        { title: '协单助手', type: 3 },
        { title: '技术协单', type: 2 },
        { title: '全部', type: 4 }],
      selcotype: 0,
      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);
    this.getReleasetDails = this.getReleasetDails.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
        })
      }
    })
    //获取地区选定数据
    const chooseLocation = requirePlugin("chooseLocation");
    const location = chooseLocation.getLocation();
    if (location) {
      this.setState({
        selectArrderLocation: location,
      });
    }

    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,
    });
  }
  // 公出详情
  getReleasetDails(id, callback) {
    getReleasetDails({
      id: id
    }).then((v) => {
      if (v.error.length === 0) {
        if (v.data) {
          
          let list = [];
          for (let i of v.data.annexUrl.split(",")) {
            if (i) {
              list.push({ url: resourceAddress + i });
            }
          }
          v.data.annexUrl = list;
          this.setState({
            dtails: v.data,
            selectArrderLocation: {
              longitude: parseFloat(v.data.prdList[0]?.longitude),
              latitude: parseFloat(v.data.prdList[0]?.latitude),
              name: v.data.prdList[0]?.districtName,
            },
          }, () => {
            callback && callback();
          })
        }
      } else {
        Taro.showToast({ title: v.error[0].message, icon: "none" });
      }
    }).catch((err) => {
      // Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
    });
  }

  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 type = 0;
    let assist = 0
    if (this.state.current === 0) {
      type = this.state.selcotype
    } else if (this.state.current === 1) {
      if (this.state.selcotype === 10) {
        type = 10
        assist = 2
      } else {
        type = 0
        assist = this.state.selcotype
      }
      
    }

    let data = {
      pageNo: pageNo,
      pageSize: 10,
      type: type.toString(),
      assist: assist.toString(),
      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'
      })
    })
  }

  getUserInfoByName(name, callback) {
    getUserByName({
      name,
      type: 1,
      pageNo: 1,
      pageSize: 10,
    }).then(res => {
      if (!res.error.length) {
        callback && callback(res.data.list)
      } else {
        Taro.showToast({title: "系统异常，请联系管理员!", icon: "none"});
      }
    })
  }

  render() {
    const { coorderPublic, current, coorder } = this.state
    const currCoorderList = current == 0 ? coorderPublic : coorder
    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,
              selcotype: current === 1 ? 4 : 0,
            }, () => {
              this.getPublicReleaseList();
            })
          }}>
          {
            this.state.typeList?.map((item, index) =>
              <AtTabsPane
                current={this.state.current}
                index={index}
              >
                <View className='navs'>
                  {
                    currCoorderList.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,
                    })
                  }}
                  again={e => {
                    if (e.userNames && e.userNames.split(',').length > 1) {
                      Taro.showToast({ title: "公出企业包含多个，不能再次公出!", icon: "none" });
                      return;
                    }
                    
                    this.getReleasetDails(e.id, () => {
                      this.setState({
                        isInquiryOpened: true,
                        inquiryTitle: "温馨提示",
                        inquiryContent: "您确定需再次公出拜访同一家企业吗？",
                        inquiryFn: () => {
                          
                        },
                      });
                    })
                    
                  }}
                  opinion={(t, e) => {
                    this.publicAssistAdviceList(t, e)
                    this.setState({
                      id: e.id,
                    });
                  }}
                />
              </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) => {
            // 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.isInquiryOpened &&
          <InquiryModal
            isOpened={this.state.isInquiryOpened}
            title={this.state.inquiryTitle}
            content={this.state.inquiryContent}
            color="black"
            isNo={this.state.isNo}
            onClose={() => {
              this.setState({
                isInquiryOpened: false,
                dtails: {},
                inquiryTitle: "",
                inquiryContent: "",
                isNo: true,
              });
            }}
            onDetermine={() => {
              const data = this.state.dtails;
              let prdData = data.prdList[0];
              this.getUserInfoByName(prdData.userName, userList => {
                let currUserInfo = userList.find(item => item.id === prdData.uid);
                if (currUserInfo && currUserInfo.shareType === 1) {
                  Taro.showToast({title: "无法发起，公共库客户请领取，再进行公出", icon: "none"});
                  this.setState({ isInquiryOpened: false });
                  return;
                }
                
                const customerList = data.prdList.map(item => {
                  return { id: item.uid, aid: data.aid, aname: data.aname, name: item.userName, myUser: currUserInfo.myUser }
                })
                Taro.setStorageSync('publicInfo', {
                  type: data.type,
                  customerList,
                  orderNo: data.orderNo,
                  contractNo: data.contractNo
                })
                Taro.switchTab({
                  url: `/pages/applyDepart/index`
                });
                this.setState({
                  // isModifyOpened: true,

                  isInquiryOpened: false,
                  inquiryTitle: "",
                  inquiryContent: "",
                  isNo: true,
                  inquiryFn: () => { },
                });
              });
              
            }}
          />
        }
        {/* 再次公出详情 */}
        {
          this.state.isModifyOpened &&
          <AtModal
            isOpened={this.state.isModifyOpened}
            onClose={() => {
              this.setState({
                isModifyOpened: false,
                dtails: {},
              })
            }}
          >
            <AtModalContent>
              <PublicContent
                again={true}
                onClose={() => {
                  this.setState({
                    isModifyOpened: false,
                    dtails: {},
                  })
                }}
                locationInfor={this.state.selectArrderLocation}
                dtails={this.state.dtails}
                isOpened={this.state.isModifyOpened}
              />
            </AtModalContent>
          </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
