import SearchBox, { searchColumns as searchColumnsType } from '~/components/search-box';
import { Button, Modal, Table, Tag } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table/InternalTable';
import AddOrEditRentModeModal from '~/pages/rentManage/rentMode/components/addOrEditRentModeModal';
import { useEffect, useState } from 'react';
import { RentManageAPI } from '~/api';
import { InterDataType, InterReqListType, PaginationProps } from '~/api/interface';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { getTypeListType, rentModeListType } from '~/api/interface/rentManageType';

//类型类别返回类型
type rentTypeListType = InterDataType<getTypeListType>['list'];
//型号返回类型
type modeListType = InterDataType<rentModeListType>['list'];
//型号列表参数类型
type modeListParametersType = InterReqListType<rentModeListType>;

const RentMode = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  const [rentTypeList, setRentTypeList] = useState<rentTypeListType>([]);
  const tableColumns: ColumnsType<modeListType[0]> = [
    {
      title: '型号名称',
      align: 'center',
      dataIndex: 'modeName',
    },
    {
      title: '所属类型',
      align: 'center',
      dataIndex: 'productTypeId',
      render: (text: number) => rentTypeList.find((v) => v.id === text)?.name || '',
    },
    {
      title: '标签',
      align: 'center',
      dataIndex: 'tag',
      render: (text: string) => text?.split(',').map((v, index) => <Tag key={index}>{v}</Tag>),
    },
    {
      title: '操作',
      align: 'center',
      width: '10%',
      render: (_: any, record) => (
        <>
          <Button type='link' onClick={() => addOrEditRentModelClick(record)}>
            编辑
          </Button>
          <Button type='link' onClick={() => deleteRentModelClick(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  const searchColumns: searchColumnsType[] = [
    {
      name: 'productTypeId',
      label: '所属类型',
      placeholder: '请选择所属类型',
      type: 'select',
      options: rentTypeList.map((v) => ({ id: v.id, name: v.name })),
    },
  ];
  const [brandInfoId, setBrandInfoId] = useState<number>(-1);
  const [addOrEditRentModelModalShow, setAddOrEditRentModelModalShow] = useState<boolean>(false);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [tableData, setTableData] = useState<modeListType>([]);
  const [query, setQuery] = useState<modeListParametersType>();
  const [currentRentMode, setCurrentRentMode] = useState<modeListType[0]>();

  //新增，编辑型号弹窗
  const addOrEditRentModelClick = (record?: modeListType[0]) => {
    setCurrentRentMode(record ? { ...record } : undefined);
    setAddOrEditRentModelModalShow(true);
  };
  const addOrEditRentModelModalCancel = () => {
    setAddOrEditRentModelModalShow(false);
  };
  const addOrEditRentModelModalOk = () => {
    setAddOrEditRentModelModalShow(false);
    getModeList(brandInfoId, query);
  };
  //删除型号
  const deleteRentModelClick = (record: modeListType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除该型号？',
      onOk: () => {
        RentManageAPI.deleteMode({ id: record.id }).then(({ code }) => {
          if (code === '200') {
            if (tableData.length === 1 && pagination.pageNo !== 1) {
              pagination.pageNo -= 1;
            }
            getModeList(brandInfoId, query);
          }
        });
      },
    });
  };
  //型号列表
  const getModeList = (brandInfoId: number, query?: modeListParametersType) => {
    RentManageAPI.getRentModeList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      brandInfoId,
      ...query,
    }).then(({ result }) => {
      pagination.totalCount = result.totalCount;
      setTableData(result.list || []);
      setPagination({ ...pagination });
    });
  };
  //获取类型列表
  const getRentTypeList = () => {
    RentManageAPI.getTypeList({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      setRentTypeList(result.list || []);
      searchColumns[0].options = (result.list || []).map((v) => ({ id: v.id, name: v.name }));
    });
  };
  //返回
  const backRoute = () => {
    navigate(-1);
  };
  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getModeList(brandInfoId, query);
  };
  //筛选
  const searchSuccess = (value: modeListParametersType) => {
    pagination.pageSize = 10;
    pagination.pageNo = 1;
    setQuery(value);
    getModeList(brandInfoId, value);
  };

  useEffect(() => {
    getRentTypeList();
    setBrandInfoId(Number(searchParams.get('brandInfoId')));
    getModeList(Number(searchParams.get('brandInfoId')));
  }, []);
  return (
    <div className='rent-model'>
      <SearchBox
        search={searchColumns}
        child={
          <>
            <span style={{ marginRight: '10px', color: '#1677ff' }}>
              当前品牌：{searchParams.get('brandName')}
            </span>
            <Button
              type='primary'
              icon={<PlusOutlined />}
              onClick={() => addOrEditRentModelClick()}
            >
              新增型号
            </Button>
          </>
        }
        otherChild={
          <Button type='primary' onClick={backRoute}>
            返回
          </Button>
        }
        searchData={searchSuccess}
      />
      <Table
        bordered
        columns={tableColumns}
        dataSource={tableData}
        rowKey='id'
        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} 条数据`,
        }}
      />
      <AddOrEditRentModeModal
        open={addOrEditRentModelModalShow}
        onCancel={addOrEditRentModelModalCancel}
        onOk={addOrEditRentModelModalOk}
        brandInfoId={brandInfoId}
        rentTypeList={rentTypeList}
        currentRentMode={currentRentMode}
      />
    </div>
  );
};
export default RentMode;
