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 dayjs from 'dayjs'
import processApi from '@/api/process/service'

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

  const Reolod = () => {
    ref.current?.resetFields()
    actionRef.current?.reload()
  }
  const columns: ProColumns<processType.output>[] = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInForm: true,
      hideInSearch: true
    },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
      formItemProps: {
        rules: [{ required: true, message: '此项为必填项!' }]
      }
    },
    {
      title: '类型',
      hideInDescriptions: true,
      dataIndex: 'processType',
      search: false,
      valueEnum: {
        0: {
          text: '人工',

        },
        1: {
          text: '设备',

        },
      },
      formItemProps: {
        rules: [{ required: true, message: '此项为必填项!' }]
      }
    },
    {
      title: '描述',
      dataIndex: 'des',

      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (_, record) => {
        return <>{dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss")}</>
      },
      search: false,
      hideInForm: true
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (text, row) => [
        <Space key={+new Date() + Math.random()}>
          <Button type='primary'  size='small' onClick={() => {
            setFromType('form')
            setSelectRow(row)
            ref.current?.setFieldsValue(row)
          }} key={+new Date() + Math.random()} target="_blank" rel="noopener noreferrer">
            编辑
          </Button>
          <Popconfirm
            key="del"
            title="确定要删除此条数据吗？"
            onConfirm={() => {

              processApi.Del(row).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  message.info("删除成功!");
                  Reolod()
                } else {
                  message.error(res.errors);
                }
              })
            }}
            onCancel={() => {
              message.info('已取消删除');
            }}
            okText="确认"
            cancelText="关闭"
          >
            <Button type='primary' danger size='small'>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ],
    },
  ];

  return (
    <>
      <ProTable<processType.output>
        columns={columns}
        type={fromType as 'table'}
        formRef={ref}
        actionRef={actionRef}
        cardBordered
        bordered
        scroll={{ x: true }}
        rowClassName={(record: any, index: number, indent: number) => {
          if (index % 2 === 0) {
            return ''; // 偶数行的类名
          } else {
            return 'even-row-background'; // 奇数行的类名
          }
        }}
        onSubmit={(params: any) => {
          params.id = selectRow?.id
          console.log(params);
          if (fromType === 'form') {
            if (params.id) {
              processApi.Update(params).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  message.info("更新成功!");
                  setFromType('table')
                  Reolod()
                } else {
                  message.error(res.errors);
                }
              })
            } else {
              processApi.Add(params).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  message.info("新增成功!");
                  setFromType('table')
                  Reolod()
                } else {
                  message.error(res.errors);
                }
              })
            }
          }
        }}

        form={{
          ignoreRules: true,// 自定义提交按钮的属性
          submitter: {
            onReset: () => {
              ref.current?.resetFields()
              setFromType("table")
            },
            searchConfig: { resetText: fromType === 'form' ? '返回' : '重置', submitText: fromType === 'form' ? '提交' : '查询' },
          }
        }}
        request={async (params = {}) => {
          const jsonData: processType.queryPage = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
          };
          const response = await processApi.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: 10,
          showSizeChanger: false
        }}
        rowKey="id"
        dateFormatter="string"
        headerTitle="列表"
        toolBarRender={() => [
          <Button key="3" type="primary" onClick={() => {
            setFromType('form');
            setSelectRow({ id: '', createTime: new Date() })
          }}>
            <PlusOutlined />
            新建
          </Button>,
        ]}
      />

    </>
  );
};