/*
 * @Author: wanghaofeng
 * @date: 2020/11/14 17:42
 * @Description：权限管理-选择成员弹窗
 */

import React from 'react';
import { Modal, Input, message, Tooltip,AutoComplete} from 'antd';
import { XMTable } from '@/components';
import college from '@/common/lottie/college.json';
import Service from '@/common/js/service';
import User from '@/common/js/user'
import SetEmployeeModal from "./SetEmployeeModal";
import search from '../../lottie/search/data.json';
import MemberTree from '../components/MemberTree'
import { DepType } from "@/domains/store-domain/constants";
import StoreService from "@/domains/store-domain/storeService";
import SearchUser from "../components/SearchUser"
import WWOpenDataCom from '@/components/WWOpenDataCom';
import './NewChooseMembersModal.less';
import _ from 'underscore';

const { Search } = Input;

class NewChooseMembersModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectList:[], //所有的选中项
      selectUserList:[], // 所有的选中的用户
      selectObject: {},
      openSetModal: false,
      visible:this.props.visible,
      completeOptions:[],
      queryName:'',
      open:false,
      searchUserResultList:{}
    }
  }
  componentDidMount() {
    
  }
  handleClose = ()=>{
    this.props.close()
  }
  
   // 信息列表——右边
  selectedColumnsRight = () => {
    const selectColumns = [
      {
        title: '学员名',
        key: 'nameRight',
        dataIndex: 'userName',
        width: '70%',
        render: (value, record) => {
          const { userName = '', avatar } = record;
          return (
            <div className='avatar'>
              <span className="icon iconfont avatar-icon">&#xe84a;</span>
              <Tooltip title={<WWOpenDataCom type="userName" openid={userName}/>}>
                <span className='userName'>
                  <WWOpenDataCom type="userName" openid={userName}/>
                  {/* {userName} */}
                </span>
              </Tooltip>
            </div> 
          )
        }
      },{
        title : '操作',
        key : 'edit',
        dataIndex : 'edit',
        width : '30%',
        align : 'right',
        render: (value, record) => {
          return (
            <div className='edit' onClick={() => this.clearOneUser(record)}>
              <span className="icon iconfont edit-icon">&#xe717;</span>
            </div>
          )
        }
      },
    ]
    return selectColumns;
  }

  treeSelect = (record)=>{
    this.setState({
      selectList:record,
      selectUserList:this.handleSelectUserList(record)
    })
  }
  

  // 将所有的选中项里的人员挑出来
  handleSelectUserList =(list)=>{
    const _list  = [];
    list.map((item,index)=>{
      if(item.userId){
        _list.push(item);
      }
    })
    return _list
  }
  clearOneUser = (record) =>{
    const {selectUserList,selectList} = this.state;
    const _selectList = [];
    selectList.map((item,index)=>{
      if(item.userId !== record.userId && item.id !==record.departmentId){
        _selectList.push(item);
      }
    });
    console.log('_selectList',_selectList);
    this.setState({
      selectList:_selectList,
      selectUserList:this.handleSelectUserList(_selectList)
    })
  }
   // 清空所有成员
  clearAllUser = () => {
    this.setState({
      selectList:[],
      selectUserList : [],
    })
  }

  addCustomer = () => {
    const { selectUserList } = this.state;
    const { addDepType } = this.props;
    let enterpriseUserList = [];            // 保存新加进去的成员
    enterpriseUserList = selectUserList.map((item) => {
      const _item = {}
      if(addDepType==='DEP_ORG'){
        _item.depUserType = 'VISIBLE_USER';
        _item.departmentId = item.departmentId;
        _item.enterpriseVisibleUserId = item.userId;
      }else{
        if(item.depId === '10000'){
          _item.depUserType = 'WE_CHART_USER'; // depid=10000代表是微信学员
          _item.userId = item.userId;
        }else{
          _item.depUserType = 'STORE_USER';
        }
        _item.enterpriseVisibleUserId = item.enterpriseUserId;
        _item.departmentId = this.props.selectDep.id;
      }
      return _item 
    })
    const _params = {
      storeId: User.getStoreId(),
      depType:addDepType,
      userAndDepartmentList:enterpriseUserList
    }   
    Service.Hades('public/hades/addBatchUserAndDepartmentStoreCustomer', _params).then((res) => {
      this.handleClose();
      message.success('添加成功')
      this.props.onConfirm(); 
    })
  }

  // 批量添加成员(点击确定)
  addUser = (selectUserList) => {
    let enterpriseUserList = [];            // 保存新加进去的成员
    selectUserList.map((item) => {
      enterpriseUserList.push({
        roleCode: item.roleCode,
        enterpriseVisibleUserId: item.userId
      })
      return enterpriseUserList
    })
    const _params = {
      storeId: User.getStoreId(),
      enterpriseUserList,
    }   
    Service.Hades('public/hades/addBatchEnterpriseStoreUser', _params).then((res) => {
      if (res.code === '200') {
        this.props.onConfirm();
        this.setState({
          openSetModal: false,
        })   
      }
    })
  }

  renderTitle = (title) => {
   return  <span>{title}</span>
  }
  renderItem = (record,type) => ({
    value: record.userName || record.name,
    label: (
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
        }}
      >
        {type === 'user'?
          <div>{record.userName}</div>
          :
          <div>{record.name}</div>
        }
        {type === 'user' && 
          record.postDepNamesList.map((item,index)=>{
          return <span>{item}</span>
          })
        }
        {type === 'post' &&
          <span>{item.parentName}</span>
        }
      </div>
    ),
  });
  notFoundContentNode = ()=>{
    return <span>暂无数据</span>
  }
  Complete = () =>{
    const {open,completeOptions,queryName} = this.state;
    return <AutoComplete
            dropdownClassName="certain-category-search-dropdown"
            dropdownMatchSelectWidth={250}
            allowClear
            onChange={(value)=>{this.getCompleteOptionData(value)}}
            notFoundContent={()=>{this.notFoundContentNode()}}
            value={queryName}
            open={open}
            onFocus={()=>{this.setState({open:true})}}
            onBlur={()=>{this.setState({open:false})}}
            style={{
              width: 250,
            }}
            options={completeOptions}
            onSelect={()=>this.confirmSearchSelect()}
            placeholder='搜索员工、部门'
      >
    </AutoComplete>
  } 
  getCompleteOptionData=(value)=>{
    if(!value){
      this.setState({
        searchUserResultList:{}
      })
      return
    }
    this.setState({
      queryName:value
    })
    const params = {
      distinct:true,
      queryType:this.props.type,
      depType:this.props.treeDepType, 
      queryName:value,
      enterpriseId:User.getEnterpriseId(),
      source:0,//0代表来自企培
      storeId:User.getStoreId(),
      userId:User.getUserId(),
      whetherCount:false
    }
    if(this.props.addDepType){
      params.nowDepType = this.props.addDepType;
    }
    if(this.props.selectDep){
      params.departmentId = this.props.selectDep.id;
    }
    StoreService.getDepartmentUser(params).then((res) => {
      const { result = {}} = res;
      this.setState({
        searchUserResultList:result
      })
    });
  }

  confirmSearchSelect=(record,type)=>{
    const { selectUserList,selectList} = this.state;
    if(type==='user'){
      this.setState({selectList:[...record],selectUserList:this.handleSelectUserList(record)});
    }else{
      let _list =  [];
      if(record.departmentUserVOList){
        _list = record.departmentUserVOList;
      }
      this.setState({selectList:[...selectList,..._list],selectUserList:[...selectUserList,..._list]});
    }  
  }

  render() {
    const {type,treeDepType,selectDep={},addDepType=''} = this.props;
    const { id=''} = selectDep;
    const {selectUserList,selectObject,visible,openSetModal,searchUserResultList,selectList} = this.state;
    const title = type === 'USER' ? '添加员工' : '添加学员';
    return (    
      <div>
        {/* 添加学员页面 */}
        <Modal
          className="choose-member-modal"
          visible={visible}
          onCancel={() => this.handleClose()}
          onOk={() => {
            if (User.getVersion() && User.getVersion().whetherReachUserNum) {
              message.error("添加失败，企业使用人数超出限制")
              return
            }
            if (_.isEmpty(selectUserList)) {
              message.warning(type === 'USER' ? '请选择员工' : '请选择学员')
              return null;
            }
            type === 'USER' ? this.setState({openSetModal:true,visible:false}) : this.addCustomer();
          }}
          okText={type === 'USER' ? '下一步' : '确定'}
          title={title}
          width={680}
          maskClosable={false}
          closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
        >
          <div className='member-container'>
            <div className='container-left'>
              <div className='container-left-body'>
                <SearchUser onChange={(value)=>{this.getCompleteOptionData(value)}} data={searchUserResultList} onSelect={(record,type)=>{this.confirmSearchSelect(record,type)}} selectUserList={selectUserList} selectList={selectList}/>
                <div className='container-left-body-table'>
                  <MemberTree departmentId={id} treeDepType={treeDepType} nowTreeDepType={addDepType} onSelect={(record)=>{this.treeSelect(record)}} selectUserList={selectUserList} type={type} selectList={selectList}/>
                </div>
              </div>
            </div>
            {/* 已选择的成员列表 */}
            <div className='container-right'>
              <span className='span-left'>已选择{type === 'USER' ? '员工' : '学员'}</span>
              <div className='span-right' onClick={() => this.clearAllUser()}>
                <span className={ (selectUserList.length > 0) ? 'span-right-l' : null }>清空</span>
              </div>
              <div className='container-right-body'>
                <XMTable 
                  renderEmpty={{
                    image: college,
                    description: '暂无数据'
                  }}
                  rowKey={(record) => record.id}
                  dataSource={selectUserList}
                  columns={this.selectedColumnsRight()}
                  showHeader={false}
                  scroll={{ y: 375 }}
                  pagination={false}
                  size={'small'}
                />
              </div>
            </div>
          </div>   
        </Modal>
        {openSetModal &&
          <SetEmployeeModal
            list={selectUserList}
            selectObject={selectObject}
            onChange={(key, value) => {
              selectObject[key] = value;
              this.setState({ selectObject });
            }}
            onClose={() => {
              // this.setState({ openSetModal: true},()=>{this.handleClose()})
              this.setState({ openSetModal: false, visible: true })  
            }}
            onCancel={() => {
              this.handleClose();
              this.setState({ openSetModal: false });
            }}
            onOk={(list) => {
              this.addUser(list);
            }}
          />
        }
      </div>
    )
  }
}

export default NewChooseMembersModal;