import React, { useState, useEffect } from "react";
import { Table, Card, message, Button, Popconfirm, Row, Col } from "antd";
import { ColumnsType } from "antd/es/table";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { PaginationProps } from "antd/lib/pagination";
import { TableListItem } from "./data";
import { queryRule, updateRule, removeRule, addRule } from "./service";
import UpdateForm, { FormValueType } from './components/UpdateForm';

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在保存');

  if (!fields.id) {
    // eslint-disable-next-line no-param-reassign
    delete fields.id
    try {
      const msg = await addRule({...fields});
      hide();
      if (msg.retcode) {
        message.success('添加成功');
      } else {
        message.error('添加失败请重试！');
      }
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  } else {
    try {
      const msg = await updateRule({...fields});
      hide();
      if (msg.retcode) {
        message.success('保存成功');
      } else {
        message.error('保存失败请重试！');
      }
      return true;
    } catch (error) {
      hide();
      message.error('保存失败请重试！');
      return false;
    }
  }
};

/**
 * 删除节点
 * @param id 
 */
const handleRemove = async (id?: number) => {
  const hide = message.loading('正在删除');
  if (!id) return false;

  try {
    const msg = await removeRule({
      id
    });
    hide();
    if (msg.retcode) {
      message.success('删除成功，即将刷新');
    } else {
      message.error('删除失败，请重试');
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleTableChange = async (params: any) => {
  const param = {
    pageNum: params.current,
    pageSize: params.pageSize
  }
  const msg = await queryRule(param);
  return {
    data: msg.data?.list,
    total: msg.data?.total,
    success: msg.retcode,
  };
};

const UserList: React.FC<{}> = () => {
  const [data, handleDataChange] = useState<TableListItem[]>([]);
  const [loading, handleLoadChange] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [page, handlePageChange] = useState<PaginationProps>({
    total: 0,
    pageSize: 20,
    current: 1,
    pageSizeOptions: ['20'],
    showTotal: ((total:number) => {
      return `共 ${total} 条`;
    }),
  });
  // const [form] = Form.useForm();
  // const [formVals,setSearchValues] = useState<FormValueType>({
  //   name: ''
  // });
  const handleChange = async (pagination: any) => {
    handleLoadChange(true)
    const res = await handleTableChange(pagination);
    handleLoadChange(false)
    handleDataChange(res.data)
    handlePageChange({
      total: res.total,
      pageSize: pagination.pageSize,
      current: pagination.current,
    })
  }
  // const onFinish = (value: any) => {
  //   setSearchValues(value)
  //   handleChange(page,value)
  // };
  const columns: ColumnsType<TableListItem> = [
    {
      title: "编号",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "级别",
      dataIndex: "levelName",
      key: "levelName",
    },
    {
      title: "状态",
      dataIndex: "state",
      key: "state",
      render(value) {
        return value == 1 ? '有效' : '无效'
      },
    },
    {
      title: "操作",
      key: "action",
      render: (text, record) => (
        <span>
          <a style={{ marginRight: 8 }} onClick={()=>{
            handleUpdateModalVisible(true);
            setStepFormValues(record);
          }}>编辑</a>
          <Popconfirm title="确定删除该级别?" onConfirm={async () => {
            const success = await handleRemove(record.id)
            if (success) handleChange(page)
          }}>
            <a style={{color: 'red'}}>删除</a>
          </Popconfirm>
        </span>
      )
    }
  ];
  useEffect(() => {
    async function fetchData() {
      handleLoadChange(true)
      page.current = 1
      const res = await handleTableChange(page)
      handleLoadChange(false)
      page.total = res.total
      handleDataChange(res.data)
    }
    fetchData()
  }, []);
  return (
    <PageHeaderWrapper>
      <Card bordered={false}>
        <div id="components-table-demo-basic">
          <Row justify="space-between">
            <Col span={14} />
            <Col span={8}>
              <div style={{textAlign: 'right'}}>
                <Button style={{marginBottom: 15}} type="primary" onClick={() => {
                  handleUpdateModalVisible(true);
                  setStepFormValues({
                    id: undefined,
                  });
                }}>
                  新增
                </Button>
              </div>
            </Col>
          </Row>
          
          <Table
            columns={columns}
            rowKey="id"
            dataSource={data}
            pagination={page}
            loading={loading}
            onChange={async pagination => {
              handleChange(pagination)
            }}
          />
        </div>
      </Card>
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);

            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});

              handleChange(page)
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
    </PageHeaderWrapper>
  )
}

export default UserList;
