import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, message, Modal, Table } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { InterListType, InterReqListType } from '~/api/interface';
import { listModuleInfoPage } from '~/api/interface/commonType';
import { ColumnsType } from 'antd/es/table';
import { CommonAPI } from '~/api';
import RemarkChange from '~/components/remarkChange';
import AddModuleModal from '~/pages/resourceManage/materielManage/comp/addModuleModal';
import qs from 'query-string';
import { useNavigate } from 'react-router-dom';

// 列表类型
type TableType = InterListType<listModuleInfoPage>;
// 请求的参数
type ReqType = InterReqListType<listModuleInfoPage>;
// 搜索表单的数据
let query: ReqType = {};
// 所属产品
const moduleType = [
  { label: '云享飞', value: 0 },
  { label: '云飞手', value: 1 },
  { label: '云仓', value: 2 },
  { label: '无人机城', value: 3 },
];

const MaterielManageView = () => {
  const { confirm } = Modal;
  // 路由钩子
  const navigate = useNavigate();
  // 备注弹窗是否开启
  const [remarkModalVisible, setRemarkModalVisible] = useState(false);
  // 新增弹窗是否开启
  const [addModalVisible, setAddModalVisible] = 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 CommonAPI.listModuleInfoPage({
      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 handleRemark = (record: TableType[0]) => {
    setEditData(record);
    setRemarkModalVisible(true);
  };
  // 修改备注
  const handleRemarkChange = async (data: TableType[0]) => {
    const res = await CommonAPI.updateModuleInfoRemark({
      id: data.id,
      remark: data.remark,
    });
    if (res && res.code === '200') {
      paginationChange(pagination.current, pagination.pageSize);
      setEditData(undefined);
      setRemarkModalVisible(false);
    }
  };
  // 删除数据
  const handleDelete = (record: TableType[0]) => {
    confirm({
      title: '提示',
      content: '是否删除该模块？',
      onOk: async () => {
        const res = await CommonAPI.removeModuleInfo({ id: record.id });
        if (res && res.code === '200') {
          paginationChange(pagination.current, pagination.pageSize);
          await message.success('删除成功');
        }
      },
    });
  };
  // 跳转详情
  const handleDetail = (record: TableType[0]) => {
    const search = {
      id: record.id,
      moduleCode: record.moduleCode,
      moduleName: record.moduleName,
      moduleType: record.moduleType,
    };
    navigate(`/resourceManage/materielManage/detail?${qs.stringify(search)}`);
  };
  // componentDidMount
  useEffect(() => {
    query = {};
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '序号',
      dataIndex: 'accountNo',
      align: 'center',
      width: '50px',
      render: (_text, _record, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '模块名称',
      dataIndex: 'moduleName',
      align: 'center',
    },
    {
      title: '所属产品',
      dataIndex: 'moduleType',
      align: 'center',
      render: (text) => moduleType?.find((i) => i.value === text)?.label || text,
    },
    {
      title: '模块代码',
      dataIndex: 'moduleCode',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
      width: '150px',
      ellipsis: true,
      render: (text, record) => (
        <Button type={'link'} onClick={() => handleRemark(record)}>
          {text ? text : '--'}
        </Button>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      width: '150px',
      fixed: 'right',
      render: (_text, record) => (
        <>
          <Button type={'link'} onClick={() => handleDetail(record)}>
            详情
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          {
            label: '模块名称',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入模块名称',
          },
          {
            label: '所属产品',
            name: 'moduleType',
            type: 'Select',
            placeholder: '请选择所属产品',
            options: moduleType,
          },
          {
            label: '模块代码',
            name: 'moduleCode',
            type: 'input',
            placeholder: '请输入模块代码',
          },
        ]}
        child={
          <>
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              onClick={() => {
                setAddModalVisible(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} 条数据`,
        }}
      />
      <RemarkChange
        open={remarkModalVisible}
        data={editData}
        closed={() => {
          paginationChange(pagination.current, pagination.pageSize);
          setEditData(undefined);
          setRemarkModalVisible(false);
        }}
        change={handleRemarkChange}
      />
      <AddModuleModal
        open={addModalVisible}
        title={editData?.id ? '编辑' : '新增'}
        data={editData}
        closed={() => {
          paginationChange(pagination.current, pagination.pageSize);
          setEditData(undefined);
          setAddModalVisible(false);
        }}
      />
    </>
  );
};

export default MaterielManageView;
