import React, { useEffect, useState } from "react";
import { withRouter } from "react-router-dom";
import { Button, Input, message,Modal,Tooltip} from "antd";
import NewChooseMembersModal from "@/modules/college-manage/modal/NewChooseMembersModal";
import LeftStructureTree from "./LeftStructureTree";
import { XMTable, PageControl } from "@/components";
import college from "@/common/lottie/college.json";
import WWOpenDataCom from '@/components/WWOpenDataCom';
import StoreService from "@/domains/store-domain/storeService";
import { DepType } from "@/domains/store-domain/constants";
import User from "@/common/js/user";
import moment from "moment";
import "./DepartMentTabCon.less";
import Bus from "@/core/bus";
import _ from 'underscore';
const { Search } = Input;
const { confirm } = Modal;
const DefaultQuery = {
  size: 10,
  current:1,
};
function DepartMentTabCon(props) {
  const [chooseMembersModalVisible, setChooseMembersModalVisible] = useState(
    false
  );
  const [query, setQuery] = useState(DefaultQuery);
  const [total, setTotal] = useState(0);
  const [userListdata, setUserListData] = useState([]);
  const [selectUser,setSelectUser] = useState([]); // 设置选中的用户
  const [selectDep,setSelectDep] = useState({});
  const columns = [
    {
      title: "学员",
      dataIndex: "nickName",
      width: 220,
      render: (val, item) => {
        return (
          <div>
            {item.sourceEnum === "WORK_WE_CHAT" ?
              <Tooltip title={<div><WWOpenDataCom type="userName" openid={val}/></div>}><span className="student-name"><WWOpenDataCom type="userName" openid={val}/></span></Tooltip>:
              <Tooltip title={val}><span className="student-name">{val}</span></Tooltip>
            }
            <span
              className="tag"
              style={{
                color:
                  item.sourceEnum === "WORK_WE_CHAT" ? "#2966FF" : "#1DCC65",
              }}
            >
              {item.sourceEnum === "WORK_WE_CHAT" ? "@企业微信" : "@微信"}
            </span>
          </div>
        );
      },
    },
    {
      title: "真实姓名",
      dataIndex: "realName",
      width: "15%",
      render: (val, record) => {
        return <span>{val}</span>;
      },
    },
    {
      title: "账号",
      dataIndex: "nickName",
      width: "15%",
      render: (val, item) => {
        return <span>{val}</span>;
      },
    },
    {
      title: "岗位",
      dataIndex: "depNameList",
      render: (val, record) => {
    
        if(!record.depNameList){
          return <span>-</span>
        }else{
          if(record.depNameList.length === 0){
            return <span>-</span>
          }
          return <Tooltip title={handleDepName(record.depNameList)} placement='top' arrowPointAtCenter><div className="post-name"> {record.depNameList.map((item, index) => {
            return <span>{item}{index!==record.depNameList.length-1 && <span>；</span>}</span>
            })}
          </div>
          </Tooltip>
        }

      }
    },
    {
      title: "手机号",
      dataIndex: "phone",
      render: (val, item) => {
        if(!val){
            return <span>-</span>
        }else{
          return <span>{item.phone}</span>
        }
      },
    },
    {
      title: "注册时间",
      dataIndex: "created",
      render: (val, item) => {
        return <div>{moment(val).format("YYYY-MM-DD HH:mm:ss")}</div>;
      },
    },
    {
      title: "操作",
      key: "operate",
      dataIndex: "operate",
      render: (val, item) => {
        return (
          <div className="operate">
            {props.currentTab==='departMentTab'?
              <span>-</span>
              // <div className="operate__item" onClick={()=>delUser('single',item.userId)}>删除</div>
              :
              <div className="operate__item" onClick={()=>delUser('single',item.userId)}>移出</div>
            }
          </div>
        );
      },
    },
  ];
  function handleDepName(depArray){
    let depStr = '';
    depArray.forEach((item, index) => {
      if (index < depArray.length - 1) {
        depStr = depStr + item + '；';
      } else {
        depStr = depStr + item;
      }
    });
    return depStr;
  };
  function closeChooseMembersModal() {
    setChooseMembersModalVisible(false);
  }
  function getUserList(record,treeType,current) {
    const params = {
      ...query,
      depType:DepType[treeType]|| DepType[props.currentTab],
      enterpriseId: User.getEnterpriseId(),
      source: 0,
      storeId: User.getStoreId(),
      userId: User.getUserId()
    };
    if(record){
      if(record.id){
        params.departmentId = record.id;
      }else{
        params.departmentId = null;
      }
      if(record.queryName){
        params.nickName = record.queryName;
      }else{
        params.nickName = null;
      }  
    }
    if (current) {
      params.current = current;
    }
    setQuery(params);
    console.log('params ++++ ',params);
    StoreService.getStoreCustomerAndDepNamePage(params).then((res) => {
      const { records = [], total } = res.result;
      setUserListData(records);
      setTotal(total);
    });
  }

  function confirmAddCustomer() {
    const _query = {
      ...DefaultQuery,
      id:query.departmentId
    }
    Bus.trigger("addCustomer",{treeType:props.currentTab,query:_query});
  }

  function delUser(type,userId){
    let idList = [];
    if(type === 'single'){
      idList.push(userId);
    }
    if(type==='multiple'){
      idList = _.pluck(selectUser,'userId');
    }
    if(idList.length===0){
      message.warning('请先选择要删除的学员')
      return;
    }
    return confirm({
      title: "确定要删除学员吗？",
      content: "删除后，该学员将从员工列表中删除，且看不到该学院用户端。",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      okType: "danger",
      cancelText: "取消",
      onOk: () => {
        handleConfirmDelUser(idList);
      },
    });
  }

  function handleConfirmDelUser(idList){
    const params = {
      depType:DepType[props.currentTab],
      idList,
      storeId:User.getStoreId()
    }
    console.log('selectDep',selectDep)
    if(selectDep.depId==='10000'){
      params.userType='WE_CHAT';
    }else{
      params.userType='WORK_WE_CHAT';
    }
    StoreService.delDepartmentUser(params).then((res) => {
      message.success(`删除成功`);
      getUserList();
      Bus.trigger("changeTreeData",{treeType:props.currentTab});
    });
  }
  function handleSelectUserList(record, selected){
    let _list = [];
    if (selected || !_.find(selectUser, (item) => item.userId === record.userId)) {
      _list = _.uniq(selectUser.concat([record]), false, (item) => item.userId);
    } else {
      _list = _.reject(selectUser, (item) => item.userId === record.userId);
    }
    if (_list.length > 50) {
      message.warning('无法继续选择，最多选择50个');
      return;
    }
    console.log('selectUser',_list);
    setSelectUser(_list);
  };

  function updateListData(){
    let num;
    const params = {
      enterpriseId:User.getEnterpriseId(),
      storeId:User.getStoreId(),
      userType:'CUSTOMER'
    }
    StoreService.getSyncCount(params).then((res) => {
      num = res.result;
      if(num<3){
        return confirm({
          title: "确定更新列表数据吗？",
          content: `学员数据来源企微通讯录，一天只能更新3次，今日还能更新${3-num}次。`,
          icon: (
            <span className="icon iconfont default-confirm-icon">&#xe839; </span>
          ),
          okText: "确定",
          cancelText: "取消",
          onOk: () => {
            confirmUpdateListData()
          },
        });
      }else{
        Modal.warning({
          title: '提示',
          okText: '我知道了',
          content: '学员数据今日更新次数已达上限（3次），无法继续更新。',
          icon: (
            <span className='icon iconfont default-confirm-icon' style={{ color: '#FFBB54 !important' }}>
              &#xe834;
            </span>
          ),
        });
      }
    });
  }

  function confirmUpdateListData(){
    const params = {
      enterpriseId:User.getEnterpriseId(),
      storeId:User.getStoreId(),
      userType:'CUSTOMER'
    }
    StoreService.syncWorkWeChatDepartment(params).then((res) => {
      message.success('已更新');
    });
  }

  return (
    <div className="department-tab-con">
      <LeftStructureTree
        treeType={props.currentTab}
        searchUserList={(params,treeType) => getUserList(params,treeType,1)}
        onChangeSelectDep={(record)=>{setSelectDep(record);}}
      />
      <div className="table-con">
        {props.currentTab === "departMentTab" && (
          <div className="operate-area">
            { selectDep.depId !== '10000' &&
              <Button
                type="primary"
                className="add-user-btn"
                onClick={() => {
                  setChooseMembersModalVisible(true);
                }}
              >
                添加学员
              </Button>
            }
            {(props.currentTab === "postGrouptab" || props.currentTab === "customGroupTab") &&
              <Button className="del-user-btn" onClick={()=>delUser('multiple')}>删除学员</Button>
            }
            { selectDep.depId !== '10000' &&
              <>
                <Button className="update-user-btn" onClick={()=>{updateListData()}}>更新列表数据</Button>
                <span className="origin-text">数据来源企业微信通讯录</span>
                <a
                  href="https://www.yuque.com/wangzhong-zkqw0/qixue"
                  target="_blank"
                >
                  <span className="view-text">查看数据更新说明</span>
                </a>
              </>
            }
          </div>
        )}
        {(props.currentTab === "postGrouptab" ||
          props.currentTab === "customGroupTab") && (
          <div className="operate-area">
            {/* 岗位组和自定义分组只有岗位下和分组才展示添加学员*/}
            {(selectDep.depLevel > 0) &&
              <Button
                type="primary"
                className="add-user-btn"
                onClick={() => {
                  setChooseMembersModalVisible(true);
                }}
              >
                添加学员
              </Button>
            }
            <Button className="del-user-btn" onClick={()=>delUser('multiple')}>移出学员</Button>
          </div>
        )}
        <div className="user-table">
          <XMTable
            renderEmpty={{
              image: college,
              description: "暂无数据",
            }}
            bordered
            size="middle"
            pagination={false}
            columns={columns}
            scroll={{ x: 800 }}
            dataSource={userListdata}
            rowKey={(record) => record.userId}
            rowSelection={{
              type: 'checkbox',
              selectedRowKeys: _.pluck(selectUser, 'userId'),
              onSelect: (record, selected) => {
                console.log('record',record);
                handleSelectUserList(record, selected)
              },
              onSelectAll: (selected, _selectedRows, changeRows) => {
                let _list = [];
                if (selected) {
                  _list = _.uniq(selectUser.concat(changeRows), false, (item) => item.userId);
                } else {
                  _list = _.reject(selectUser, (item) => _.find(changeRows, (data) => data.userId === item.userId));
                }
                if (_list.length > 50) {
                  message.warning('无法继续选择，一个任务最多关联50个课程');
                  const extraLength = _list.length  - 50;
                  _list.splice(_list.length - extraLength, extraLength);
                }
                setSelectUser(_list);
              },
            }}
          />
          <div className="box-footer">
            <PageControl
              current={query.current - 1}
              pageSize={query.size}
              total={total}
              toPage={(page) => {
                const queryStates = _.clone(query);
                queryStates.current = page + 1;
                setQuery(queryStates);
                getUserList(null,null,queryStates.current);
              }}
            />
          </div>
        </div>
      </div>
      {chooseMembersModalVisible && (
        <NewChooseMembersModal
          visible={chooseMembersModalVisible}
          type="CUSTOMER"
          selectDep={selectDep}
          treeDepType={
            props.currentTab === "departMentTab" ? "DEP_CHAT" : "DEP_ORG"
          }
          addDepType={DepType[props.currentTab]}
          close={() => {
            closeChooseMembersModal();
          }}
          onConfirm={() => {
            confirmAddCustomer();
          }}
        />
      )}
    </div>
  );
}

export default withRouter(DepartMentTabCon);
