/*
 * @Author: wufan
 * @Date: 2020-11-30 10:47:38
 * @LastEditors: wufan
 * @LastEditTime: 2021-06-21 11:13:15
 * @Description: 学员管理页面
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React, { useEffect, useState } from "react";
import { withRouter } from "react-router-dom";
import _ from "underscore";
import { PageControl } from "@/components";
import { Input, DatePicker, Select, Button, message } from "antd";
import StoreService from "@/domains/store-domain/storeService";
import User from "@/common/js/user";
import ChooseMembersModal from "./modal/ChooseMembersModal";
import LimitTip from "./LimitTip"

import { XMTable } from '@/components';
import college from '@/common/lottie/college.json';
import "./UserManagePage.less";
import moment from "moment";

const { Option } = Select;
const { Search } = Input;
const { RangePicker } = DatePicker;

declare var window: any;



function UserManagePage() {
  const [userList, setUserList] = useState([]);
  const [model, setModel] = useState<React.ReactNode>(null);
  const [query, setQuery] = useState({
    current: 0,
    size: 10,
    nickName: "",
    phone: "",
    registerBegin: null,
    registerEnd: null,
    sourceEnum: undefined,
  });
  const [total, setTotal] = useState(0);
  const [realTotal, setRealTotal] = useState(0)

  useEffect(() => {
    if (!User.getEnterpriseId()) {
      window.RCHistory.replace('/user-manage');
    }
    //获取学员数
    const _query = {
      current: 0,
      size: 10,
      nickName: "",
      phone: "",
      registerBegin: null,
      registerEnd: null,
      sourceEnum: undefined,
    }
    StoreService.getUserList(_query).then((res: any) => {
      setRealTotal(res.result.total);
    });
  }, [])

  useEffect(() => {
    getUserList();
  }, [query]);

  function getUserList() {
    let _query = _.clone(query);
    _query.current = query.current + 1;
    StoreService.getUserList(_query).then((res: any) => {
      setUserList(res.result.records);
      setTotal(res.result.total);
    });
  }

  function parseColumn() {
    const list = [
      {
        title: "学员姓名",
        dataIndex: "nickName",
        render: (val: string, item: any) => {
          return (
            <div className="coupon-info">
              <span className="title">{val}</span>
              <span
                className="tag"
                style={{ color: item.sourceEnum === 'WORK_WE_CHAT' ? '#2966FF' : '#1DCC65'}}
              >{item.sourceEnum === 'WORK_WE_CHAT' ? '@企业微信' : '@微信'}</span>
            </div>
          );
        },
      },
      {
        title: "手机号",
        dataIndex: "phone",
        key: "phone",
        render: (val: string) => {
          return <div>{val || '-'}</div>;
        },
      },
      {
        title: "注册时间",
        dataIndex: "created",
        key: "created",
        render: (val: string) => {
          return <div>{moment(val).format("YYYY-MM-DD HH:mm:ss")}</div>;
        },
      },
    ];
    if (User.getUserRole() !== 'StoreManager') {
      list.splice(1, 1);
    }
    return list;
  }

  function handleToAddEmployee() {
    const model: React.ReactNode = (
      <ChooseMembersModal
        isOpen={true}
        type="CUSTOMER"
        handleChooseModal={(bool: any) => {
          setModel(null)
          if (bool) {
            message.success('添加成功')
            getUserList();
          }
        }}
      />
    );
    setModel(model);
  }


  return (
    <div className=" page user-manage-page">
        <div className="content-header">学员管理</div>
        <div className="box">
          <div className="box-header">
            <div className="header-item">
              <span className="item-name">搜索学员：</span>
              <Search
                placeholder="搜索学员姓名/手机号"
                onSearch={(value) => {
                  const _query = { ...query };
                  if (value) {
                    console.log("value", value);
                    const isPhone = (value || "").match(/^\d+$/);
                    const name = isPhone ? "phone" : "nickName";
                    _query.nickName = "";
                    _query.phone = "";
                    _query[name] = value;
                    _query.current = 0;
                  } else {
                    _query.nickName = "";
                    _query.phone = "";
                    _query.current = 0;
                  }
                  setQuery(_query);
                }}
                enterButton={<span className="icon iconfont">&#xe832;</span>}
              />

            </div>
            <div className="header-item">
              <span className="item-name">学员来源：</span>
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                  allowClear
                  onChange={(value) => {
                    const _query: any = _.clone(query);
                    _query.sourceEnum = value;
                    _query.current = 0;
                    setQuery(_query);
                  }}
                >
                <Option value="WORK_WE_CHAT">企业微信</Option>
                <Option value="WE_CHAT">微信</Option>
              </Select>
            </div>

            <div className="header-item">
              <span className="item-name">注册时间：</span>
              <RangePicker
                style={{ flex: 1, width: "auto" }}
                value={
                  query.registerBegin
                    ? [moment(query.registerBegin), moment(query.registerEnd)]
                    : null
                }
                format={"YYYY-MM-DD"}
                onChange={(dates: any) => {
                  const _query = _.clone(query);
                  _query.registerBegin = dates ? dates[0].startOf("day").valueOf() : null;
                  _query.registerEnd = dates ? dates[1].endOf("day").valueOf() : null;
                  _query.current = 0;
                  setQuery({
                    ..._query
                      });
                }}
              />
            </div>
        </div>
        {(User.getUserRole() === 'CloudManager' || User.getUserRole() ==='StoreManager') &&
          <Button
            type="primary"
            style={{ marginBottom: 12 }}
            onClick={() => {
              handleToAddEmployee();
            }}
          >添加学员</Button>
        }
        <LimitTip type="学员" total={realTotal} tip={()=>{ return (<div><div>1、数据为当前学院的员工数，若学员存在多个学院，企业人数只统计为1人；</div><div>2、若一个学员既用「企业微信」登录学习又用「微信」登录学习，企业人数将统计为2人。</div></div>)}}/>
        <div className="box-body">
        <XMTable 
            renderEmpty={{
              image: college,
              description: '暂无数据'
            }} 
            size={"middle"}
            pagination={false}
            dataSource={userList}
            columns={parseColumn()}
            rowKey={(item: any) => item.id}
            bordered
          />
        </div>
        <div className="box-footer">
          <PageControl
            current={query.current}
            pageSize={query.size}
            total={total}
            toPage={(page: any) => {
              const queryStates = _.clone(query);
              queryStates.current = page;
              setQuery(queryStates);
            }}
          />
        </div>
      </div>
      {model}
    </div>
  );
}

export default withRouter(UserManagePage);
