/*
 * @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 './ChooseMembersModal.less';
import _ from 'underscore';

const { Search } = Input;

class NewChooseMembersModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      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='userImg'>
                  <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)=>{
    // console.log('record',record)
    this.setState({
      selectUserList:record
    })
  }

  clearOneUser = (record) =>{
    console.log("record",record);
    const {selectUserList} = this.state;
    const _selectUserList = selectUserList.filter((item,index)=>{
      return item.userId !== record.userId
    })
    console.log('selectUserList',selectUserList);
    this.setState({
      selectUserList:_selectUserList
    })
  }
   // 清空所有成员
  clearAllUser = () => {
    this.setState({
      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();
      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
    }
    StoreService.getDepartmentUser(params).then((res) => {
      const { result = {}} = res;
      this.setState({
        searchUserResultList:result
      })
    });
  }

  confirmSearchSelect=(record,type)=>{
    const { selectUserList } = this.state;
    if(type==='user'){
      this.setState({selectUserList:[...selectUserList,...record]});
    }else{
      let _list =  [];
      if(record.departmentUserVOList){
        _list = record.departmentUserVOList;
      }
      console.log('_list',_list);
      this.setState({selectUserList:[...selectUserList,..._list]},()=>{
        console.log('selectUserList',this.state.selectUserList);
      });
    }  
    // }else{
    //   const params = {
    //     depType:this.props.treeDepType,
    //     enterpriseId: User.getEnterpriseId(),
    //     source: 0,
    //     storeId: User.getStoreId(),
    //     userId: User.getUserId(),
    //     departmentId:record.id
    //   }
    //   StoreService.getStoreCustomerAndDepNamePage(params).then((res) => {
    //     const { records = []} = res.result;
    //     this.setState({selectUserList:[...selectUserList,...records]});
    //   });
    // }
  }

  render() {
    const {type,treeDepType,selectDep={},addDepType=''} = this.props;
    const { id=''} = selectDep;
    const {selectUserList,selectObject,visible,openSetModal,searchUserResultList} = 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'>
                {/* <Search 
                  placeholder='搜索成员'
                  className='search search-input'
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                /> */}
                {/* {this.Complete()} */}
                <SearchUser onChange={(value)=>{this.getCompleteOptionData(value)}} data={searchUserResultList} onSelect={(record,type)=>{this.confirmSearchSelect(record,type)}}/>
                <div className='container-left-body-table'>
                  <MemberTree departmentId={id} treeDepType={treeDepType} nowTreeDepType={addDepType} onSelect={(record)=>{this.treeSelect(record)}} selectUserList={selectUserList} type={type}/>
                </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;