import { PlusOutlined } from '@ant-design/icons';
import type {
  ActionType,
  ProColumns,
  ProFormInstance,
} from '@ant-design/pro-components';
import {
  ProCard,
  ProTable,
} from '@ant-design/pro-components';
import { Button, message, Popconfirm, Space } from 'antd';
import { useState, useRef } from 'react';
//引入接口
import templateApi from '@/api/app/template/service'

export default () => {
  const [fromType, setFromType] = useState<any>('table')
  const ref = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();

  const Reolod = () =>{
    ref.current?.resetFields()
    actionRef.current?.reload()
  }
  const columns: ProColumns<template.output>[] = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInForm: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '编码',
      hideInTable: true,
      hideInDescriptions: true,
      dataIndex: 'code',
      search: false,
    },
    {
      title: '描述',
      dataIndex: 'des',
      width: 120,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'id',
      render: (text, row) => [
        <Space key={+new Date() + Math.random()}>
          <a  onClick={() => {
             setFromType('form')
            ref.current?.setFieldsValue(row)
          }} key={+new Date() + Math.random()} target="_blank" rel="noopener noreferrer">
            编辑
          </a>
          <Popconfirm
           key="del"
           title="确定要删除此条数据吗？"
           onConfirm={() => {
          
            templateApi.Del(row).then((res: MyResponse.Content) => {
              if (res.statusCode === 200) {
                message.info("删除成功!");
                Reolod()
              } else {
                message.error(res.errors);
              }
            })
          }}
          onCancel={() => {
            message.info('已取消删除');
          }}
          okText="确认"
          cancelText="关闭"
        > 
          <a> 
            删除
          </a>
          </Popconfirm>
        </Space>
      ],
    },
  ];

  return (
    <>
      <ProCard>
        {fromType === 'form' ? <Button type='link' onClick={() =>{
           ref.current?.resetFields();
          setFromType("table")}}>⬅返回</Button> : ""}
        <ProTable<template.output>
          columns={columns}
          type={fromType as 'table'}
          formRef={ref}
          actionRef={actionRef}
          onSubmit={(params: any) => {
            console.log(params);
            if (fromType === 'form') {
              if (params.id) {
                templateApi.Update(params).then((res: MyResponse.Content) => {
                  if (res.statusCode === 200) {
                    message.info("更新成功!");
                    setFromType('table')
                    Reolod()
                  } else {
                    message.error(res.errors);
                  }
                })
              } else {
                templateApi.Add(params).then((res: MyResponse.Content) => {
                  if (res.statusCode === 200) {
                    message.info("新增成功!");
                    setFromType('table')
                    Reolod()
                  } else {
                    message.error(res.errors);
                  }
                })
              }
            }
          }}
          request={async (params = {}) => {
            const jsonData: template.queryPage = {
              pageIndex: params.current || 1,
              pageSize: params.pageSize || 10,
              name: params.name || '',
            };
            const response = await templateApi.PagedList(jsonData);
            if (response.statusCode === 200) {
              return {
                data: response.data.items,
                success: true,
                total: response.data.total,
              };
            } else {
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
          }}
          pagination={{
            pageSize: 5,
          }}
          rowKey="id"
          dateFormatter="string"
          headerTitle="列表"
          toolBarRender={() => [
            <Button key="3" type="primary" onClick={() => {
              setFromType('form');
            }}>
              <PlusOutlined />
              新建
            </Button>,
          ]}
        />
      </ProCard>
    </>
  );
};