import Taro from '@tarojs/taro'
import { View, Text, Radio, Button } from '@tarojs/components'
import CtsThumb from '../thumb'
import CtsSearch from '../search'
import { AtDrawer } from 'taro-ui'

import classNames from 'classnames'
import PropTypes, { InferProps } from 'prop-types'
import CtsComponent from '../../common/component'
import { CommonEvent } from '@tarojs/components/types/common'
import { CtsPersonAddProps, CtsPersonAddState } from 'types/person-add'

/**
 * 新增人员组件
 */
export default class CtsPersonAdd extends CtsComponent<CtsPersonAddProps, CtsPersonAddState> {
  // static options = {
  //   addGlobalClass: true
  // }

  public static defaultProps: CtsPersonAddProps
  public static propTypes: InferProps<CtsPersonAddProps>

  public constructor(props: CtsPersonAddProps) {
    super(props)
    this.state = {
      searchVal: '',
      lists: [],
      chooseWorkers: []
    }
  }

  public componentWillReceiveProps(props: CommonEvent): void {
    const { show, workerStatus, choosePersons } = props
    if (show) {
      let typelist = {
        1: '新增',
        2: '减少',
        3: '变更'
      }

      this.setState({
        chooseWorkers: choosePersons
      })
      Taro.setNavigationBarTitle({
        title: `${typelist[workerStatus] || ''}人员`
      })

      this.searchFn()
    }
  }

  // 点击返回
  private onCancel(): void {
    this.props.onCancel()
  }

  // 更改关键词
  private searchChange(val: string): void {
    this.setState({
      searchVal: val
    }, () => {
      // 搜索
      this.searchFn()
    })
  }

  // 搜索
  private searchFn(): void {
    const { workerStatus } = this.props
    if (!workerStatus) {
      // (选择框)工人列表: 新增保单
      this.getWorkers()
    } else {
      // (选择框)工人列表: 新增批单
      this.getEndorsement()
    }
  }

  // (选择框)工人列表: 新增保单
  private getWorkers(): void {
    const { searchVal } = this.state
    const { projectId } = this.props
    let params = {
      projectId,
      keyword: searchVal
    }
    Taro['common'].request('/cts/insurance/optional/workers/forPolicy', 'GET', params).then(res => {
      // console.log(res)
      this.setState({
        lists: res.data
      })
    })
  }

  // (选择框)工人列表: 新增批单
  private getEndorsement(): void {
    const { searchVal } = this.state
    const { projectId, policyId, workerStatus } = this.props
    let params = {
      projectId,
      policyId,
      workerStatus,
      keyword: searchVal,
      teamId: ''
    }
    Taro['common'].request('/cts/insurance/optional/workers/forEndorsement', 'GET', params).then(res => {
      // console.log(res)

      let { unableChooseVariable, workerStatus } = this.props
      let increaseProjectGroupWorkerIdArr: any[] = [] // 增保人员列表
      let decreaseProjectGroupWorkerIdArr: any[] = [] // 停保人员列表

      // 已选择的变更人员（新增人员不能选择增保人员，减少人员不能选择停保人员）
      if (unableChooseVariable && unableChooseVariable.length > 0) {
        unableChooseVariable.forEach(item => {
          increaseProjectGroupWorkerIdArr.push(item.increaseProjectGroupWorkerId)
          decreaseProjectGroupWorkerIdArr.push(item.decreaseProjectGroupWorkerId)
        })

        if (workerStatus === 1) {
          // 新增人员
          res.data = res.data.filter(item => {
            return !increaseProjectGroupWorkerIdArr.includes(item.projectGroupWorkerId)
          })
        } else if (workerStatus === 2) {
          // 减少人员
          res.data = res.data.filter(item => {
            return !decreaseProjectGroupWorkerIdArr.includes(item.projectGroupWorkerId)
          })
        }
      }

      this.setState({
        lists: res.data
      })
    })
  }

  // 点击取消搜索
  private cancelSearch(): void {
    this.setState({
      searchVal: ''
    }, () => {
      this.searchFn()
    })
  }

  // 点击选择工人
  private chooseWorker(projectGroupWorkerId: string): void {
    let { chooseWorkers } = this.state
    // 若选中，则删除
    let index = chooseWorkers.indexOf(projectGroupWorkerId)
    if (index > -1) {
      chooseWorkers.splice(index, 1)
    } else {
      chooseWorkers.push(projectGroupWorkerId)
    }
    this.setState({ chooseWorkers })
  }

  // 确认添加工人
  private submit(): void {
    const { chooseWorkers } = this.state
    const { required } = this.props
    if (required && chooseWorkers.length === 0) {
      return
    }

    this.props.onChange(this.state.chooseWorkers)
  }

  public render(): JSX.Element {
    const { searchVal, lists, chooseWorkers } = this.state
    const { show, required } = this.props

    return (
      <AtDrawer show={show} width='100%' right={true}>
        <View className='cts-person-add'>
          <View className='person-header'>
            <View className='return' onClick={this.onCancel.bind(this)}>
              <Text className='iconfont iconRectangle1'></Text>
              <Text className='return-text'>返回</Text>
            </View>
            <View className='title'>人员</View>
          </View>

          {/* <View className='person-home'>
            <View className='search'>
              <AtSearchBar value={searchVal} onChange={this.searchChange.bind(this)} placeholder="请输入姓名或身份证件号"></AtSearchBar>
            </View>
          </View> */}

          <CtsSearch value={searchVal} onChange={this.searchChange.bind(this)} placeholder='请输入姓名或身份证件号' />

          {
            lists.length > 0 ?
              <View className='lists'>
                {
                  lists.map((item, index) => {
                    return <View className='lists-item' key={String(index)} onClick={this.chooseWorker.bind(this, item.projectGroupWorkerId)}>
                      <View className='item-left'>
                        <Radio value={item.projectGroupWorkerId} checked={chooseWorkers.includes(item.projectGroupWorkerId)} color='#1976D2' />
                      </View>
                      <View className='item-right'>
                        <CtsThumb headImg={item.headImg} name={item.workerName} />
                        <View className='person-info'>
                          <View className="person-name">{item.workerName}</View>
                          <View className="person-content">{item.idcardNo}</View>
                        </View>
                      </View>
                    </View>
                  })
                }
              </View>
              :
              <View className="person-list-nodata">查无该人员，检查是否输入错误。</View>
          }

          {
            searchVal ?
              <View className='footer-bar'>
                <Button className='btn-confirm' onClick={this.cancelSearch.bind(this)}>
                  {
                    chooseWorkers.length === 0 && lists.length > 0 &&
                    <Text>返回继续添加</Text>
                  }
                  {
                    chooseWorkers.length > 0 && lists.length > 0 &&
                    <Text>共选择了{chooseWorkers.length}人，继续添加</Text>
                  }
                  {
                    lists.length === 0 &&
                    <Text>返回继续添加</Text>
                  }
                </Button>
              </View>
              :
              <View className='footer-bar'>
                <Button
                  className={classNames('btn-confirm', (required && chooseWorkers.length === 0 ? 'disabled' : ''))}
                  onClick={this.submit.bind(this)}
                >
                  确认选择({chooseWorkers.length}人)
                </Button>
              </View>
          }


        </View>
      </AtDrawer>
    )
  }
}

CtsPersonAdd.defaultProps = {
  projectId: '',
  policyId: '',
  show: false,
  workerStatus: 1,
  unableChooseVariable: [],
  required: false,
  choosePersons: [],
  onChange() { },
  onCancel() { }
}

CtsPersonAdd.propTypes = {
  projectId: PropTypes.string,
  policyId: PropTypes.string,
  show: PropTypes.bool,
  workerStatus: PropTypes.number,
  unableChooseVariable: PropTypes.array,
  required: PropTypes.bool,
  choosePersons: PropTypes.array,
  onChange: PropTypes.func,
  onCancel: PropTypes.func,
}
