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 workplanApi from '@/api/work/plan/service'
import finalApi from '@/api/finalService'

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

  const Reolod = () =>{
    ref.current?.resetFields()
    actionRef.current?.reload()
  }
  const columns: ProColumns<workPlanTypes.output>[] = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInForm: true,
      hideInSearch:true
    },
    {
      title: '计划名称',
      dataIndex: 'name',
      ellipsis: true,
      formItemProps:{
        rules:[{ required: true, message: '此项为必填项!' }]
      }
    },
    {
      title: '成品',
      hideInDescriptions: true,
      dataIndex: 'finalId',
      valueType:'select',
      request:async ()=>{
        const data: MyResponse.Content = await finalApi.SelectList()
        const chan: any[] = data.data;
        chan.map((item) => (
          item.label = item.value,
          item.value = item.key
        ))
        return chan;
      },
      formItemProps:{
        rules:[{ required: true, message: '此项为必填项!' }]
      }
    },
    {
      title: '数量',
      dataIndex: 'quantity',
    
      search: false,
      formItemProps:{
        rules:[{ required: true, message: '此项为必填项!' }]
      }
    },
    {
        title: '预计时间',
        dataIndex: 'dateRange',
    
        search: false,
        valueType:'dateRange',
       render(dom, entity, index, action, schema) {
           return <>{dayjs(entity.expectedStartTime).format("YYYY年MM月DD日") } ~ {dayjs(entity.expectedEndTime).format("YYYY年MM月DD日")}</>
       },
        formItemProps:{
            rules:[{ required: true, message: '此项为必填项!' }]
          }
      },
    {
      title: '操作',
      valueType: 'option',
      fixed:'right',
      render: (text, row) => [
        <Space key={+new Date() + Math.random()}>
          <Button size='small' type='primary' 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={() => {
          
            workplanApi.Del(row).then((res: MyResponse.Content) => {
              if (res.statusCode === 200) {
                message.info("删除成功!");
                Reolod()
              } else {
                message.error(res.errors);
              }
            })
          }}
          onCancel={() => {
            message.info('已取消删除');
          }}
          okText="确认"
          cancelText="关闭"
        > 
          <Button size='small' type='primary' danger > 
            删除
          </Button>
          </Popconfirm>
        </Space>
      ],
    },
  ];

  return (
    <>
        <ProTable<workPlanTypes.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) => {
           
            if (fromType === 'form') {
              params.id = selectRow.id
              params.expectedStartTime = params.dateRange[0]
              params.expectedEndTime =  params.dateRange[1]
              console.log(params);
              if (params.id) {
                params.e
                workplanApi.Update(params).then((res: MyResponse.Content) => {
                  if (res.statusCode === 200) {
                    message.info("更新成功!");
                    setFromType('table')
                    Reolod()
                  } else {
                    message.error(res.errors);
                  }
                })
              } else {
                workplanApi.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: workPlanTypes.queryPage = {
              pageIndex: params.current || 1,
              pageSize: params.pageSize || 10,
              name: params.name || '',
              finalId:params.finalId || ''
            };
            const response = await workplanApi.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,
            showSizeChanger:false
          }}
          rowKey="id"
          dateFormatter="string"
          headerTitle="列表"
          toolBarRender={() => [
            <Button key="3" type="primary" onClick={() => {
              setFromType('form');
              setSelectRow({id:''})
            }}>
              <PlusOutlined />
              新建
            </Button>,
          ]}
        />
    </>
  );
};