import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react';
import { useAccess, useParams } from '@umijs/max';
import { Button, FormInstance, message, Modal } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { DeleteOutlined, FormOutlined, PlusOutlined } from '@ant-design/icons';
import UpStationEdit from '@/pages/Area/Business/UpLine/edit';
import {
  addCmsAreaListRow,
  deleteCmsAreaListRow,
  getCmsAreaList,
  updateCmsAreaListRow,
} from '@/services/area/business';
import { useLocation } from '@@/exports';

const handleRemoveOne = async (selectedRow: API.AreaSubWay.LinePoint) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    const resp = await deleteCmsAreaListRow(selectedRow.commercialAreaId);
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

function ManagementList() {
  const access = useAccess();

  const formTableRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const location = useLocation();
  const params = useParams();

  const searchParams = new URLSearchParams(location.search);
  const name = searchParams.get('name');
  const id = params.id || '0';

  const [regionalId, setRegionalId] = useState<string>();
  const [regionalName, setRegionalName] = useState<string>();
  const [currentRow, setCurrentRow] = useState<API.AreaPlatForm.LinePoint>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [page, setPage] = useState<API.AreaPlatForm.LineParams>({});

  useEffect(() => {
    if (regionalId !== id) {
      setRegionalId(id);
      setRegionalName(name);
    }
  }, [regionalId, params]);

  const getStationInfo = useCallback(async () => {
    // const resData = await getCmsLineSubWay()
  }, []);

  const columns: ProColumns<API.AreaSubWay.LinePoint>[] = [
    {
      title: '商业区名称',
      dataIndex: 'commercialAreaName',
      align: 'center',
      valueType: 'text',
    },
    {
      title: '商业区地址',
      dataIndex: 'address',
      hideInSearch: true,
      align: 'center',
      valueType: 'text',
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      width: 300,
      render: (_, record) => [
        <Button
          type="link"
          size="small"
          key="edit"
          icon={<FormOutlined />}
          hidden={!access.hasPerms('area:business:List.update')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          key="batchRemove"
          icon={<DeleteOutlined />}
          hidden={!access.hasPerms('area:subway:List')}
          onClick={async () => {
            Modal.confirm({
              title: '删除',
              content: '确定删除该项吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const success = await handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}
        >
          删除
        </Button>,
      ],
    },
  ];
  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.AreaPlatForm.Line>
          // params 是需要自带的参数
          // 这个参数优先级更高，会覆盖查询表单的参数
          actionRef={actionRef}
          formRef={formTableRef}
          columns={columns}
          headerTitle="信息"
          rowKey="stationId"
          key="stationId"
          request={(params) => {
            return getCmsAreaList({
              regionalId,
              ...params,
            } as API.AreaPlatForm.LineParams).then((res) => {
              setPage(params as API.AreaPlatForm.LineParams);
              const result = {
                data: res.rows,
                total: res.total,
                success: true,
              };
              return result;
            });
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('manage:List:add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
        />
      </div>
      <UpStationEdit
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        onSubmit={async (values) => {
          if (values.commercialAreaId) {
            const resData = await updateCmsAreaListRow(values);
            if (resData.code === 200) {
              setModalVisible(false);
              setCurrentRow(undefined);
              message.success('添加成功');
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          } else {
            let params = {
              regionalName,
              regionalId,
              ...values,
            };
            const resData = await addCmsAreaListRow(params);
            if (resData.code === 200) {
              setModalVisible(false);
              setCurrentRow(undefined);
              message.success('添加成功');
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }
          // values.regionalId =
          //   values.lineName =
          // const resData = await addCmsAreaListRow(values);
          // if (resData.code === 200) {
          //   setModalVisible(false);
          //   setCurrentRow(undefined);
          //   message.success('添加成功');
          //   if (actionRef.current) {
          //     actionRef.current.reload();
          //   }
          // }
        }}
        values={currentRow}
      ></UpStationEdit>
    </Fragment>
  );
}

export default ManagementList;
