import React, { FC, useEffect, useState } from 'react';
import { useNavigate } 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';

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

const ServiceList: FC<any> = () => {
  const navigate = useNavigate();
  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' },
    { 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 [currentServiceData, setCurrentServiceData] = useState<serviceListType[0]>();
  // 表格多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  //筛选
  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;
    setQuery({ ...query, displayState: key === '1' ? undefined : key === '2' ? 0 : 1 });
    setActiveTabKey(key);
    getServiceList({ ...query, displayState: key === '1' ? undefined : key === '2' ? 0 : 1 });
  };
  //新增服务
  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) => {
    setLoading(true);
    MallManageAPI.getServiceList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      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;
    getServiceList(query);
  };
  // 表格多选事件
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  //筛选
  const searchSuccess = (data: any) => {
    pagination.pageNo = 1;
    setQuery(data);
    getServiceList(data);
  };
  //预览视频
  const previewVideo = (url: string) => {
    setPreviewShow(true);
    setPreviewUrl(url);
  };
  const previewCancel = () => {
    setPreviewShow(false);
  };
  useEffect(() => {
    getServiceList();
    getIndustryCategoryList();
    getApplicationCategoryList();
  }, []);

  return (
    <div className='service-list'>
      <SearchBox
        search={searchColumnsData}
        child={
          <Button
            type='primary'
            icon={<PlusOutlined />}
            onClick={() => addOrEditServiceModalShow()}
          >
            新增服务
          </Button>
        }
        searchData={searchSuccess}
      />
      <Card tabList={tabList} activeTabKey={activeTabKey} onTabChange={onTabChange}>
        <div className='header-operate' style={{ marginBottom: '10px' }}>
          {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;
