import ReadText from '@/components/readText';
import { useAjax } from '@/Hook/useAjax';
import {
  apiBookContentShortBookInfoAdd,
  apiBookContentShortBookInfoBatch,
  apiBookContentShortBookInfoDel,
  apiBookContentShortBookInfoDels,
  apiBookContentShortBookInfoEdit,
  apiBookContentShortBookInfoList,
  apiShortBookGetInfo,
} from '@/services/book/shortbookList';
import { ColumnHeightOutlined, DeleteOutlined, PlusCircleOutlined } from '@ant-design/icons';
import {
  ActionType,
  BetaSchemaForm,
  PageContainer,
  ProFormInstance,
  ProTable,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Drawer, message, Popconfirm, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';
import formConfig from './formConfig';
import Item from './item';
import { columns } from './tableConfig';
const wordCountRanges: any = {
  '': { start: null, end: null }, // 全部
  '0-2': { start: 0, end: 2 * 10000 },
  '2-5': { start: 2 * 10000, end: 5 * 10000 },
  '5-10': { start: 5 * 10000, end: 10 * 10000 },
  '10-20': { start: 10 * 10000, end: 20 * 10000 },
  '20-40': { start: 20 * 10000, end: 40 * 10000 },
  '40-100': { start: 40 * 10000, end: 100 * 10000 },
  '100-150': { start: 100 * 10000, end: 150 * 10000 },
  '150-200': { start: 150 * 10000, end: 200 * 10000 },
  '200-300': { start: 200 * 10000, end: 300 * 10000 },
  '300-0': { start: 300 * 10000, end: null }, // 300万以上
};
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 [openBook, setOpneBook] = useState<any>(null); //阅读小说
  const [editSelectedRow, setEditSelectedRow] = useState<any[]>([]); //小说列表选择

  // ======================API=======================
  let BookContentShortBookInfoList = useAjax((params) => apiBookContentShortBookInfoList(params), {
    type: 'table',
  }); //获取书籍列表
  let BookContentShortBookInfoAdd = useAjax((params) => apiBookContentShortBookInfoAdd(params)); //新增书籍
  let BookContentShortBookInfoEdit = useAjax((params) => apiBookContentShortBookInfoEdit(params)); //编辑书籍
  let BookContentShortBookInfoDel = useAjax((id) => apiBookContentShortBookInfoDel(id)); //单个删除书籍
  let BookContentShortBookInfoDels = useAjax((ids) => apiBookContentShortBookInfoDels(ids)); //批量删除书籍
  let BookContentShortBookInfoBatch = useAjax((params) => apiBookContentShortBookInfoBatch(params)); //批量上下架
  let ShortBookGetInfo = useAjax((params) => apiShortBookGetInfo(params)); //查询单个段落
  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();

  // 获取标签和分类
  useEffect(() => {
    getLabelAndClassList({ workDirection });
  }, [workDirection]);
  // 看小说
  const lookBook = (params: any) => {
    let { id, pageNum, pageSize } = params;
    return ShortBookGetInfo.run({ id, pageNum, pageSize }).then((res) => {
      setOpneBook({ ...res.data, ...params });
      return res.data;
    });
  };
  // 删除or批量删除
  const del = (ids: any) => {
    let api = Array.isArray(ids) ? BookContentShortBookInfoDels : BookContentShortBookInfoDel;
    api.run(ids).then((res) => {
      if (res.code === 200) {
        actionRef?.current?.reload();
        message.success('删除成功');
        setEditSelectedRow([]);
      }
    });
  };
  // 批量上下架
  const shelveAll = (ids: any[], shelve: 0 | 1) => {
    BookContentShortBookInfoBatch.run({ ids, shelve }).then((res) => {
      if (res.code === 200) {
        actionRef?.current?.reload();
        message.success('批量' + (shelve === 0 ? '上架成功' : '下架成功'));
      }
    });
  };
  // 提交表单
  const submit = async (values: any) => {
    let api = editValues?.id ? BookContentShortBookInfoEdit : BookContentShortBookInfoAdd;
    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' }}>
      <ProTable<any, any>
        // 实例
        actionRef={actionRef}
        // 标题
        headerTitle={'短篇小说列表'}
        // 唯一key
        rowKey={(r) => r.id}
        // 按钮
        toolBarRender={() => {
          return [
            <Button
              type="primary"
              onClick={() => {
                setOpen(true);
              }}
            >
              <PlusCircleOutlined />
              新增书籍
            </Button>,
          ];
        }}
        //多选
        rowSelection={{
          selectedRowKeys: editSelectedRow?.map((item: { id: any }) => item.id),
          onSelect: (record, selected) => {
            if (selected) {
              setEditSelectedRow([...editSelectedRow, record]);
            } else {
              setEditSelectedRow(
                editSelectedRow?.filter((item: { id: any }) => item.id !== record.id),
              );
            }
          },
          onSelectAll: (selected, rows, changeRows) => {
            if (selected) {
              setEditSelectedRow([...editSelectedRow, ...changeRows]);
            } else {
              let newArr = editSelectedRow?.filter((item: { id: any }) =>
                changeRows.every((i) => i?.id !== item?.id),
              );
              setEditSelectedRow(newArr);
            }
          },
        }}
        //多选展示栏
        tableAlertRender={({ selectedRowKeys, selectedRows }) => {
          return (
            <Space size={24}>
              <span style={{ width: 90, display: 'inline-block' }}>
                已选 {selectedRowKeys.length} 项
              </span>
              <span style={{ color: 'red' }}>
                {selectedRows
                  ?.map((item: { bookName: string }) => '《' + item.bookName + '》')
                  .join()}
              </span>
            </Space>
          );
        }}
        // 多选后的按钮操作
        tableAlertOptionRender={({ selectedRowKeys }) => {
          return (
            <Space>
              <Popconfirm
                title={null}
                icon={null}
                onConfirm={() => {
                  shelveAll(
                    editSelectedRow?.map((item) => item.id),
                    0,
                  );
                }}
                onCancel={() => {
                  shelveAll(
                    editSelectedRow?.map((item) => item.id),
                    1,
                  );
                }}
                okText="全部上架"
                cancelText="全部下架"
              >
                <Button type="primary" disabled={selectedRowKeys.length === 0}>
                  <ColumnHeightOutlined />
                  批量上下架
                </Button>
              </Popconfirm>
              <Popconfirm
                title={<div>确定要删除此批书籍?</div>}
                onConfirm={() => {
                  del(editSelectedRow?.map((item) => item.id));
                }}
              >
                <Button type="primary" danger disabled={selectedRowKeys.length === 0}>
                  <DeleteOutlined />
                  批量删除
                </Button>
              </Popconfirm>
            </Space>
          );
        }}
        //宽度自适应
        scroll={{ x: true }}
        // 加载
        loading={BookContentShortBookInfoList?.loading}
        // 搜索的配置
        search={{
          labelWidth: 90,
          searchGutter: [10, 15],
        }}
        //处理搜索数据
        beforeSearchSubmit={(params) => {
          let newParams = Object.entries(params).reduce((acc: any, [key, value]) => {
            // 过滤掉空值，包括空字符串和 null
            if (value !== '' && value != null) {
              acc[key] = value;
            }
            if (key === 'wordCount' && value) {
              let obj = wordCountRanges[value];
              acc['startWordCount'] = obj.start;
              acc['endWordCount'] = obj.end;
              delete acc[key];
            }
            return acc;
          }, {});
          return newParams;
        }}
        // 数据请求
        request={async (params) => {
          return await BookContentShortBookInfoList.run(params);
        }}
        // 表
        columns={columns({
          authList: state?.authList,
          labelList: state.labelList,
          categoryList: state.categoryList,
          enumList: state?.enumList,
          lookBook,
          closeForm,
          setWorkDirection,
          del,
          setEditValues,
        })}
      />
      {/* 新增编辑小说 */}
      <BetaSchemaForm<DataItem>
        layout="horizontal"
        title={!editValues?.id ? '新增书籍' : '编辑书籍'}
        formRef={formRef}
        open={open}
        onOpenChange={(b) => {
          !b && closeForm(b);
        }}
        layoutType={'ModalForm'}
        rowProps={{
          gutter: [16, 16],
        }}
        colProps={{
          span: 12,
        }}
        grid={true}
        onValuesChange={(changedValues, allValues) => {
          // 检查 workDirection 是否变化
          if ('workDirection' in changedValues) {
            setWorkDirection(changedValues['workDirection']);
            // 清空 categoryId 和 labelIds 的值
            formRef.current?.setFieldsValue({
              categoryId: undefined,
              labelIds: undefined,
            });
          }
        }}
        onFinish={submit}
        columns={formConfig({
          authList: state?.authList,
          enumList: state?.enumList,
          labelList: state.labelList,
          categoryList: state.categoryList,
        })}
        loading={BookContentShortBookInfoAdd?.loading || BookContentShortBookInfoEdit?.loading}
      />
      {/* 阅读小说 */}
      <Drawer
        open={!!openBook}
        placement="right"
        onClose={() => {
          setOpneBook(null);
        }}
        footer={null}
        width={'65%'}
        destroyOnClose={true}
        // getContainer={false}
        styles={{ body: { padding: 0 } }}
        closeIcon={false}
        title={<div style={{ fontSize: 20 }}>{openBook?.bookName ? openBook?.bookName : ''}</div>}
      >
        <ReadText data={openBook} next={lookBook} />
      </Drawer>
      {/* 段落管理 */}
      <Item data={editValues} onClose={setEditValues} />
    </PageContainer>
  );
};
export default Page;
