import React, {Fragment, useRef, useState} from "react";
import { useIntl, FormattedMessage, useAccess, history } from '@umijs/max';
import { Dropdown, FormInstance, Space, Button, message, Modal } from 'antd';
import { ActionType, FooterToolbar, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, FormOutlined, DownOutlined, AlignLeftOutlined } from '@ant-design/icons';
import {getCmsAreaList, addCmsAreaListRow, updateCmsAreaListRow, deleteCmsAreaListRow} from "@/services/area/business";
import SubWayEdit from "@/pages/Area/Business/edit";
import {deleteCmsLineSubWay} from "@/services/area/subway";


const handleRemoveOne = async (selectedRow: API.AreaBusiness.Circle) => {
  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 [currentRow, setCurrentRow] = useState<API.AreaBusiness.Circle>()
  const [modalVisible, setModalVisible] = useState<boolean>(false)

  const columns: ProColumns<API.AreaBusiness.Circle>[] = [
    {
      title: '商圈名称',
      dataIndex: 'commercialAreaName',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => [
        <Button
          type="link"
          size="small"
          key="detail"
          icon = <AlignLeftOutlined />
          hidden={!access.hasPerms('area:business:list.detail')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          详细
        </Button>,
        <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:business: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.AreaBusiness.Circle>
          // params 是需要自带的参数
          // 这个参数优先级更高，会覆盖查询表单的参数
          actionRef={actionRef}
          formRef={formTableRef}
          columns={columns}
          request={(params) =>
            getCmsAreaList({ ...params } as API.AreaBusiness.CircleParams).then((res) => {
              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>
      <SubWayEdit
        open={modalVisible}
        onSubmit={async (values) => {
          let resData
          if(values.commercialAreaId) {
            resData = await updateCmsAreaListRow(values)
          } else {
            resData = await addCmsAreaListRow(values)
          }
          if (resData.code === 200) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if(values.commercialAreaId) {
              message.success('修改成功')
            } else {
              message.success('新增成功')
            }
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        values={currentRow}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined)
        }}
      ></SubWayEdit>
    </Fragment>
  )
}
export default ManagementList
