import React, { useState, useRef, forwardRef, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Modal,
  Form,
  Select,
  Table,
  Card,
  Row,
  Col,
  Input,
  Button,
  message,
  Upload,
  notification,
} from 'antd';
import { columns, repastTypeList } from './data';
import styles from './index.less';
import {
  apiStaffList,
  apiEnterpriseList,
  apiDepartmentList,
  apiStaffExcel,
  apiStaffDelete,
  apiGenerateLogList,
  apiStaffLimit,
} from './service.js';
import NewEmployeeModal from './components/newEmployeeModal';
import DepartmentModal from './components/departmentModal';
import ViewDepartmentModal from './components/viewDepartmentModal';
import BlacklistModal from './components/blacklistModal';
import RechargeDetailsModal from './components/RechargeDetailsModal';

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 8 },
};
const { confirm } = Modal;
const StoreManagement = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [departmentVisible, setDepartmentVisible] = useState(false);
  const [viewDepartmentVisible, setViewDepartmentVisible] = useState(false);
  const [blacklistVisible, setBlacklistVisible] = useState(false);
  const [rechargeDetailsVisible, setRechargeDetailsVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [staffList, setStaffList] = useState([]);
  const [enterpriseList, setEnterpriseList] = useState([]);
  const [firstEnterprise, setFirstEnterprise] = useState();
  const [departmentList, setDepartmentList] = useState([]);
  const [generateLog, setGenerateLog] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState({
    current: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [searchForm, setSearchForm] = useState({});
  const formRef = useRef(null);
  const [editVisible, setEditVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [repastType, setRepastType] = useState([]);
  const [repastId, setRepastId] = useState(null);

  const shopList = async params => {
    setLoading(true);
    const res = await apiStaffList(params);
    if (res?.businessCode === '0000') {
      const list = res.data?.records;
      setTotal(res.data.total);
      setStaffList(list);
      setLoading(false);
      return;
    }
    setTimeout(() => {
      setLoading(false);
      setStaffList([]);
      setTotal(0);
    }, 5000);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: (select, selectList) => {
      setSelectedRowKeys(select);
      setSelectedRows(selectList);
    },
    getCheckboxProps: record => ({
      disabled: record.isBlack === 1,
    }),
  };
  // 部门查询
  const getDepartmentList = async id => {
    const res = await apiDepartmentList({ data: { enterpriseId: id }, page: 1, size: 10000 });
    if (res.businessCode === '0000' && res.data?.records?.length) {
      const list = res.data.records;
      const optionData = list.map(item => ({
        value: item.id,
        label: item.name,
      }));
      setDepartmentList(optionData);
      return;
    }
    setDepartmentList([]);
  };
  // 关闭弹框
  const handleCloseModal = (status, val) => {
    switch (val) {
      case 'newEmployee':
        setModalVisible(false);
        break;
      case 'viewDepartment':
        setViewDepartmentVisible(false);
        getDepartmentList(searchForm.enterpriseId);
        break;
      case 'department':
        setDepartmentVisible(false);
        break;
      case 'blacklist':
        setBlacklistVisible(false);
        setSelectedRowKeys([]);
        setSelectedRows([]);
        break;
      case 'rechargeDetails':
        setRechargeDetailsVisible(false);
        break;
      default:
        break;
    }
    if (status) {
      shopList({ ...page, data: searchForm });
    }
  };

  // 企业查询
  const getEnterpriseList = async () => {
    const res = await apiEnterpriseList();
    if (res.businessCode === '0000' && res.data?.records?.length) {
      const list = res.data.records;
      const firstOption = list[0].id;
      const optionData = list.map(item => ({
        value: item.id,
        label: item.name,
      }));
      setEnterpriseList(optionData);
      setFirstEnterprise(firstOption);
      getDepartmentList(firstOption);
      setSearchForm({ enterpriseId: firstOption });
      shopList({ ...page, data: { enterpriseId: firstOption } });
    }
  };

  // 设置黑名单
  const getBlacklist = () => {
    if (!selectedRowKeys.length) {
      notification.error({ message: '请选择员工' });
      return;
    }
    setBlacklistVisible(true);
  };
  useEffect(() => {
    getEnterpriseList();
  }, []);
  // 删除
  const deleteEmployee = async id => {
    const res = await apiStaffDelete({ id, enterpriseId: searchForm.enterpriseId, state: 0 });
    if (res.businessCode === '0000') {
      message.success('删除成功！');
      shopList({ ...page, data: searchForm });
    }
  };
  // 删除
  const delEmployee = ({ staffName, id }) => {
    confirm({
      title: `确认删除企业员工#${staffName || ''}#?`,
      onOk() {
        deleteEmployee(id);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  // 添加商户
  const addShop = () => {
    setAddVisible(true);
  };
  // 搜索
  const onFinish = values => {
    setSearchForm(values);
    const pageInfo = {
      current: 1,
      pageSize: 10,
    };
    setPage(pageInfo);
    shopList({ ...pageInfo, data: values });
  };
  // 重置
  const onReset = () => {
    formRef.current.resetFields();
    setSearchForm({ enterpriseId: firstEnterprise });
    shopList({ ...page, data: { enterpriseId: firstEnterprise } });
  };
  // 分页
  const onChange = (current, pageSize) => {
    const pageInfo = {
      current,
      pageSize,
    };
    setPage(pageInfo);
    shopList({ data: searchForm, ...pageInfo });
  };
  const goDetails = async ({ staffNo }) => {
    setRechargeDetailsVisible(true);
    const res = await apiGenerateLogList({ staffNo, enterpriseId: searchForm.enterpriseId });
    if (res.businessCode === '0000') {
      const list = res.data;
      setGenerateLog(list);
    }
  };
  const handleLimitChange = async (checked, row) => {
    const res = await apiStaffLimit({
      id: row.id,
      isLimit: checked ? 1 : 0,
      enterpriseId: searchForm.enterpriseId,
    });
    if (res.businessCode === '0000') {
      message.success('设置成功');
      shopList({ ...page, data: searchForm });
    }
  };
  const enterpriseOnChange = val => {
    setFirstEnterprise(val);
    getDepartmentList(val);
    const pageInfo = {
      current: 1,
      pageSize: 10,
    };
    const values = formRef.current.getFieldsValue();
    setPage(pageInfo);
    setSearchForm(values);
    shopList({ ...pageInfo, data: values });
  };
  const res = {
    delEmployee,
    goDetails,
    handleLimitChange,
  };
  const pagination = {
    ...page,
    total,
    showTotal: t => `共 ${t} 条`,
    onChange,
    onShowSizeChange: onChange,
  };
  return (
    <PageHeaderWrapper>
      <Card className={styles.card}>
        {firstEnterprise && (
          <Form ref={formRef} onFinish={onFinish} {...layout}>
            <Row gutter={24}>
              <Col span={8}>
                <Form.Item
                  label="企业名称"
                  name="enterpriseId"
                  wrapperCol={{ span: 16 }}
                  rules={[{ required: true }]}
                  initialValue={firstEnterprise}
                >
                  <Select
                    showSearch
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    options={enterpriseList}
                    onChange={enterpriseOnChange}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="部门查询" name="departmentIds" wrapperCol={{ span: 16 }}>
                  <Select
                    mode="multiple"
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    options={departmentList}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="员工手机号" name="mobile" wrapperCol={{ span: 16 }}>
                  <Input maxLength="11" allowClear />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="员工id" name="staffNo" wrapperCol={{ span: 16 }}>
                  <Input allowClear />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="员工状态" name="isBlack" wrapperCol={{ span: 16 }}>
                  <Select
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    options={[
                      {
                        value: 0,
                        label: '正常',
                      },
                      {
                        value: 1,
                        label: '拉黑',
                      },
                    ]}
                    placeholder="全部"
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="员工姓名" name="staffName" wrapperCol={{ span: 16 }}>
                  <Input maxLength="8" allowClear />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                  <Button htmlType="button" onClick={onReset} className={styles.left}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        )}

        <div className={styles.addBtn}>
          <Button type="primary" className={styles.left} onClick={getBlacklist}>
            设置员工黑名单
          </Button>
          <Button
            type="primary"
            className={styles.left}
            onClick={() => {
              setModalVisible(true);
            }}
          >
            添加新员工
          </Button>
          <Button
            type="primary"
            className={styles.left}
            onClick={() => {
              setDepartmentVisible(true);
            }}
          >
            创建部门
          </Button>
          <Button
            type="primary"
            className={styles.left}
            onClick={() => {
              setViewDepartmentVisible(true);
            }}
          >
            查看部门
          </Button>
        </div>
      </Card>
      <Card>
        <Table
          columns={columns(res)}
          dataSource={staffList}
          rowKey={r => r.id}
          bordered
          rowSelection={rowSelection}
          pagination={pagination}
          loading={loading}
        />
      </Card>
      <NewEmployeeModal
        visible={modalVisible}
        enterpriseList={enterpriseList}
        onClose={handleCloseModal}
        getDepartmentList={getDepartmentList}
      />
      <DepartmentModal
        visible={departmentVisible}
        enterpriseList={enterpriseList}
        onClose={handleCloseModal}
      />
      <ViewDepartmentModal
        visible={viewDepartmentVisible}
        enterpriseList={enterpriseList}
        onClose={handleCloseModal}
      />
      <BlacklistModal
        list={selectedRowKeys}
        visible={blacklistVisible}
        onClose={handleCloseModal}
        enterpriseId={searchForm.enterpriseId}
        selectedRows={selectedRows}
      />
      <RechargeDetailsModal
        visible={rechargeDetailsVisible}
        list={generateLog}
        onClose={handleCloseModal}
      />
    </PageHeaderWrapper>
  );
};
export default StoreManagement;
