import React, { FC, useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { searchColumns } from '~/components/search-box';
import SearchBox from '~/components/search-box';
import AddOrEditServiceModal from './components/addOrEditServiceModal';
import PreviewImageVideo from '~/components/previewImageVideo';
import { Button, Card, Image, message, Modal, Table } from 'antd';
import {
  PlusOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import { CategoryManageAPI, MallManageAPI } from '~/api';
import { InterDataType, InterReqType, PaginationProps } from '~/api/interface';
import { categoryListType } from '~/api/interface/categoryManage';
import { serviceType } from '~/api/interface/mallManageType';
import qs from 'query-string';

//分类返回类型
type categoryType = InterDataType<categoryListType>['list'];
//服务返回类型
type serviceListType = InterDataType<serviceType>['list'];
//服务列表请求类型
type serviceParametersType = InterReqType<serviceType>;

const ServiceList: FC<any> = () => {
  const searchRef = useRef<any>();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const tabList = [
    {
      key: '1',
      tab: '全部',
    },
    {
      key: '2',
      tab: '上架中',
    },
    {
      key: '3',
      tab: '仓库中',
    },
  ];
  const [activeTabKey, setActiveTabKey] = useState<string>('1');
  const [searchColumnsData, setSearchColumnsData] = useState<searchColumns[]>([
    {
      type: 'input',
      placeholder: '请输入服务名称',
      label: '服务名称',
      name: 'serviceName',
    },
    {
      type: 'select',
      placeholder: '请选择应用类型',
      label: '应用类型',
      name: 'applicationId',
      options: [],
    },
    {
      type: 'select',
      placeholder: '请选择对应行业',
      label: '对应行业',
      name: 'industryId',
      options: [],
    },
  ]);
  const tableColumns: ColumnsType<serviceListType[0]> = [
    {
      title: '序号',
      align: 'center',
      render: (_text: any, _record: any, index: number) =>
        (pagination.pageNo - 1) * pagination.pageSize + index + 1,
    },
    { title: '服务名称', align: 'center', dataIndex: 'serviceName', width: '20%' },
    { title: '应用', align: 'center', dataIndex: 'applicationName' },
    { title: '对应行业', align: 'center', dataIndex: 'industryName' },
    {
      title: '封面图',
      align: 'center',
      dataIndex: 'coverPlan',
      render: (text: string) => <Image src={text} width={50} height={50} />,
    },
    {
      title: '分享卡片',
      align: 'center',
      dataIndex: 'shareCard',
      render: (text: string) => (text ? <Image src={text} width={50} height={50} /> : '暂无'),
    },
    {
      title: '视频',
      align: 'center',
      dataIndex: 'video',
      render: (text: string) =>
        text ? (
          <Button type='link' onClick={() => previewVideo(text)}>
            查看
          </Button>
        ) : (
          '暂无'
        ),
    },
    {
      title: '服务介绍',
      align: 'center',
      dataIndex: 'serviceIntroduction',
      render: (_text: string, record) => (
        <Button type='link' onClick={() => toServiceIntroduce(record)}>
          编辑
        </Button>
      ),
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'displayState',
      render: (text: number) => (text === 0 ? '上架' : '下架'),
    },
    {
      title: '操作',
      align: 'center',
      render: (_text: any, record) => (
        <>
          <Button type='link' onClick={() => addOrEditServiceModalShow(record)}>
            编辑
          </Button>
          <Button type='link' onClick={() => toServiceDetail(record)}>
            详情
          </Button>
        </>
      ),
    },
  ];
  const [loading, setLoading] = useState<boolean>(false);
  const [tableData, setTableData] = useState<serviceListType>([]); //表格数据
  const [allServiceData, setAllServiceData] = useState<serviceListType>([]);
  const [currentServiceData, setCurrentServiceData] = useState<serviceListType[0]>();
  // 表格多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState<
    PaginationProps & { totalCount: number; totalPage: number }
  >({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
    totalPage: 1,
  });
  //筛选
  const [query, setQuery] = useState<serviceParametersType>({
    displayState: undefined,
  });
  //行业分类列表
  const [industryCategoryList, setIndustryCategoryList] = useState<categoryType>([]);
  //应用分类列表
  const [applicationCategoryList, setApplicationCategoryList] = useState<categoryType>([]);
  //新增、编辑服务弹窗
  const [addOrEditServiceModalOpen, setAddOrEditServiceModalOpen] = useState<boolean>(false);
  const [addOrEditServiceModalTitle, setAddOrEditServiceModalTitle] = useState<string>('新增服务');
  //预览视频、图片
  const [previewShow, setPreviewShow] = useState<boolean>(false);
  const [previewUrl, setPreviewUrl] = useState<string>('');

  const onTabChange = (key: string) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setQuery({ ...query, displayState: key === '1' ? undefined : key === '2' ? 0 : 1 });
    setSearchParams(
      qs.stringify({ ...query, displayState: key === '1' ? 'all' : key === '2' ? 0 : 1 }),
    );
    setActiveTabKey(key);
    getServiceList({ ...query, displayState: key === '1' ? undefined : key === '2' ? 0 : 1 });
    getServiceList(
      {
        ...query,
        displayState: key === '1' ? undefined : key === '2' ? 0 : 1,
        pageNo: 1,
        pageSize: 9999,
      },
      true,
    );
  };
  //新增服务
  const addOrEditServiceModalShow = (record?: serviceListType[0]) => {
    setAddOrEditServiceModalTitle(record ? '编辑服务' : '新增服务');
    setAddOrEditServiceModalOpen(true);
    setCurrentServiceData(record && { ...record });
  };

  const addOrEditServiceModalCancel = () => {
    setAddOrEditServiceModalOpen(false);
  };
  const addOrEditServiceModalOk = () => {
    setAddOrEditServiceModalOpen(false);
    getServiceList(query);
  };
  //服务-列表
  const getServiceList = (query?: serviceParametersType, isAll?: boolean) => {
    setLoading(true);
    MallManageAPI.getServiceList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      if (isAll) {
        setAllServiceData(result.list || []);
      } else {
        setTableData(result.list || []);
        pagination.totalCount = result.totalCount;
        pagination.totalPage = result.totalPage;
        setPagination(pagination);
      }
    });
  };
  //行业分类列表
  const getIndustryCategoryList = () => {
    CategoryManageAPI.getCategoryList({ directoryId: 2, pageSize: 99999, pageNo: 1 }).then(
      ({ result }) => {
        setIndustryCategoryList(result.list || []);
        searchColumnsData[2].options =
          result.list?.map((v) => ({
            id: v.id,
            name: v.classifyName,
          })) || [];
        setSearchColumnsData(searchColumnsData);
      },
    );
  };
  //应用分类列表
  const getApplicationCategoryList = () => {
    CategoryManageAPI.getCategoryList({ directoryId: 3, pageSize: 99999, pageNo: 1 }).then(
      ({ result }) => {
        setApplicationCategoryList(result.list || []);
        searchColumnsData[1].options =
          result.list?.map((v) => ({
            id: v.id,
            name: v.classifyName,
          })) || [];
        setSearchColumnsData(searchColumnsData);
      },
    );
  };
  //服务详情
  const toServiceDetail = (record: serviceListType[0]) => {
    navigate({ pathname: '/mallManage/serviceDetail', search: `id=${record.id}` });
  };
  //服务介绍
  const toServiceIntroduce = (record: serviceListType[0]) => {
    navigate({ pathname: '/mallManage/serviceIntroduce', search: `id=${record.id}` });
  };
  //上下架
  const groundingOrOffService = (status: number) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择服务');
      return;
    }
    MallManageAPI.batchUpAndDownWorkService({
      displayState: status,
      ids: selectedRowKeys as number[],
    }).then(({ code }) => {
      if (code === '200') {
        message.success(status ? '下架成功' : '上架成功');
        getServiceList(query);
        setSelectedRowKeys([]);
      }
    });
  };
  //服务删除
  const deleteService = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择服务');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '删除后数据将会丢失，确定删除吗？',
      onOk() {
        MallManageAPI.deleteService(selectedRowKeys as number[]).then(({ code }) => {
          if (code === '200') {
            if (pagination.pageNo !== 1 && tableData.length === 1) {
              pagination.pageNo -= 1;
            }
            message.success('删除成功');
            getServiceList(query);
          }
        });
      },
    });
  };
  //分页事件
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    setSearchParams(
      qs.stringify({
        ...query,
        pageNo,
        pageSize,
        displayState: query.displayState === undefined ? 'all' : query.displayState,
      }),
    );
    getServiceList(query);
    getServiceList({ ...query, pageNo: 1, pageSize: 9999 }, true);
  };
  // 表格多选事件
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  //筛选
  const searchSuccess = (data: any) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setSearchParams(
      qs.stringify({
        ...data,
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
        displayState: query.displayState === undefined ? 'all' : query.displayState,
      }),
    );
    setQuery(data);
    getServiceList(data);
    getServiceList({ ...data, pageNo: 1, pageSize: 9999 }, true);
  };
  //预览视频
  const previewVideo = (url: string) => {
    setPreviewShow(true);
    setPreviewUrl(url);
  };
  const previewCancel = () => {
    setPreviewShow(false);
  };
  //上移
  const upServiceClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择服务');
    } else if (selectedRowKeys.length > 1) {
      message.warning('最多选择一个服务');
    } else {
      const index = tableData.findIndex((v) => v.id === selectedRowKeys[0]);
      const allIndex = allServiceData.findIndex((v) => v.id === selectedRowKeys[0]);
      if (index === 0 && pagination.pageNo === 1) {
        message.warning('位置已到最前列，无法上移');
      } else {
        const exReqData =
          index === 0
            ? allServiceData
                .filter((_v, index) => index === allIndex - 1 || index === allIndex)
                .map((v) => ({ id: v.id, sort: v.sort }))
            : tableData
                .filter((_v, i) => index - 1 === i || index === i)
                .map((v) => ({ id: v.id, sort: v.sort }));
        MallManageAPI.exChangeService(exReqData).then(({ code }) => {
          if (code === '200') {
            message.success('上移成功');
            if (index === 0 && pagination.pageNo !== 1) {
              pagination.pageNo -= 1;
              setSearchParams(
                qs.stringify({
                  ...query,
                  pageNo: pagination.pageNo,
                  pageSize: pagination.pageSize,
                  displayState: query.displayState === undefined ? 'all' : query.displayState,
                }),
              );
            }
            getServiceList(query);
            getServiceList({ ...query, pageNo: 1, pageSize: 9999 }, true);
          }
        });
      }
    }
  };
  //下移
  const downServiceClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择服务');
    } else if (selectedRowKeys.length > 1) {
      message.warning('最多选择一个服务');
    } else {
      const index = tableData.findIndex((v) => v.id === selectedRowKeys[0]);
      const allIndex = allServiceData.findIndex((v) => v.id === selectedRowKeys[0]);
      if (index === tableData.length - 1 && pagination.pageNo === pagination.totalPage) {
        message.warning('位置已到最后，无法下移');
      } else {
        const exReqData =
          index === tableData.length - 1
            ? allServiceData
                .filter((_v, index) => index === allIndex + 1 || index === allIndex)
                .map((v) => ({ id: v.id, sort: v.sort }))
            : tableData
                .filter((_v, i) => index + 1 === i || index === i)
                .map((v) => ({ id: v.id, sort: v.sort }));
        MallManageAPI.exChangeService(exReqData).then(({ code }) => {
          if (code === '200') {
            message.success('下移成功');
            if (index === tableData.length - 1 && pagination.pageNo !== pagination.totalPage) {
              pagination.pageNo += 1;
              setSearchParams(
                qs.stringify({
                  ...query,
                  pageNo: pagination.pageNo,
                  pageSize: pagination.pageSize,
                  displayState: query.displayState === undefined ? 'all' : query.displayState,
                }),
              );
            }
            getServiceList(query);
            getServiceList({ ...query, pageNo: 1, pageSize: 9999 }, true);
          }
        });
      }
    }
  };
  useEffect(() => {
    pagination.pageNo = Number(searchParams.get('pageNo') || 1);
    pagination.pageSize = Number(searchParams.get('pageSize') || 10);
    searchRef.current.getForm().setFieldsValue({
      serviceName: searchParams.get('serviceName') || undefined,
      applicationId: searchParams.get('applicationId')
        ? Number(searchParams.get('applicationId'))
        : undefined,
      industryId: searchParams.get('industryId')
        ? Number(searchParams.get('industryId'))
        : undefined,
    });
    const queryObj = {
      serviceName: searchParams.get('serviceName') || undefined,
      applicationId: searchParams.get('applicationId')
        ? Number(searchParams.get('applicationId'))
        : undefined,
      industryId: searchParams.get('industryId')
        ? Number(searchParams.get('industryId'))
        : undefined,
      displayState:
        searchParams.get('displayState') === 'all' || searchParams.get('displayState') === null
          ? undefined
          : Number(searchParams.get('displayState')),
    };
    setQuery(queryObj);
    setActiveTabKey(
      searchParams.get('displayState') === 'all' || searchParams.get('displayState') === null
        ? '1'
        : Number(searchParams.get('displayState')) === 0
        ? '2'
        : '3',
    );
    getServiceList(queryObj);
    getServiceList({ ...queryObj, pageNo: 1, pageSize: 9999 }, true);
    getIndustryCategoryList();
    getApplicationCategoryList();
  }, []);

  return (
    <div className='service-list'>
      <SearchBox
        search={searchColumnsData}
        child={
          <Button
            type='primary'
            icon={<PlusOutlined />}
            onClick={() => addOrEditServiceModalShow()}
          >
            新增服务
          </Button>
        }
        searchData={searchSuccess}
        baseRef={searchRef}
      />
      <Card tabList={tabList} activeTabKey={activeTabKey} onTabChange={onTabChange}>
        <div className='header-operate' style={{ marginBottom: '10px' }}>
          <Button
            type='primary'
            style={{ marginRight: '10px' }}
            icon={<ArrowUpOutlined />}
            onClick={upServiceClick}
          >
            上移
          </Button>
          <Button
            type='primary'
            style={{ marginRight: '10px' }}
            icon={<ArrowDownOutlined />}
            onClick={downServiceClick}
          >
            下移
          </Button>
          {activeTabKey !== '2' ? (
            <Button
              type='primary'
              style={{ marginRight: '10px' }}
              icon={<ArrowUpOutlined />}
              onClick={() => groundingOrOffService(0)}
            >
              上架
            </Button>
          ) : (
            ''
          )}
          {activeTabKey !== '3' ? (
            <Button
              type='primary'
              style={{ marginRight: '10px' }}
              icon={<ArrowDownOutlined />}
              onClick={() => groundingOrOffService(1)}
            >
              下架
            </Button>
          ) : (
            ''
          )}

          <Button danger icon={<DeleteOutlined />} onClick={deleteService}>
            删除
          </Button>
        </div>
        <Table
          columns={tableColumns}
          loading={loading}
          bordered
          rowKey='id'
          dataSource={tableData}
          pagination={{
            total: pagination.totalCount,
            pageSize: pagination.pageSize,
            current: pagination.pageNo,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
            showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
          }}
          rowSelection={{
            selectedRowKeys,
            onChange: onSelectChange,
          }}
        />
      </Card>
      {/*新增/编辑服务弹窗*/}
      <AddOrEditServiceModal
        open={addOrEditServiceModalOpen}
        title={addOrEditServiceModalTitle}
        handleCancel={addOrEditServiceModalCancel}
        industryCategoryList={industryCategoryList}
        applicationCategoryList={applicationCategoryList}
        handleOk={addOrEditServiceModalOk}
        currentServiceData={currentServiceData}
      />
      {/* 预览*/}
      <PreviewImageVideo
        open={previewShow}
        onCancel={previewCancel}
        type='video'
        url={previewUrl}
      />
    </div>
  );
};
export default ServiceList;
