import SearchBox, { searchColumns as searchColumnsType } from '~/components/search-box';
import { Button, Table, Tag } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { CommonAPI, FlyerCenterAPI } from '~/api';
import { useEffect, useState } from 'react';
import { InterDataType, InterReqListType, PaginationProps } from '~/api/interface';
import { backListPilotType } from '~/api/interface/flyerCenterType';
import { getSecondDistrictInfoType } from '~/api/interface/commonType';
import { useNavigate } from 'react-router-dom';
import UpdateRemarkModal from './components/updateRemarkModal';

//飞手列表返回类型
type flyerListType = InterDataType<backListPilotType>['list'];
//飞手列表请求类型
type flyerListParameters = InterReqListType<backListPilotType>;
//地址返回数据
type locationType = InterDataType<getSecondDistrictInfoType>;

const FlyerList = () => {
  const navigate = useNavigate();

  const [searchColumns, setSearchColumns] = useState<searchColumnsType[]>([
    {
      name: 'accountNumber',
      label: '账号',
      placeholder: '请输入UID,姓名或手机号',
      type: 'input',
    },
    {
      name: 'auditStatus',
      label: '执照认证状态',
      placeholder: '请选择执照认证状态',
      type: 'select',
      options: [
        { id: 0, name: '审核中' },
        { id: 1, name: '已通过' },
        { id: 2, name: '未通过' },
      ],
    },
    {
      name: 'abilityId',
      label: '能力认证',
      placeholder: '请选择能力认证',
      type: 'select',
      options: [],
    },
    {
      name: 'areaNumber',
      label: '常驻城市',
      placeholder: '请选择常驻城市',
      type: 'Cascader',
      options: [],
    },
  ]);
  const tableColumns: ColumnsType<flyerListType[0]> = [
    {
      title: 'UID',
      dataIndex: 'userAccountId',
      align: 'center',
    },
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'userName',
    },
    {
      title: '执照认证状态',
      align: 'center',
      dataIndex: 'auditStatus',
      render: (text: number) => (text === 0 ? '审核中' : text === 1 ? '已通过' : '未通过'),
    },
    {
      title: '能力认证',
      align: 'center',
      dataIndex: 'pilotAbility',
      width: '20%',
      render: (text: flyerListType[0]['pilotAbility']) =>
        text ? text.map((v) => <Tag key={v.abilityId}>{v.abilityName}</Tag>) : '',
    },
    {
      title: '常驻城市',
      align: 'center',
      dataIndex: 'residentCity',
    },
    {
      title: '手机号',
      align: 'center',
      dataIndex: 'phoneNum',
    },
    {
      title: '申请认证时间',
      align: 'center',
      dataIndex: 'createTime',
    },
    {
      title: '备注',
      align: 'center',
      dataIndex: 'remark',
      width: '20%',
      ellipsis: true,
      render: (text: string, record) => (
        <div
          onClick={() => updateRemarkClick(record)}
          style={{
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            width: '100%',
            overflow: 'hidden',
            cursor: 'pointer',
            color: '#1677ff',
          }}
        >
          {text || '--'}
        </div>
      ),
    },
    {
      title: '操作',
      align: 'center',
      render: (_text: string, record) => (
        <>
          <Button
            type='link'
            danger
            disabled={record.auditStatus !== 0}
            onClick={() => toFlyerApprove(record)}
          >
            审批
          </Button>
          <Button type='link' onClick={() => toFlyerDetail(record)}>
            详情
          </Button>
        </>
      ),
    },
  ];

  const [tableData, setTableData] = useState<flyerListType>([]);
  const [currentTableItem, setCurrentTableItem] = useState<flyerListType[0]>();
  const [query, setQuery] = useState<flyerListParameters>();
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [loading, setLoading] = useState<boolean>(false);
  //修改备注弹窗
  const [updateRemarkModalShow, setUpdateRemarkModalShow] = useState<boolean>(false);

  //飞手列表
  const getFlyerList = (query?: flyerListParameters) => {
    setLoading(true);
    FlyerCenterAPI.getBackListPilot({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      pagination.totalCount = result.totalCount;
      setTableData(result.list || []);
      setPagination(pagination);
    });
  };
  //飞手能力列表
  const getAbilityList = () => {
    FlyerCenterAPI.getAbilityList().then(({ result }) => {
      searchColumns[2].options = (result || []).map((v) => ({
        id: v.abilityId,
        name: v.abilityName,
      }));
      setSearchColumns([...searchColumns]);
    });
  };

  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getFlyerList(query);
  };
  //筛选成功
  const searchSuccess = (value: flyerListParameters) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setQuery({ ...value, areaNumber: value.areaNumber ? value.areaNumber[1] : undefined });
    getFlyerList({ ...value, areaNumber: value.areaNumber ? value.areaNumber[1] : undefined });
  };
  //获取地域数据
  const getSecondDistrictInfo = () => {
    CommonAPI.getSecondDistrictInfo().then(({ result }) => {
      const covertLocationData: any = (list: locationType) => {
        return list.map((v) => ({
          label: v.name,
          value: v.id,
          children: v.childInfo ? covertLocationData(v.childInfo) : [],
        }));
      };
      searchColumns[3].options = covertLocationData(result);
      setSearchColumns([...searchColumns]);
    });
  };
  //认证日志页面
  const toFlyerAuthDaily = () => {
    navigate('/flyerCenter/flyerAuthDaily');
  };
  //飞手审批页面
  const toFlyerApprove = (record: flyerListType[0]) => {
    navigate({ pathname: '/flyerCenter/flyerDetail', search: `id=${record.id}&isApprove=1` });
  };
  //飞手详情页面
  const toFlyerDetail = (record: flyerListType[0]) => {
    navigate({ pathname: '/flyerCenter/flyerApprove', search: `id=${record.id}` });
  };
  //修改备注
  const updateRemarkClick = (record: flyerListType[0]) => {
    setCurrentTableItem(record);
    setUpdateRemarkModalShow(true);
  };
  const updateRemarkModalCancel = () => {
    setUpdateRemarkModalShow(false);
  };
  const updateRemarkModalOk = () => {
    getFlyerList(query);
    setUpdateRemarkModalShow(false);
  };

  useEffect(() => {
    getFlyerList();
    getAbilityList();
    getSecondDistrictInfo();
  }, []);

  return (
    <div className='flyer-list'>
      <SearchBox
        search={searchColumns}
        searchData={searchSuccess}
        child={
          <Button type='primary' onClick={toFlyerAuthDaily}>
            认证日志
          </Button>
        }
      />
      <Table
        bordered
        columns={tableColumns}
        dataSource={tableData}
        loading={loading}
        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} 条数据`,
        }}
      />
      {/*修改备注*/}
      <UpdateRemarkModal
        open={updateRemarkModalShow}
        onOk={updateRemarkModalOk}
        onCancel={updateRemarkModalCancel}
        flyerItem={currentTableItem}
      />
    </div>
  );
};
export default FlyerList;
