/**
 * 设备基础信息管理
 * @param Page
 * @returns
 */
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Tag, DatePicker as TDatePicker, Select } from 'antd';
import { useEffect, useRef, useState } from 'react';
import DeviceInfoAPI from '@/api/DeviceInfo';
import deviceProductAPI from '@/api/deviceInfo/services/deviceProduct';
import dayjs from 'dayjs'



const DatePicker: any = TDatePicker;

export default () => {
  //表单
  const [typeForm] = Form.useForm();
  const [modelTitle, setModelTitle] = useState<string>();
  //编辑/新增弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [deviceModelList,setDeviceModelList] = useState<any>([])
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<DeviceTypes.DeviceInfoOutput>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tooltip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '设备编号',
      dataIndex: 'code',

      ellipsis: true,
    },
    {
      title: '设备描述',
      dataIndex: 'describe',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      ellipsis: true,
      hideInSearch: true,
      render(dom, entity, index, action, schema) {
        return <>{deviceModelList.find((x:any)=>x.key==entity.deviceType)?.value}</>
      },
    },
    {
      title: '设备维保日期',
      dataIndex: 'repairDate',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return <>{dayjs(record.repairDate).format("YYYY-MM-DD")}</>
      }
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed:'right',
      render: (_, record) => [
        <Button
          key="edit"
          type="primary" size='small'
          onClick={async () => {
            setIsModalOpen(true);
            setModelTitle('编辑信息');
            const copyFormData = JSON.parse(JSON.stringify(record));
            copyFormData.repairDate = dayjs(record.repairDate)
            console.log('record', record);

            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          key="del"
          title="确定要删除此条数据吗？"
          onConfirm={() => {
            const EnablejsonData: DeviceTypes.DeviceInfoDelInput = {
              id: record.id,
            };
            DeviceInfoAPI.Del(EnablejsonData).then((r) => {
              if (r.statusCode === 200) {
                message.success(r.statusCode === 200 ? '删除成功' : r.message);
                actionRef.current?.reloadAndRest?.();
              }
            });
          }}
          onCancel={() => {
            message.info('已取消删除');
          }}
          okText="确认"
          cancelText="关闭"
        >
          <Button type="primary" size='small' danger >删除</Button>
        </Popconfirm>,
      ],
    },
  ];

  useEffect(()=>{
  deviceProductAPI.SelectList().then((v:MyResponse.Content)=>{
    if (v.statusCode===200) {
      setDeviceModelList(v.data)
    }
   })
  },[])

  /*
   *表单提交
   */
  const OnSubmit = async (values: DeviceTypes.DeviceInfoOutput) => {

    if (values.id) {
      const response = await DeviceInfoAPI.Update(values);
      if (response.statusCode === 200) {
        message.success('修改成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '修改失败');
      }
    } else {
      const response = await DeviceInfoAPI.Add(values);
      console.log('response', response);
      if (response.statusCode === 200) {
        message.success('添加成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '添加失败');
      }
    }
  };
  return (
    <>
      <ProTable<DeviceTypes.DeviceInfoOutput>
        key="myTable"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        bordered
        rowClassName={(record:any , index: number, indent: number)=>{
          if (index % 2 === 0) {
            return ''; // 偶数行的类名
          } else {
            return 'even-row-background'; // 奇数行的类名
          }
        }}
        request={async (params = {}) => {
          const jsonData: DeviceTypes.Page = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
            code: params.code
          };
          const response = await DeviceInfoAPI.PagedList(jsonData);
          if (response.statusCode === 200) {
            return {
              data: response.data.items,
              success: true,
              total: response.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger:false
        }}
        dateFormatter="string"
        headerTitle="设备列表"
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              typeForm.resetFields();
              setIsModalOpen(true);
              setModelTitle('新增信息');
            }}
          >
            新建设备
          </Button>,
        ]}
      />
      <Modal
        maskClosable={false}
        key="01"
        width={800}
        title={<Tag color="#cd201f">{modelTitle}</Tag>}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setIsModalOpen(false);
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="deviceInfoForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form
          form={typeForm}
          name="basic"
          id="deviceInfoForm"

          onFinish={OnSubmit}
          autoComplete="off"
        >
          <Form.Item label="id" name="id" hidden>
            <Input />
          </Form.Item>

          <Form.Item
            label="设备名称"
            name="name"
            rules={[{ required: true, message: '此项为必填项!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="设备编号" name="code" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Input />
          </Form.Item>
          <Form.Item label="设备描述" name="describe"  >
            <Input />
          </Form.Item>
          <Form.Item label="设备类型" name="deviceType" rules={[{ required: true, message: '此项为必填项!' }]} >
          <Select placeholder='请选择设备类型' style={{ width: 375 }}>
                            {
                                deviceModelList.map((item: MySelectType.Select) => {
                                    return <Select.Option value={item.key} key={item.key}>
                                        <span>{item.value}</span>
                                    </Select.Option>
                                })
                            }
                        </Select>
          </Form.Item>
          {/* name="repairDate" */}
          <Form.Item label="设备维保日期" name="repairDate" rules={[{ required: true, message: '此项为必填项!' }]} >
            <DatePicker ></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
