/*
 * @Author: wufan
 * @Date: 2020-07-09 14:03:09
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-11-28 13:53:12
 * 店铺管理-员工管理
 */
import React, { useEffect, useState } from "react";
import { withRouter } from "react-router-dom";
import _ from "underscore";
import PageControl from "@/components/PageControl";
import { CheckBox, SearchBar } from "@/components";
import { Button, Table, Tooltip, Modal, message, Row, Col, Input } from "antd";
import { QuestionCircleOutlined } from "@ant-design/icons";
import { storeRoleEnum } from "@/domains/store-domain/constants";
import StoreService from "@/domains/store-domain/storeService";
import EmployeeAddOrEditModal from "./EmployeeAddOrEditModal";
import User from "@/common/js/user";

import "./EmployeesManagePage.less";
import { string } from "prop-types";
const { confirm } = Modal;
const { Search } = Input;

declare var window: any;
interface RecordTypes {
  id: string;
  role: string;
  roleCodes: Array<string>;
  userId: string;
  nickName: string;
  phone: string;
  avatar?: string;
}

interface RoleItemType {
  isChecked: boolean;
  roleCode: string;
  name: string;
  id: string;
}

interface QueryType {
  current: number;
  size: number;
  nickName?: string;
  phone?: string;
  roleCodes: Array<string>;
  storeId: string | undefined | null;
}

interface ChoosedItemType {
  nickName?: string;
  phone?: string;
  role: Array<string>;
  avatar?: string;
  storeUserId?: string;
}

function EmployeesManagePage() {
  const [employeeList, setEmployeeList] = useState([]);
  const [query, setQuery] = useState<QueryType>({
    current: 0,
    size: 10,
    nickName: "",
    phone: "",
    roleCodes: ["StoreManager"],
    storeId: User.getStoreId(),
  });

  const [valueLike, setValueLike] = useState();
  const [total, setTotal] = useState(0);
  const [model, setModel] = useState<React.ReactNode>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isManager, setIsManager] = useState(true);
  const [isNormal, setIsNormal] = useState(true);
  const [choosedItem, setChooseItem] = useState<ChoosedItemType>({
    nickName: "",
    phone: "",
    role: [],
    avatar: "",
  });
  const [roleIds, setRoleIds] = useState<Array<RoleItemType>>([]);
  const roleMap = {
    CloudManager: "管理员",
    CloudLecturer: "讲师",
    StoreManager: "店铺管理员",
  };
  const storeId = User.getStoreId();

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

  useEffect(() => {
    getListInfo();
  }, [storeId]);

  async function getListInfo() {
    await getStoreRole();
    await getEmployeeList();
  }

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

  function getStoreRole() {
    StoreService.getStoreRole({ storeId }).then((res: any) => {
      const data = [...res.result];
      const _query = { ...query };

      let _data = _.filter(data, _item => {
       return _item.roleCode !== "StoreManager";
      });

      _data = _.map(_data, (item: any) => {
        item.isChecked = true;
        _query.roleCodes.push(item.roleCode);
        return item;
      });


      setQuery(_query);
      setRoleIds(_data);
    });
  }

  function parseColumn() {
    return [
      {
        title: "员工",
        dataIndex: "nickName",
        render: (val: string) => {
          return (
            <div className="coupon-info">
              <span className="title">{val}</span>
            </div>
          );
        },
      },
      {
        title: "手机号",
        dataIndex: "phone",
        key: "phone",
        render: (val: string) => {
          return <div>{val}</div>;
        },
      },
      {
        title: "身份",
        dataIndex: "role",
        key: "role",
        render: (val: string) => {
          return <div>{val.split("，").join("、")}</div>;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        render: (val: string, record: RecordTypes) => {
          return record.role === "店铺管理员" ||
            record.userId === User.getUserId() ? (
            <div className="no-operate">-</div>
          ) : (
            <div className="operation">
              <span className="edit" onClick={() => handleEditEmployee(record)}>
                编辑
              </span>
              <span className="divider-line">{" | "}</span>
              <span
                className="delete"
                onClick={() => handleDeleteEmployeeConfirm(record)}
              >
                删除
              </span>
            </div>
          );
        },
      },
    ];
  }

  function handleEditEmployee(record: RecordTypes) {
    const { nickName, phone, roleCodes, avatar, id } = record;
    const _choosesItem = {
      nickName: nickName,
      phone: phone,
      role: roleCodes,
      avatar: avatar,
      storeUserId: id,
    };
    setChooseItem(_choosesItem);
    const model: React.ReactNode = (
      <EmployeeAddOrEditModal
        isOpen={true}
        choosedItem={_choosesItem}
        onClose={() => {
          setModel(null);
          getEmployeeList();
        }}
      />
    );
    setModel(model);
  }

  function handleDeleteEmployeeConfirm(record: RecordTypes) {
    return confirm({
      title: "你确定要删除此讲师吗？",
      content: "删除后，讲师将不能登录系统，此操作不能被撤销",
      icon: <QuestionCircleOutlined />,
      okText: "删除",
      okType: "danger",
      cancelText: "取消",
      onOk: () => {
        handleDeleteEmployee(record.id);
      },
    });
  }

  function handleToAddEmployee() {
    setIsModalOpen(true);
  }

  function handleDeleteEmployee(storeUserId: string) {
    StoreService.deleteEmployee({ storeUserId }).then((res: any) => {
      message.success("讲师已删除");
      getEmployeeList();
    });
  }

  function handleQuery(name: string, value: any) {
    const _query = _.clone(query);
    // _query[name] = value;
    setQuery(_query);
  }

  return (
    <div className=" page employee-manage-page">
      <div className="page-content">
        <div className="content-header">员工管理</div>
        <div className="box">
          <div className="box-header">
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                padding: "15px 0 10px",
              }}
            >
              <div style={{ flex: 1 }}>
                搜索员工：
                <Search
                  style={{
                    width: 300,
                    marginRight: 40,
                  }}
                  placeholder="搜索员工姓名/手机号"
                  onChange={(event) => {
                    const val = event.target.value;
                    const _query = { ...query };
                    _query.nickName = val;
                    setQuery(_query);
                  }}
                  onSearch={() => getEmployeeList()}
                />
                {/* <SearchBar
                  label="搜索用户"
                  placeholder="搜索用户姓名/手机号"
                  style={{
                    width: 300,
                    marginRight: 40,
                  }}
                  value={valueLike}
                  onSearch={(value: any) => {
                    const _query = { ...query };
                    if (valu                      const isPhone = (value || "").match(/^\d+$/);
                      const nameLike = isPhone ? "phone" : "nickName";
                      setValueLike(value);
                      _query[nameLike] = value;
                    } else {
                      _query.nickName = "";
                      _query.phone = "";
                    }
                    setQuery(_query);
                  }}
                /> */}
              </div>

              <div style={{ flex: 1 }}>
                身份：
                {_.map(roleIds, (item: any) => {
                  return (
                    <CheckBox
                      text={item.name}
                      name={item.roleCode}
                      onChange={(e: any) => {
                        const { checked, name } = e.target;
                        const _query = { ...query };
                        _query.roleCodes = [];

                        const _roleIds: Array<RoleItemType> = roleIds.map(
                          (_item: RoleItemType) => {
                            if (name === _item.roleCode) {
                              if (checked) {
                                _item.isChecked = true;
                              } else {
                                _item.isChecked = false;
                              }
                            }
                            if (_item.isChecked) {
                              _query.roleCodes.push(_item.roleCode);
                            }
                            return _item;
                          }
                        );

                        setRoleIds(_roleIds);
                        setQuery(_query);
                      }}
                      defaultChecked={item.isChecked}
                    />
                  );
                })}
              </div>
            </div>
            <Button
              onClick={() => {
                handleToAddEmployee();
              }}
              type="primary"
              className="add-show-btn"
            >
              添加员工
            </Button>
          </div>
          <div className="box-body">
            <Table
              size={"middle"}
              pagination={false}
              dataSource={employeeList}
              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>
        {isModalOpen && (
          <EmployeeAddOrEditModal
            isOpen={isModalOpen}
            choosedItem={choosedItem}
            onClose={() => {
              setIsModalOpen(false);
              getEmployeeList();
            }}
          />
        )}
        {model}
      </div>
    </div>
  );
}

export default withRouter(EmployeesManagePage);
