import { Button, DatePicker, Input, notification, Popconfirm, 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 { SearchButton } from '@/components/SearchButton';
import type { ColumnsTypeUltra } from '@/components/TableColumnsFilterPlugin';
import { TablePlugin } from '@/components/TablePlugin';
import { stateObj, stateOptions } from '@/configs/adminDepConfig';
import type { IAjaxDataBase, IParamsBase } from '@/interfaces/common';
import { AdminDepartmentServices } from '@/services/AdminDepartmentServices';
import { useAuthStore } from '@/store/AuthStore';
import { tableFixedByPhone, toArray } from '@/utils/common';
import { useRequest } from '@/utils/useRequest';
import { AdminDepEditModal, type IAdminDepEditModalType } from './components/AdminDepEditModal';

interface IAjaxData extends IAjaxDataBase {
  data: any[];
}
type IParams = IParamsBase & {
  department_name?: string;
  nickname?: string;
  mobile?: string;
  state?: number;
  create_dateL?: string;
  create_dateU?: string;
};

/** 组织架构列表页面 */
const DepListForm: 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 AdminDepEditModalRef = useRef<IAdminDepEditModalType>(null);

  const { loading: listLoading, request: listRequest } = useRequest(AdminDepartmentServices.getAdminDepartmentList, {
    onSuccessCodeZero: (res) => {
      setAjaxData({
        count: res.count || 0,
        data: toArray(res.data),
      });
    },
  });

  const { request: deleteAdminDepartmentRequest } = useRequest(AdminDepartmentServices.del, {
    onSuccessCodeZero: (res) => {
      if (res.err_code == 0) {
        notification.success({ message: '删除成功' });
        page(params.curr_page);
      }
    },
  });

  const columns: ColumnsTypeUltra<any> = [
    {
      title: '操作',
      width: 50,
      fixed: tableFixedByPhone('left'),
      render: (_, item) => (
        <GapBox>
          {item?.admin_id != 1 && (
            <>
              {auth.SF_ADMIN_DEPART_EDIT && (
                <Button
                  type='primary'
                  onClick={() => {
                    AdminDepEditModalRef.current?.show(item);
                  }}
                >
                  编辑
                </Button>
              )}
              {auth.SF_ADMIN_DEPART_DEL && (
                <Popconfirm
                  placement='top'
                  title='确认删除该组织架构吗？'
                  onConfirm={() => {
                    deleteAdminDepartmentRequest(stringify({ department_id: item.department_id }));
                  }}
                >
                  <Button danger>删除</Button>
                </Popconfirm>
              )}
            </>
          )}
        </GapBox>
      ),
    },
    { title: '组织架构', dataIndex: 'department_name', width: 120 },
    { title: '状态', dataIndex: 'state', width: 60, ellipsis: true, render: (value) => stateObj[value] },
    { title: '备注', dataIndex: 'comments', width: 120 },
    {
      title: '创建时间',
      width: window.dfConfig.isPhone ? 160 : 160,
      dataIndex: 'create_date',
      ellipsis: true,
    },
  ];

  function page(curr: number) {
    if (!listLoading) {
      params.curr_page = curr;
      listRequest(stringify(params));
    }
  }

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

  return (
    <>
      <FormPlugin gutter={16}>
        <FormItemPlugin label={'组织架构'}>
          <Input
            allowClear
            defaultValue={params.department_name}
            placeholder='组织架构'
            onChange={(e) => {
              params.department_name = e.target.value.trim() || undefined;
            }}
            onPressEnter={() => page(1)}
          />
        </FormItemPlugin>
        <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>

        <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={statusOptions}
            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>
          {auth.SF_ADMIN_DEPART_ADD && (
            <Button
              type='primary'
              onClick={() => {
                AdminDepEditModalRef.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={listLoading}
        onChange={(_p, _f, sort: any) => {
          page(1);
        }}
        dataSource={ajaxData.data}
        columns={columns}
        scroll={{ x: true }}
        rowKey={'department_id'}
      />

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

      <AdminDepEditModal ref={AdminDepEditModalRef} onCallback={() => page(1)} />
    </>
  );
};

const Dep = () => (
  <PageContainerPlugin breadcrumb={['权限管理', '组织架构']}>
    <DepListForm />
  </PageContainerPlugin>
);
export default Dep;
