import SearchBox, { searchColumns } from '~/components/search-box';
import { Button, message, Modal, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import { PilotTrainAPI } from '~/api';
import { useEffect, useState } from 'react';
import { InterDataType, InterReqType, PaginationProps } from '~/api/interface';
import {
  licenceGradeListType,
  licenceModelsListType,
  licenceTypeListType,
  listOrgPageType,
} from '~/api/interface/pilotTrainType';
import { filterObjAttr } from '~/utils';
import { useSelector } from 'react-redux';

//机构列表返回类型
type institutionListType = InterDataType<listOrgPageType>['list'];
//机型下拉返回类型
type modelsListType = InterDataType<licenceModelsListType>;
//等级下拉返回类型
type gradeListType = InterDataType<licenceGradeListType>;
//执照类型返回类型
type typeListType = InterDataType<licenceTypeListType>;
//机构列表请求参数类型
type listOrgPageParametersType = InterReqType<listOrgPageType>;

const InstitutionsList = () => {
  const navigate = useNavigate();
  const { userInfo } = useSelector((state: any) => state.UserInfo);
  //机型下拉列表
  const [modelsList, setModelsList] = useState<modelsListType>([]);
  //等级下拉列表
  const [gradeList, setGradeList] = useState<gradeListType>([]);
  //执照类型列表
  const [typeList, setTypeList] = useState<typeListType>([]);
  const search: searchColumns[] = [
    { label: '机构名称', name: 'name', placeholder: '请输入机构名称', type: 'input' },
    {
      label: '培训等级',
      name: 'gradeId',
      placeholder: '请选择培训等级',
      type: 'select',
      options: gradeList,
    },
    {
      label: '培训机型',
      name: 'modelsId',
      placeholder: '请选择培训机型',
      type: 'select',
      options: modelsList,
    },
    {
      label: '培训类型',
      name: 'typeId',
      placeholder: '请选择培训类型',
      type: 'select',
      options: typeList,
    },
    {
      label: '选择日期',
      name: 'time',
      placeholder: '请选择日期',
      type: 'rangePicker',
      options: [],
    },
  ];
  const tableColumns: ColumnsType<institutionListType[0]> = [
    {
      title: '序号',
      align: 'center',
      render: (_text: string, _record, index: number) =>
        (pagination.pageNo - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '机构名称',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '培训类型',
      align: 'center',
      render: (_text: string, record: any) =>
        record.programsDOList
          ? Object.getOwnPropertyNames(record.programsDOList[0])
              .filter(
                (key: string) =>
                  ['gradeName', 'modelsName', 'typeName'].includes(key) &&
                  record.programsDOList[0][key] !== undefined &&
                  record.programsDOList[0][key] !== '' &&
                  record.programsDOList[0][key] !== null,
              )
              .map((key: string) => record.programsDOList[0][key])
              .join('/')
          : '',
      width: '20%',
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      render: (_text: string, record) => (
        <>
          <Button type='link' onClick={() => editInstitutionsClick(record)}>
            编辑
          </Button>
          <Button
            type='link'
            danger
            onClick={() => deleteInstitutionsClick(record)}
            disabled={!userInfo.roleInfo.superAdmin}
          >
            删除
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<institutionListType>([]);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [query, setQuery] = useState<listOrgPageParametersType>();

  // const toAddInstitutions = () => {
  //   navigate('/pilotTraining/institutionsList/add');
  // };
  //机构列表
  const getListOrgPage = (query?: listOrgPageParametersType) => {
    PilotTrainAPI.getListOrgPage({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
    });
  };
  //分页-监听
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getListOrgPage(query);
  };
  //机构删除
  const deleteInstitutionsClick = (record: institutionListType[0]) => {
    Modal.confirm({
      title: '删除机构',
      content: '确认删除该机构吗？',
      onOk: () => {
        PilotTrainAPI.removeOrg({ id: record.id }).then(({ code }) => {
          if (code === '200') {
            message.success('删除成功').then();
            if (pagination.pageNo !== 1 && tableData.length === 1) {
              pagination.pageNo -= 1;
            }
            getListOrgPage();
          }
        });
      },
    });
  };
  //机构编辑
  const editInstitutionsClick = (record: institutionListType[0]) => {
    navigate({ pathname: '/pilotTraining/institutionsList/edit', search: `id=${record.id}` });
  };
  //培训机型下拉
  const getLicenceModelsList = () => {
    PilotTrainAPI.getLicenceModelsList().then(({ result }) => {
      setModelsList(result || []);
    });
  };
  //培训等级下拉
  const getLicenceGradeList = () => {
    PilotTrainAPI.getLicenceGradeList().then(({ result }) => {
      setGradeList(result || []);
    });
  };
  //培训类型下拉
  const getLicenceTypeList = () => {
    PilotTrainAPI.getLicenceTypeList().then(({ result }) => {
      setTypeList(result || []);
    });
  };
  //筛选
  const searchSuccess = (value: any) => {
    const req = {
      ...filterObjAttr(value, ['time']),
      startTime: value.startTime ? value.startTime.split(' ')[0] : undefined,
      endTime: value.endTime ? value.endTime.split(' ')[0] : undefined,
    };
    setQuery(req);
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    getListOrgPage(req);
  };

  useEffect(() => {
    getListOrgPage();
    getLicenceModelsList();
    getLicenceGradeList();
    getLicenceTypeList();
  }, []);
  return (
    <div className='institutions-list'>
      {!!userInfo.roleInfo.superAdmin && (
        <SearchBox
          search={search}
          // child={
          // <Button
          //   icon={<PlusOutlined />}
          //   type='primary'
          //   onClick={toAddInstitutions}
          //   disabled={true}
          // >
          //   新增
          // </Button>
          // }
          searchData={searchSuccess}
        />
      )}
      <Table
        bordered
        size={'small'}
        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} 条数据`,
        }}
      />
    </div>
  );
};
export default InstitutionsList;
