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';
import { stringOrObjectTrim } from '@/utils/utils';

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 => {
    // 去掉前后空格
    const data = stringOrObjectTrim(params);
    setLoading(true);
    const res = await apiStaffList(data);
    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);
        shopList({ ...page, data: searchForm });
        break;
      case 'department':
        setDepartmentVisible(false);
        getDepartmentList(searchForm.enterpriseId);
        break;
      case 'blacklist':
        setBlacklistVisible(false);
        setSelectedRowKeys([]);
        setSelectedRows([]);
        break;
      case 'rechargeDetails':
        setGenerateLog([]);
        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: $t('select.staff') });
      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($t('deleted.successfully'));
      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($t('setup.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={$t('enterprise.name')}
                  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={$t('department.query')} 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={$t('employee.mobile')} name="mobile" wrapperCol={{ span: 16 }}>
                  <Input maxLength="11" allowClear />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label={$t('employee.id')} name="staffNo" wrapperCol={{ span: 16 }}>
                  <Input allowClear />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label={$t('employee.status')} name="isBlack" wrapperCol={{ span: 16 }}>
                  <Select
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    options={[
                      {
                        value: 0,
                        label: $t('normal'),
                      },
                      {
                        value: 1,
                        label: $t('block'),
                      },
                    ]}
                    placeholder={$t('all')}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label={$t('employee.name')} name="staffName" wrapperCol={{ span: 16 }}>
                  <Input maxLength="8" allowClear />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item>
                  <Button type="primary" htmlType="submit">{$t('search')}</Button>
                  <Button htmlType="button" onClick={onReset} className={styles.left}>{$t('reset')}</Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        )}

        <div className={styles.addBtn}>
          <Button type="primary" className={styles.left} onClick={getBlacklist}>{$t('set.employee.blacklist')}</Button>
          <Button
            type="primary"
            className={styles.left}
            onClick={() => {
              setModalVisible(true);
            }}
          >{$t('add.new.staff')}</Button>
          <Button
            type="primary"
            className={styles.left}
            onClick={() => {
              setDepartmentVisible(true);
            }}
          >{$t('create.department')}</Button>
          <Button
            type="primary"
            className={styles.left}
            onClick={() => {
              setViewDepartmentVisible(true);
            }}
          >{$t('view.department')}</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;
