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 { statusObj, statusOptions } from '@/configs/adminGrpConfig';
import type { IAjaxDataBase, IParamsBase } from '@/interfaces/common';
import { AdminGroupServices } from '@/services/AdminGroupServices';
import { useAuthStore } from '@/store/AuthStore';
import { tableFixedByPhone, toArray } from '@/utils/common';
import { useRequest } from '@/utils/useRequest';
import { AdminGrpEditModal, type IAdminGrpEditModalType } from './components/AdminGrpEditModal';

interface IAjaxData extends IAjaxDataBase {
  data: any[];
}
type IParams = IParamsBase & {
  name?: string;
  status?: number;
  create_dateL?: string;
  create_dateU?: string;
};

/** 岗位角色列表页面 */
const GrpListForm: 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 AdminGrpEditModalRef = useRef<IAdminGrpEditModalType>(null);

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

  const { request: deleteAdminGroupRequest } = useRequest(AdminGroupServices.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?.group_id != 1 && (
            <>
              <Button
                type='primary'
                onClick={() => {
                  AdminGrpEditModalRef.current?.show(item);
                }}
              >
                编辑
              </Button>
              <Popconfirm
                placement='bottom'
                title='确认删除该岗位角色吗？'
                onConfirm={() => {
                  deleteAdminGroupRequest(stringify({ group_id: item.group_id }));
                }}
              >
                <Button danger>删除</Button>
              </Popconfirm>
            </>
          )}
        </GapBox>
      ),
    },
    { title: '岗位角色', dataIndex: 'name', width: 120 },
    { title: '状态', dataIndex: 'status', width: 60, ellipsis: true, render: (value) => statusObj[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.name}
            placeholder='岗位角色'
            onChange={(e) => {
              params.name = e.target.value.trim() || undefined;
            }}
            onPressEnter={() => page(1)}
          />
        </FormItemPlugin>
        <FormItemPlugin label={'状态'}>
          <Select
            allowClear
            value={params.status}
            options={statusOptions}
            onChange={(value) => {
              params.status = 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>
          <Button
            type='primary'
            onClick={() => {
              AdminGrpEditModalRef.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={'group_id'}
      />

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

      <AdminGrpEditModal ref={AdminGrpEditModalRef} onCallback={() => page(1)} />
    </>
  );
};

const Grp = () => (
  <PageContainerPlugin breadcrumb={['权限管理', '岗位角色']}>
    <GrpListForm />
  </PageContainerPlugin>
);
export default Grp;
