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 fakeData = [
  {
    isBlack: 0,
    id: 1,
    isLimit: 0,
  },
  {
    isBlack: 1,
    id: 2,
    isLimit: 1,
  },
];

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 [staffList, setStaffList] = useState([]);
  const [enterpriseList, setEnterpriseList] = useState([]);
  const [firstEnterprise, setFirstEnterprise] = useState();
  const [departmentList, setDepartmentList] = useState([]);
  const [generateLog, setGenerateLog] = useState([]);
  const [page, setPage] = useState({
    page: 1,
    size: 10,
  });
  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 data = [
    {
      enterpriseId: '企业id',
      id: '1',
      shopId: 'shopId',
      shopName: '店铺名称',
      mealType: '到店',
      pickselfName: '',
      updatedBy: '修改人名称',
      amount: '2023/03/21 14:06:11',
      isBlack: 0,
    },
    {
      enterpriseId: '企业id',
      id: '2',
      shopId: 'shopId',
      shopName: '店铺名称',
      mealType: '到店',
      pickselfName: '取餐点',
      updatedBy: '修改人名称',
      isBlack: 1,
    },
  ];

  const shopList = async () => {
    const res = await apiStaffList({ ...page, data: searchForm });
    if (res.businessCode === '0000' && res.data?.records?.length) {
      const list = res.data.records;
      setStaffList(list);
    }
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    getCheckboxProps: record => ({
      disabled: record.isBlack === 1,
    }),
  };

  // 关闭弹框
  const handleCloseModal = val => {
    setModalVisible(false);
    setDepartmentVisible(false);
    setViewDepartmentVisible(false);
    setBlacklistVisible(false);
    setRechargeDetailsVisible(false);
    if (val) {
      shopList();
    }
  };
  // 部门查询
  const getDepartmentList = async id => {
    const res = await apiDepartmentList({ 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 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,
      }));
      setFirstEnterprise(firstOption);
      setEnterpriseList(optionData);
      getDepartmentList(firstOption);
      shopList();
    }
  };
  // 设置黑名单
  const getBlacklist = () => {
    if (!selectedRowKeys.length) {
      notification.error({ message: '请选择员工' });
      return;
    }
    setBlacklistVisible(true);
  };
  useEffect(() => {
    getEnterpriseList();
  }, []);

  // 删除
  const deleteEmployee = async id => {
    const res = await apiStaffDelete({ id });
    if (res.businessCode === '0000') {
      message.success('删除成功！');
      shopList();
    }
  };
  // 删除
  const delEmployee = ({ staffName, id }) => {
    confirm({
      title: `确认删除企业员工#${staffName || ''}#?`,
      onOk() {
        deleteEmployee(id);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  // 添加商户
  const addShop = () => {
    setAddVisible(true);
  };
  // 搜索
  const onFinish = values => {
    setSearchForm(values);
    setPage({ current: 1, pageSize: 10 });
    shopList();
  };
  // 重置
  const onReset = () => {
    formRef.current.resetFields();
    shopList();
  };
  // 分页
  const handleTableChange = val => {
    setPage(val);
  };
  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,
      isLimit: checked ? 1 : 0,
      enterpriseId: searchForm.enterpriseId,
    });
    if (res.businessCode === '0000') {
      message.success('设置成功');
    }
  };
  const res = {
    delEmployee,
    goDetails,
    handleLimitChange,
  };
  return (
    <PageHeaderWrapper>
      <Card className={styles.card}>
        <Form ref={formRef} onFinish={onFinish} initialValue={{ enterpriseId: firstEnterprise }}>
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item
                label="企业名称"
                name="enterpriseId"
                wrapperCol={{ span: 16 }}
                rules={[{ required: true }]}
              >
                <Select
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                  options={enterpriseList}
                />
              </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="mealType" 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>
              <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>
      <Table
        columns={columns(res)}
        // dataSource={staffList}
        dataSource={fakeData}
        rowKey={r => r.id}
        bordered
        onChange={handleTableChange}
        rowSelection={rowSelection}
      />
      <NewEmployeeModal
        visible={modalVisible}
        enterpriseList={enterpriseList}
        departmentList={departmentList}
        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}
        employeeId={searchForm.enterpriseId}
      />
      <RechargeDetailsModal
        visible={rechargeDetailsVisible}
        list={generateLog}
        onClose={handleCloseModal}
      />
    </PageHeaderWrapper>
  );
};
export default StoreManagement;
