import { useEffect, useState } from 'react';
import { InterListType, InterReqType } from '~/api/interface';
import { listBAccountPageType } from '~/api/interface/systemManageType';
import SearchBox from '~/components/search-box';
import { Button, message, Modal, Table, Tooltip } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import { SystemManageAPI } from '~/api';
import AddEditModal from '~/pages/systemManage/accountManage/comp/addEditModal';
import ChangeModal from '~/pages/systemManage/accountManage/comp/changeModal';

// 列表的数据类型
type TableType = InterListType<listBAccountPageType>;
// 请求数据的类型
type ReqType = InterReqType<listBAccountPageType>;
// 搜索表单的数据
let query: ReqType = {};

function AccountManageView() {
  const { confirm } = Modal;
  // 新增编辑弹窗是否开启
  const [addEditModalVisible, setAddEditModalVisible] = useState(false);
  // 变更密码弹窗是否开启
  const [changeModalVisible, setChangeModalVisible] = useState(false);
  // 需要编辑的数据
  const [editData, setEditData] = useState<TableType[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 SystemManageAPI.listBAccountPage({
      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);
    }
  };
  // 翻页
  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,
          );
        }
      },
    });
  };
  // componentDidMount
  useEffect(() => {
    query = {};
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '账号',
      dataIndex: 'accountNo',
      align: 'center',
      width: '150px',
      fixed: 'left',
    },
    {
      title: '账号类型',
      dataIndex: 'accountType',
      align: 'center',
      width: '10%',
      render: (text) => (text === 1 ? '员工' : '合伙人'),
    },
    { title: '姓名', dataIndex: 'userName', align: 'center', width: '10%' },
    {
      title: '所属单位',
      align: 'center',
      dataIndex: 'companyName',
      width: '150px',
      ellipsis: true,
    },
    {
      title: '渠道等级',
      dataIndex: 'channelLevel',
      align: 'center',
      width: '150px',
    },
    {
      title: '角色',
      align: 'center',
      width: '10%',
    },
    { title: '手机号', dataIndex: 'phoneNum', align: 'center', width: '150px' },
    { title: '邮箱', align: 'center', width: '12%', dataIndex: 'email' },
    {
      title: '备注',
      align: 'center',
      width: '10%',
      dataIndex: 'remark',
      render: (text) => (
        <Tooltip placement='top' title={text}>
          <div className='remark-wrap'>{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '账号状态',
      dataIndex: 'accountStatus',
      align: 'center',
      width: '10%',
      render: (text) => (text === 1 ? '可用' : '停用'),
    },
    {
      title: '企业实名认证',
      dataIndex: 'companyAuthStatus',
      align: 'center',
      width: '10%',
    },
    {
      title: '操作',
      width: '160px',
      fixed: 'right',
      align: 'center',
      render: (_text, record) => (
        <>
          <Button
            type='link'
            onClick={() => {
              setEditData(JSON.parse(JSON.stringify(record)));
              setAddEditModalVisible(true);
            }}
          >
            变更
          </Button>
          <Button
            type='link'
            onClick={() => {
              setEditData(JSON.parse(JSON.stringify(record)));
              setChangeModalVisible(true);
            }}
          >
            修改密码
          </Button>
          <Button type='link' danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          {
            label: '账号',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入姓名或账号',
          },
          {
            label: '账号类型',
            name: 'userType',
            type: 'Select',
            placeholder: '请选择账号类型',
            options: [
              { value: 1, label: '员工' },
              { value: 0, label: '合伙人' },
            ],
          },
          {
            label: '角色',
            name: 'roleId',
            type: 'Select',
            placeholder: '请选择账号角色',
            options: [],
          },
          {
            label: '状态',
            name: 'accountStatus',
            type: 'Select',
            placeholder: '请选择账号状态',
            options: [
              { value: 1, label: '可用' },
              { value: 0, label: '停用' },
            ],
          },
        ]}
        child={
          <>
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              onClick={() => {
                setAddEditModalVisible(true);
              }}
            >
              新增账号
            </Button>
          </>
        }
        searchData={onFinish}
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1500 }}
        bordered
        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} 条数据`,
        }}
      />
      <AddEditModal
        open={addEditModalVisible}
        title={editData ? '变更账号' : '新增账号'}
        data={editData}
        closed={() => {
          setAddEditModalVisible(false);
          setEditData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
      />
      <ChangeModal
        open={changeModalVisible}
        title={'修改密码'}
        data={editData}
        closed={() => {
          setChangeModalVisible(false);
          setEditData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
      />
    </>
  );
}

export default AccountManageView;
