import { Button, DatePicker, Input, Select } from 'antd';
import { stringify } from 'qs';
import { useEffect, useRef, useState } from 'react';
import { FormItemPlugin, FormPlugin } from '@/components/FormPlugin';
import { GapBox } from '@/components/GapBox';
import PageContainerPlugin from '@/components/PageContainer/PageContainerPlugin';
import { FooterPagination, HeaderPagination } from '@/components/PaginationPlugin';
import { MoreSearchButton, SearchButton } from '@/components/SearchButton';
import type { ColumnsTypeUltra } from '@/components/TableColumnsFilterPlugin';
import { TablePlugin } from '@/components/TablePlugin';
import { staffType } from '@/configs/staffsConfig';
import { stateOptions, userSex, userState } from '@/configs/usersConfig';
import type { IAjaxDataBase, IParamsBase } from '@/interfaces/common';
import { type IUserEditModalType, UserEditModal } from '@/pages/User/List/components/UserEditModal';
import { UserServices } from '@/services/UserServices';
import { useAuthStore } from '@/store/AuthStore';
import { tableFixedByPhone, toArray } from '@/utils/common';
import { useRequest } from '@/utils/useRequest';

interface IAjaxData extends IAjaxDataBase {
  data: any[];
}
type IParams = IParamsBase & {
  login_name?: string;
  nick_name?: string;
  user_phone?: string;
  state?: number;
  create_dateL?: string;
  create_dateU?: string;
};

/** 企业列表页面 */
const CompanyListForm: React.FC = () => {
  const auth = useAuthStore().auth;
  const [params, setParams] = useState<IParams>({ curr_page: 1, page_count: 20 });
  const [ajaxData, setAjaxData] = useState<IAjaxData>({ count: 0, data: [] });
  const [showMoreSearch, setShowMoreSearch] = useState(false);
  const UserEditModalRef = useRef<IUserEditModalType>(null);

  const { loading: userLoading, request: userRequest } = useRequest(UserServices.getUserList, {
    onSuccessCodeZero: (res) => {
      setAjaxData({
        count: res.count || 0,
        data: toArray(res.data),
      });
    },
  });

  const columns: ColumnsTypeUltra<any> = [
    {
      title: '操作',
      width: 50,
      fixed: tableFixedByPhone('left'),
      render: (_, item) => (
        <GapBox>
          <Button
            type='primary'
            onClick={() => {
              UserEditModalRef.current?.show(item);
            }}
          >
            编辑
          </Button>
          {auth.SF_ERP_USER_EDIT && (
            <Button
              type='primary'
              onClick={() => {
                UserEditModalRef.current?.show(item);
              }}
            >
              编辑
            </Button>
          )}
        </GapBox>
      ),
    },
    { title: '用户名', dataIndex: 'login_name', width: 120 },
    { title: '企业名称', dataIndex: 'company_name', width: 120 },
    { title: '类型', dataIndex: 'staff_type', width: 60, render: (value) => staffType[value] },
    { title: '昵称', dataIndex: 'nick_name', width: 120 },
    { title: '手机', dataIndex: 'user_phone', width: 120 },
    { title: '性别', dataIndex: 'user_sex', width: 60, render: (value) => userSex[value] },
    { title: '状态', dataIndex: 'state', width: 60, ellipsis: true, render: (value) => userState[value] },
    {
      title: '备注',
      dataIndex: 'comments',
      width: 300,
    },
    {
      title: '创建时间',
      width: window.dfConfig.isPhone ? 160 : 160,
      dataIndex: 'create_date',
      ellipsis: true,
    },
  ];

  function page(curr: number) {
    if (!userLoading) {
      params.curr_page = curr;
      console.log(params);
      userRequest(stringify(params));
    }
  }

  useEffect(() => {
    page(1);
  }, []);

  return (
    <>
      <FormPlugin gutter={16}>
        <FormItemPlugin label={'用户名'}>
          <Input
            allowClear
            defaultValue={params.login_name}
            placeholder='用户名'
            onChange={(e) => {
              params.login_name = e.target.value.trim() || undefined;
            }}
            onPressEnter={() => page(1)}
          />
        </FormItemPlugin>
        <FormItemPlugin label={'昵称'}>
          <Input
            allowClear
            defaultValue={params.nick_name}
            placeholder='昵称'
            onChange={(e) => {
              params.nick_name = e.target.value.trim() || undefined;
            }}
            onPressEnter={() => page(1)}
          />
        </FormItemPlugin>
        <FormItemPlugin label={'手机号'}>
          <Input
            allowClear
            defaultValue={params.user_phone}
            placeholder='手机号'
            onChange={(e) => {
              params.user_phone = e.target.value.trim() || undefined;
            }}
            onPressEnter={() => page(1)}
          />
        </FormItemPlugin>

        <FormItemPlugin>
          <div
            style={{
              display: 'flex',
              flexWrap: 'nowrap',
              alignItems: 'center',
              whiteSpace: 'nowrap',
              gap: 8,
            }}
          >
            <SearchButton
              onClick={() => {
                page(1);
              }}
            />
            <MoreSearchButton
              show={showMoreSearch}
              onClick={() => {
                setShowMoreSearch((v) => !v);
              }}
            />
          </div>
        </FormItemPlugin>
      </FormPlugin>

      <FormPlugin style={{ display: showMoreSearch ? 'flex' : 'none' }} gutter={16}>
        <FormItemPlugin label={'状态'}>
          <Select
            allowClear
            value={params.state}
            options={stateOptions}
            onChange={(value) => {
              params.state = value || undefined;
              setParams({ ...params });
            }}
          />
        </FormItemPlugin>
        <FormItemPlugin label={'创建日期'}>
          <DatePicker.RangePicker
            style={{ width: '100%' }}
            onChange={(_values, dates) => {
              params.create_dateL = dates?.[0] || undefined;
              params.create_dateU = dates?.[1] || undefined;
            }}
          />
        </FormItemPlugin>
      </FormPlugin>

      <GapBox style={{ marginBottom: 12, justifyContent: 'space-between' }}>
        <GapBox>
          <Button
            type='primary'
            onClick={() => {
              UserEditModalRef.current?.show();
            }}
          >
            新增
          </Button>
        </GapBox>
        <HeaderPagination
          style={{ marginBottom: 0, marginRight: 12 }}
          current={params.curr_page}
          pageSize={params.page_count}
          total={ajaxData.count}
          onChange={page}
        />
      </GapBox>

      <TablePlugin
        loading={userLoading}
        onChange={(_p, _f, sort: any) => {
          page(1);
        }}
        dataSource={ajaxData.data}
        columns={columns}
        scroll={{ x: true }}
        rowKey={'user_id'}
      />

      <FooterPagination
        current={params.curr_page}
        pageSize={params.page_count}
        total={ajaxData.count}
        onChange={(curr, pageSize) => {
          params.page_count = pageSize;
          page(curr);
        }}
      />

      <UserEditModal ref={UserEditModalRef} onCallback={() => page(1)} />
    </>
  );
};

const CompanyList = () => (
  <PageContainerPlugin breadcrumb={['企业管理', '企业信息']}>
    <CompanyListForm />
  </PageContainerPlugin>
);
export default CompanyList;
