import { useState, useEffect } from 'react';
import SearchBox from '~/components/search-box';
import { Button, message, Modal, Table } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { InterListType, InterReqType } from '~/api/interface';
import { ColumnsType } from 'antd/es/table';
import { SystemManageAPI } from '~/api';
import { listCompanyPage } from '~/api/interface/systemManageType';
import { useNavigate } from 'react-router-dom';
import AddEditModal from './comp/addEditModal';

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

const CompanyManageView = () => {
  const navigate = useNavigate();
  const { confirm } = Modal;
  // 新增编辑弹窗是否开启
  const [addEditModalVisible, setAddEditModalVisible] = 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.listCompanyPage({
      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.listCompanyRemove({ id: value.id });
        if (res && res.code === '200') {
          message.success('删除成功');
          paginationChange(
            tableData.length === 1 ? pagination.current - 1 : pagination.current,
            pagination.pageSize,
          );
        }
      },
    });
  };
  //跳转单位详情
  const toCompanyDetail = (record: TableType[0]) => {
    navigate({
      pathname: '/systemManage/companyDetail',
      search: `id=${record.id}`,
    });
  };

  // componentDidMount
  useEffect(() => {
    query = {};
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '单位名称',
      dataIndex: 'companyName',
      align: 'center',
      width: '20%',
      fixed: 'left',
      ellipsis: true,
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      align: 'center',
      width: '250px',
      ellipsis: true,
    },
    {
      title: '联系人',
      dataIndex: 'companyUserName',
      align: 'center',
    },
    {
      title: '联系电话',
      dataIndex: 'phoneNum',
      align: 'center',
    },
    {
      title: '操作',
      width: '20%',
      fixed: 'right',
      align: 'center',
      render: (_text, record) => (
        <>
          <Button
            type='link'
            onClick={() => {
              setEditData(JSON.parse(JSON.stringify(record)));
              setAddEditModalVisible(true);
            }}
          >
            变更
          </Button>
          <Button type='link' onClick={() => toCompanyDetail(record)}>
            详情
          </Button>
          <Button
            type='link'
            danger
            onClick={() => handleDelete(record)}
            disabled={record.id === 1}
          >
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          {
            label: '单位名称',
            name: 'companyName',
            type: 'input',
            placeholder: '请输入单位名称',
          },
        ]}
        searchData={onFinish}
        child={
          <>
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              onClick={() => {
                setAddEditModalVisible(true);
              }}
            >
              新增单位
            </Button>
          </>
        }
      />
      <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);
        }}
      />
    </>
  );
};

export default CompanyManageView;
