import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, message, Modal, Table, Tag } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { ChangeModal } from '~/pages/customManage/customList/comp/changeModal';
import { InterListType, InterReqType } from '~/api/interface';
import { listAppUserType } from '~/api/interface/customManageType';
import { CustomManageAPI, SystemManageAPI } from '~/api';
import qs from 'query-string';
import { useNavigate } from 'react-router-dom';

// 表格数据类型
type TableType = InterListType<listAppUserType>;
// 请求数据的类型
type ReqType = InterReqType<listAppUserType>;
// 搜索表单的数据
let query: ReqType = {};
//来源列表
const portTypeList = [
  { value: 100, label: '自然流' },
  { value: 200, label: '海报' },
  { value: 300, label: '抖音' },
  { value: 400, label: '公众号' },
  { value: 500, label: '社群' },
  { value: 600, label: '招投标' },
];

function CustomListView() {
  const { confirm } = Modal;
  // 路由钩子
  const navigate = useNavigate();
  // 是否打开变更弹窗
  const [isChangeVisModal, setIsChangeVisModal] = useState<boolean>(false);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 需要编辑的数据
  const [editData, setEditData] = useState<TableType[0]>();
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await CustomManageAPI.listAppUser({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list);
      // console.log('加载列表 --->', list);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: ReqType) => {
    pagination.current = 1;
    query = data;
    getTableList(data).then();
  };
  // 删除用户
  const handleDelete = (value: TableType[0]) => {
    confirm({
      title: '提示',
      content: '是否删除该账号？',
      onOk: async () => {
        const res = await SystemManageAPI.removeBAccount({ userAccountId: value.id });
        if (res && res.code === '200') {
          message.success('删除成功');
          paginationChange(
            tableData.length === 1 ? pagination.current - 1 : pagination.current,
            pagination.pageSize,
          );
        }
      },
    });
  };
  // 跳转详情
  const handleInvite = (record: TableType[0]) => {
    const search = {
      id: record.id,
    };
    navigate(`/customManage/customList/detail?${qs.stringify(search)}`);
  };
  // componentDidMount
  useEffect(() => {
    query = {};
    (async () => {
      await getTableList();
    })();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '用户UID',
      dataIndex: 'id',
      align: 'center',
      width: '100px',
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      align: 'center',
      render: (text, record) => text || record.nickName,
    },
    {
      title: '手机号',
      dataIndex: 'phoneNum',
      align: 'center',
    },
    {
      title: '认证企业',
      dataIndex: 'companyName',
      align: 'center',
    },
    {
      title: '企业认证',
      dataIndex: 'companyAuthStatus',
      align: 'center',
      render: (text) => (text === 0 ? '未认证' : '已认证'),
    },
    {
      title: '电子签约认证',
      dataIndex: 'userName',
      align: 'center',
      render: (_text) => `未认证`,
    },
    {
      title: '用户来源',
      dataIndex: 'portType',
      align: 'center',
      render: (text) => portTypeList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '账号类型',
      dataIndex: 'phoneNum',
      align: 'center',
      render: (text) => (text ? '普通用户' : '游客用户'),
    },
    {
      title: '加盟身份',
      dataIndex: 'cooperationTagVOS',
      align: 'center',
      width: '100px',
      render: (_text, record) =>
        record.cooperationTagVOS?.map((i, j) => (
          <Tag color='processing' key={j} style={{ marginBottom: '10px' }}>
            {i.tagName}
          </Tag>
        )),
    },
    {
      title: '上级推荐人',
      align: 'center',
      render: (_text, record) =>
        record?.userRcdVO?.id &&
        `${record?.userRcdVO?.rcdUserName || record?.userRcdVO?.rcdNickname}(${
          record?.userRcdVO?.rcdUserId
        })`,
    },
    {
      title: '推荐伙伴',
      dataIndex: 'inviteCount',
      align: 'center',
      render: (text, record) =>
        !!text && (
          <Button type={'link'} onClick={() => handleInvite(record)}>
            {text}
          </Button>
        ),
    },
    {
      title: '相关运营',
      dataIndex: 'remark',
      align: 'center',
      render: (_text) => `--`,
    },
    {
      title: '相关销售',
      dataIndex: 'remark',
      align: 'center',
      render: (_text) => `--`,
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      width: '100px',
      render: (_text, record) => (
        <>
          <Button
            type={'link'}
            onClick={() => {
              setEditData(JSON.parse(JSON.stringify(record)));
              setIsChangeVisModal(true);
            }}
          >
            变更
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          {
            label: '用户名称',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入UID、用户名称',
          },
          {
            label: '手机号',
            name: 'phoneNum',
            type: 'input',
            placeholder: '请输入手机号',
          },
          {
            label: '来源',
            name: 'portType',
            type: 'Select',
            placeholder: '请选择相关来源',
            options: portTypeList,
          },
          {
            label: '创建时间',
            name: 'rangeTime',
            type: 'rangePicker',
            placeholder: '请选择创建时间',
          },
          {
            label: '企业认证',
            name: 'companyAuthStatus',
            type: 'Select',
            placeholder: '请选择是否认证',
            options: [
              { value: 0, label: '未认证' },
              { value: 1, label: '已认证' },
            ],
          },
          // {
          //   label: '电子签约认证',
          //   name: 'contract',
          //   type: 'Select',
          //   placeholder: '请选择是否认证',
          //   options: [
          //     { value: 1, label: '未认证' },
          //     { value: 2, label: '已认证' },
          //   ],
          // },
        ]}
        searchData={onFinish}
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1200 }}
        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} 条数据`,
        }}
        // rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
      />
      <ChangeModal
        open={isChangeVisModal}
        closed={() => {
          setIsChangeVisModal(false);
          paginationChange(pagination.current, pagination.pageSize);
        }}
        data={editData}
      />
    </>
  );
}

export default CustomListView;
