import { useAjax } from '@/Hook/useAjax';
import {
  apiDistributorInfo,
  apiDistributorInfoPageList,
  apiDistributorInfoRemove,
  apiDistributorInfoUpdate,
} from '@/services/distribution/info';
import { PlusCircleOutlined } from '@ant-design/icons';
import {
  ActionType,
  BetaSchemaForm,
  PageContainer,
  ProFormInstance,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { formConfig } from './formConfig';
import Item from './item';
import { columns } from './tableConfig';
import MyProTable from '@/components/MyProTable';
type DataItem = {
  name: string;
  state: string;
};
const Page: React.FC = () => {
  let { state, getLabelAndClassList } = useModel('global');
  let [open, setOpen] = useState<any>(null); //付费配置
  let [editValues, setEditValues] = useState<any>({});
  let [workDirection, setWorkDirection] = useState<any>(null);
  const [userManage, setUserManage] = useState<any>(null); //账号管理
  const [editSelectedRow, setEditSelectedRow] = useState<any[]>([]); //小说列表选择

  // ======================API=======================
  let DistributorInfoPageList = useAjax((params) => apiDistributorInfoPageList(params), {
    type: 'table',
  }); //分销商分页列表
  let DistributorInfoUpdate = useAjax((params) => apiDistributorInfoUpdate(params)); //修改
  let DistributorInfo = useAjax((params) => apiDistributorInfo(params)); //新增
  let DistributorInfoRemove = useAjax((distributorId) => apiDistributorInfoRemove(distributorId)); //分销商删除
  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();

  // 获取标签和分类
  useEffect(() => {
    getLabelAndClassList({ workDirection });
  }, [workDirection]);
  // 删除or批量删除
  const del = (id: any) => {
    DistributorInfoRemove.run(id).then((res) => {
      if (res.code === 200) {
        actionRef?.current?.reload();
        message.success('删除成功');
        setEditSelectedRow([]);
      }
    });
  };
  // 提交表单
  const submit = async (values: any) => {
    let api = editValues?.id ? DistributorInfoUpdate : DistributorInfo;
    if (editValues?.id) {
      values.id = editValues?.id;
    }
    api.run(values).then((res) => {
      if (res.code === 200) {
        actionRef?.current?.reload();
        message.success('操作成功!');
        closeForm(false);
      }
    });
  };
  // 关闭表单弹窗和重置表单内容
  const closeForm = (b: boolean, values?: any) => {
    if (!b) {
      setEditValues({});
      formRef?.current?.resetFields?.();
      setOpen(b);
    } else {
      setEditValues(values);
      setWorkDirection(values.workDirection);
      setTimeout(() => {
        formRef?.current?.setFieldsValue(values);
      }, 100);
      setOpen(b);
    }
  };
  return (
    <PageContainer title={false} tabProps={{ type: 'card' }}>
      <MyProTable<any, any>
        // 实例
        actionRef={actionRef}
        // 标题
        headerTitle={'短篇小说列表'}
        // 唯一key
        rowKey={(r) => r.id}
        // 按钮
        toolBarRender={() => {
          return [
            <Button
              type="primary"
              onClick={() => {
                setOpen(true);
              }}
            >
              <PlusCircleOutlined />
              新增分销商
            </Button>,
          ];
        }}
        //宽度自适应
        scroll={{ x: true }}
        // 加载
        loading={DistributorInfoPageList?.loading}
        // 搜索的配置
        search={{
          labelWidth: 120,
          searchGutter: [10, 15],
        }}
        // 数据请求
        request={async (params) => {
          return await DistributorInfoPageList.run(params);
        }}
        // 表
        columns={columns({ del, edit: closeForm, setUserManage })}
      />
      {/* 新增分销商 */}
      <BetaSchemaForm<DataItem>
        layout="horizontal"
        title={!editValues?.id ? '新增分销商' : '编辑分销商'}
        formRef={formRef}
        open={open}
        onOpenChange={(b) => {
          !b && closeForm(b);
        }}
        layoutType={'ModalForm'}
        rowProps={{
          gutter: [16, 16],
        }}
        labelCol={{ span: 6 }}
        colProps={{
          span: 20,
        }}
        grid={true}
        onFinish={submit}
        columns={formConfig()}
        loading={DistributorInfo?.loading || DistributorInfoUpdate?.loading}
      />
      {/* 账号管理 */}
      <Item data={userManage} onClose={setUserManage} />
    </PageContainer>
  );
};
export default Page;
