import { useEffect, useState } from 'react';
import SearchView from '~/components/search-box';
import { Button, message, Table, Image, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { industryListPagesType } from '~/api/interface/categoryManage';
import { InterListType } from '~/api/interface';
import { ColumnsType } from 'antd/es/table';
import { CategoryManageAPI } from '~/api';
import Video from '~/components/video';
import AddEditModalView from '~/pages/categoryManage/serviceCategoryList/comp/addEditModal';
import AddEditChildrenView from '~/pages/categoryManage/serviceCategoryList/comp/addEditChildren';
import { useNavigate } from 'react-router-dom';
import qs from 'query-string';

// 列表的类型
type TableType = InterListType<industryListPagesType>;

function ServiceCategoryList() {
  // 路由钩子
  const navigate = useNavigate();
  // 新增编辑弹窗是否显示
  const [addEditVisible, setAddEditVisible] = useState(false);
  // 新增编辑子分类弹窗是否显示
  const [addEditChildVisible, setAddEditChildVisible] = useState(false);
  // 编辑的数据
  const [recordData, setRecordData] = useState<TableType[0]>();
  // 编辑子分类的数据
  const [recordChildData, setRecordChildData] = useState<TableType[0]['inspectionDTOS'][0]>();
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await CategoryManageAPI.industryListPages({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list || []);
      // setPointData(res?.result?.list);
    } else {
      message.warning(res.message);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 排序
  // const handleSort = (type: string) => {
  //   console.log(type);
  // };
  // 删除数据
  const handleDelete = (record: TableType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '是否删除该分类？',
      onOk: async () => {
        const res = await CategoryManageAPI[
          record.typeName ? 'industryRemove' : 'inspectionRemove'
        ]({
          id: record.id,
        });
        if (res && res.code === '200') {
          message.success('删除成功');
          paginationChange(
            tableData.length === 1 ? pagination.current - 1 : pagination.current,
            pagination.pageSize,
          );
        }
      },
    });
  };
  // 跳转详情
  const handleNavigation = (record: TableType[0]) => {
    const search = {
      id: record.id,
    };
    navigate(`/categoryManage/mallCategoryList/detail?${qs.stringify(search)}`);
  };
  // 获取图片
  const getImgParse = (text: string) => {
    try {
      return JSON.parse(text)?.[0]?.fileUrl;
    } catch (e) {
      return text;
    }
  };
  // 表格列
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '分类名称',
      dataIndex: 'typeName',
      align: 'center',
      render: (text, record) => text || record.inspectionName,
    },
    {
      title: '图片',
      dataIndex: 'typeImg',
      align: 'center',
      render: (text, record) => (
        <>
          <Image src={text || record.inspectionImg} width={40} height={40} />
        </>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      align: 'center',
      render: (text, record) => text || record.inspectionDescription,
    },
    {
      title: '业务案例图片',
      dataIndex: 'caseImg',
      align: 'center',
      render: (text) => <>{text && <Image src={getImgParse(text)} width={40} height={40} />}</>,
    },
    {
      title: '业务案例视频',
      dataIndex: 'caseVideo',
      align: 'center',
      render: (text) => <>{text && <Video src={text} width={40} height={40} />}</>,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      width: 180,
      render: (_text, record) => (
        <>
          {!record.inspectionName && (
            <Button
              type='link'
              onClick={() => {
                setRecordData(record);
                setRecordChildData(undefined);
                setAddEditChildVisible(true);
              }}
            >
              新增子分类
            </Button>
          )}
          {record.inspectionName && (
            <Button
              type='link'
              onClick={() => {
                handleNavigation(record);
              }}
            >
              详情
            </Button>
          )}
          {!record.inspectionName && (
            <Button
              type='link'
              onClick={() => {
                setRecordData(record);
                setAddEditVisible(true);
              }}
            >
              编辑
            </Button>
          )}
          {record.inspectionName && (
            <Button
              type='link'
              onClick={() => {
                setRecordData(record);
                setRecordChildData(record as any);
                setAddEditChildVisible(true);
              }}
            >
              编辑
            </Button>
          )}
          <Button
            type='link'
            onClick={() => {
              handleDelete(record);
            }}
            danger
          >
            删除
          </Button>
        </>
      ),
    },
  ];
  // 组件挂载
  useEffect(() => {
    (async () => {
      await getTableList();
    })();
  }, []);
  return (
    <>
      <SearchView
        sufFixBtn={
          <>
            <Button
              type='primary'
              onClick={() => {
                setAddEditVisible(true);
              }}
              icon={<PlusOutlined />}
            >
              新增分类
            </Button>
            {/*<Button*/}
            {/*  icon={<ArrowUpOutlined />}*/}
            {/*  type='primary'*/}
            {/*  onClick={() => handleSort('up')}*/}
            {/*></Button>*/}
            {/*<Button*/}
            {/*  icon={<ArrowDownOutlined />}*/}
            {/*  type='primary'*/}
            {/*  onClick={() => handleSort('down')}*/}
            {/*></Button>*/}
          </>
        }
      />
      <Table
        size={'small'}
        columns={columns}
        rowKey={'id'}
        // scroll={{ x: 1000 }}
        // rowSelection={{ ...rowSelection, checkStrictly }}
        dataSource={tableData}
        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} 条数据`,
        }}
        expandable={{
          childrenColumnName: 'inspectionDTOS',
          fixed: true,
          // expandIcon: ({ expanded, onExpand, record }) =>
          //   record?.inspectionDTOS?.length ? (
          //     expanded ? (
          //       <CaretDownOutlined
          //         onClick={(e) => onExpand(record, e)}
          //         style={{ marginRight: '10px', marginLeft: '-20px', color: '#1668dc' }}
          //       />
          //     ) : (
          //       <CaretRightOutlined
          //         onClick={(e) => onExpand(record, e)}
          //         style={{ marginRight: '10px', color: '#1668dc' }}
          //       />
          //     )
          //   ) : (
          //     <span style={{ marginRight: '0px', marginLeft: '-20px' }}>&nbsp;</span>
          //   ),
        }}
      />
      <AddEditModalView
        title={recordData ? '编辑分类' : '新增分类'}
        open={addEditVisible}
        data={recordData}
        onCancel={() => {
          setAddEditVisible(false);
          setRecordData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
      />
      <AddEditChildrenView
        title={recordData ? '编辑子分类' : '新增子分类'}
        open={addEditChildVisible}
        data={recordChildData}
        id={Number(recordData?.id)}
        onCancel={() => {
          setAddEditChildVisible(false);
          setRecordData(undefined);
          setRecordChildData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
      />
    </>
  );
}

export default ServiceCategoryList;
