import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Select, Table, Image, Modal, message } from 'antd';
import { listBannerInfoPage, updateModuleInfo } from '~/api/interface/commonType';
import { InterListType, InterReqListType, InterReqType } from '~/api/interface';
import { useLocation, useNavigate } from 'react-router-dom';
import qs from 'query-string';
import { ArrowDownOutlined, ArrowUpOutlined, PlusOutlined } from '@ant-design/icons';
import { CommonAPI } from '~/api';
import { ColumnsType } from 'antd/es/table';
import AddEditModal from '../comp/addEditModal';

// 表格的类型
type TableType = InterListType<listBannerInfoPage>;
// 请求的参数
type ReqType = InterReqListType<listBannerInfoPage>;
// 搜索表单的数据
let query: ReqType = {};
// 所属产品
const moduleType = [
  { label: '云享飞Pro', value: '0' },
  { label: '云享飞Web', value: '1' },
  // { label: '云飞手', value: '1' },
  // { label: '云仓', value: '2' },
  // { label: '无人机城', value: '3' },
];
// 详情类型
const bannerType = [
  { label: '无', value: 0 },
  { label: '海报', value: 1 },
  { label: '路由', value: 2 },
  { label: '路由(需要授权)', value: 9 },
  { label: '路由(跳转Tab栏)', value: 10 },
  { label: '小程序', value: 3 },
  // { label: '弹窗', value: 4 },
  { label: '纯文本', value: 5 },
  // { label: '服务SKU', value: 6 },
  // { label: '红包', value: 7 },
  { label: '链接', value: 8 },
  { label: '富文本', value: 11 },
  { label: '分享', value: 12 },
];
// 全部数据
// let tableDataAll: TableType = [];

const MaterielManageDetail = () => {
  const { confirm } = Modal;
  // 表单钩子
  const [form] = Form.useForm<InterReqType<updateModuleInfo>>();
  // 路由钩子
  const location = useLocation();
  const navigate = useNavigate();
  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };
  // 当前选择的项目
  const [selectedRows, setSelectedRows] = useState<TableType>([]);
  // 排序按钮是否能操作
  const [sortBtnDisabled, setSortBtnDisabled] = useState<boolean>(false);
  // 新增修改弹窗是否开启
  const [addModalVisible, setAddModalVisible] = useState(false);
  // 需要编辑的数据
  const [editData, setEditData] = useState<TableType[0]>();
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 全部表格数据
  const [tableDataAll, setTableDataAll] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 5,
    current: 1,
    totalPage: 0,
  });
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await CommonAPI.listBannerInfoPage({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
      moduleId: Number(qs.parse(location.search).id),
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list || []);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 删除数据
  const handleDelete = (record: TableType[0]) => {
    confirm({
      title: '提示',
      content: '是否删除该模块？',
      onOk: async () => {
        const res = await CommonAPI.removeBannerInfo({ id: record.id });
        if (res && res.code === '200') {
          message.success('删除成功');
          paginationChange(
            tableData.length === 1 ? pagination.current - 1 : pagination.current,
            pagination.pageSize,
          );
        }
      },
    });
  };
  // 获取全部数据
  const getAllData = async () => {
    const res = await CommonAPI.listBannerInfoPage({
      pageNo: 1,
      pageSize: 9999,
      moduleId: Number(qs.parse(location.search).id),
    });
    if (res && res.code === '200') {
      const { list } = res.result; // 解构
      setTableDataAll(list || []);
      // tableDataAll = list || [];
    }
  };
  // 切换排序
  const handleSort = async (from: 'up' | 'down') => {
    if (selectedRows.length === 0) {
      message.warning('请选择需要排序的数据').then();
      return;
    }
    // 当前选项
    const item = selectedRows.at(-1);
    // 当前索引
    const index = tableDataAll.findIndex((i) => i.id === item?.id);
    // 当前表格中的索引
    const tableIndex = tableData.findIndex((i) => i.id === item?.id);
    // 第一条数据不能上移
    if (index === 0 && from === 'up') {
      message.warning('已是第一条数据').then();
      return;
    }
    // 最后一条数据不能下移
    if (index === tableDataAll.length - 1 && from === 'down') {
      message.warning('已是最后一条数据').then();
      return;
    }
    setSortBtnDisabled(true);
    // 转换位置
    const res = await CommonAPI.exchangeBannerInfo(
      from === 'up'
        ? [tableDataAll[index - 1], tableDataAll[index]]
        : [tableDataAll[index + 1], tableDataAll[index]],
    );
    if (res && res.code === '200') {
      message.success('操作成功').then();
      // setSelectedRows(from === 'up' ? [tableDataAll[index - 1]] : [tableDataAll[index + 1]]);
      // 如果是当前页的第一条数据
      if (tableIndex === 0 && from === 'up') {
        paginationChange(pagination.current - 1, pagination.pageSize);
        await getAllData();
        await setSortBtnDisabled(false);
        return;
      }
      // 如果是当前页的最后一条数据
      if (tableIndex === tableData.length - 1 && from === 'down') {
        paginationChange(pagination.current + 1, pagination.pageSize);
        await getAllData();
        await setSortBtnDisabled(false);
        return;
      }
      paginationChange(pagination.current, pagination.pageSize);
      await getAllData();
      await setSortBtnDisabled(false);
    }
  };
  // 修改提交数据
  const handleEdit = () => {
    form
      .validateFields()
      .then(async (values) => {
        const res = await CommonAPI.updateModuleInfo({
          ...values,
          id: Number(qs.parse(location.search).id),
        });
        if (res && res.code === '200') {
          message.success('修改成功');
          getTableList().then();
          getAllData().then();
        } else {
          window.location.reload();
        }
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // componentDidMount
  useEffect(() => {
    query = {};
    form.setFieldsValue(qs.parse(location.search));
    getTableList().then();
    getAllData().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '序号',
      dataIndex: 'accountNo',
      align: 'center',
      width: '50px',
      render: (_text, _record, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    // {
    //   title: 'sort',
    //   dataIndex: 'sort',
    //   align: 'center',
    //   width: '100px',
    //   ellipsis: true,
    // },
    {
      title: '名称',
      dataIndex: 'bannerName',
      align: 'center',
      width: '100px',
      ellipsis: true,
    },
    {
      title: '封面图',
      dataIndex: 'bannerImg',
      align: 'center',
      width: '100px',
      render: (text) => (
        <>
          <Image src={text} alt={'封面图'} style={{ width: '32px', height: '32px' }} />
        </>
      ),
    },
    {
      title: '详情类型',
      dataIndex: 'bannerType',
      align: 'center',
      width: '100px',
      render: (text) => bannerType.find((i) => i.value === text)?.label || text,
    },
    {
      title: '点击详情',
      dataIndex: 'bannerPoster',
      align: 'center',
      width: '100px',
      render: (text, record) => {
        if ([1].includes(record.bannerType)) {
          return <Image src={text} alt={'点击详情'} style={{ width: '32px', height: '32px' }} />;
        } else {
          return <>{record?.bannerUrl}</>;
        }
      },
    },
    {
      title: '状态',
      dataIndex: 'using',
      align: 'center',
      width: '100px',
      render: (text) => (text === 1 ? '上架' : '下架'),
    },
    {
      title: '有效时间',
      dataIndex: 'createTime',
      align: 'center',
      width: '120px',
      ellipsis: true,
      render: (_text, record) =>
        record.startTime && record.endTime ? (
          <>
            <div>{record?.startTime}</div>
            <div>至</div>
            <div>{record?.endTime}</div>
          </>
        ) : (
          '永久'
        ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      width: '150px',
      fixed: 'right',
      render: (_text, record) => (
        <>
          <Button
            type={'link'}
            onClick={() => {
              setEditData(JSON.parse(JSON.stringify(record)));
              setAddModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <div
        style={{
          width: '100%',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <div>基本信息</div>
        <div
          style={{
            marginTop: '10px',
            width: '120px',
            display: 'flex',
            justifyContent: 'space-around',
          }}
        >
          <Button type={'primary'} onClick={handleEdit}>
            修改
          </Button>
          <Button type={'primary'} onClick={handleBack}>
            返回
          </Button>
        </div>
      </div>
      <div style={{ width: '350px' }}>
        <Form name='addForm' form={form} labelAlign='right'>
          <Form.Item
            label='模块名称'
            name='moduleName'
            rules={[{ required: true, message: '请输入模块名称' }]}
          >
            <Input placeholder={'请输入模块名称'} maxLength={20} allowClear />
          </Form.Item>
          <Form.Item
            label='所属产品'
            name='moduleType'
            rules={[{ required: true, message: '所属产品' }]}
          >
            <Select placeholder={'所属产品'} options={moduleType} allowClear />
          </Form.Item>
          <Form.Item
            label='模块代码'
            name='moduleCode'
            rules={[{ required: true, message: '请输入模块代码' }]}
          >
            <Input placeholder={'请输入模块代码'} maxLength={20} allowClear />
          </Form.Item>
        </Form>
      </div>
      <div>模块内容</div>
      <div
        style={{
          marginTop: '20px',
          width: '150px',
          display: 'flex',
          justifyContent: 'space-around',
          marginBottom: '20px',
        }}
      >
        <Button
          type={'primary'}
          icon={<ArrowUpOutlined />}
          onClick={() => handleSort('up')}
          disabled={sortBtnDisabled}
        ></Button>
        <Button
          type={'primary'}
          icon={<ArrowDownOutlined />}
          onClick={() => handleSort('down')}
          disabled={sortBtnDisabled}
        ></Button>
        <Button
          type={'primary'}
          icon={<PlusOutlined />}
          onClick={() => {
            setAddModalVisible(true);
          }}
        >
          新增
        </Button>
      </div>
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        // scroll={{ x: 1500 }}
        bordered
        pagination={{
          total: pagination.total,
          pageSize: pagination.pageSize,
          current: pagination.current,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
        rowSelection={{
          type: 'radio',
          // selectedRowKeys: selectedRows.map((i) => i.id),
          onChange: (_selectedRowKeys: React.Key[], selectedRows: TableType) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <AddEditModal
        open={addModalVisible}
        title={editData?.id ? '编辑' : '新增'}
        data={editData}
        closed={() => {
          setAddModalVisible(false);
          setEditData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
          getAllData().then();
        }}
        moduleId={Number(qs.parse(location.search).id)}
      />
    </>
  );
};

export default MaterielManageDetail;
