import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  ProColumns,
  ProForm,
  ProFormInstance,
} from '@ant-design/pro-components';
import {
  ProCard,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Form, Input, message, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
import { useState, useRef } from 'react';
//引入接口
import { dictTypeApi, dictDataApi } from '@/api/dictType/service'
import { set } from 'lodash';

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

  const [selectDataRow, setSelectDataRow] = useState<dictType.output>()
  const actionRef1 = useRef<ActionType>();
  // 编辑子项
  const [modelTitle, setModelTitle] = useState<string>();
  const [dataSource, setdataSource] = useState([])
  // 设置子项的弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);

  // // 拿到当前子项id
  const [thisitem, setthisitem] = useState<any>();
  ;

  // 设置新增子项的弹窗
  const [isitemModalOpen, setisitemModalOpen] = useState(false);
  // 新增子项的表单
  const [typeForm] = Form.useForm();

  const Reolod = () => {
    ref.current?.resetFields()
    actionRef.current?.reload()

  }
  const columns: ProColumns<dictType.output>[] = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInTable: true,
      hideInForm: true,
      search: false,
    },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '编码',
      hideInDescriptions: true,
      dataIndex: 'code',
      copyable: true,

    },
    {
      title: '排序',
      dataIndex: 'sort',
      ellipsis: true,
      hideInTable: true,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      fixed:'right',
      render: (text, row) => [
        <Space key={+new Date() + Math.random()}>
          <a onClick={() => {
            setSelectDataRow(row)
            setFromType('form')
            ref.current?.setFieldsValue(row)
          }} key={+new Date() + Math.random()} target="_blank" rel="noopener noreferrer">

            编辑
          </a>
          <a onClick={async () => {

            // row就是当前点击的id
            setthisitem(row);

            // console.log(row);
            // const ee = setthisitem(row)

            //  setFromType('form')
            // ref.current?.setFieldsValue(row)

            const jsonData: dictData.queryPage = {
              pageIndex: 1,
              pageSize: 10,
              name: '',
              typeId: row.id

              // code:params.code||''
            };
            console.log(row.id);

            const response = await dictDataApi.PagedList(jsonData);

            if (response.statusCode === 200) {
              // console.log(response);

              setdataSource(response.data.items);
            } else {
              return {
                data: [],
                success: false,
                total: 0,
              };
            }

            setIsModalOpen(true)
            actionRef1.current?.reload()

          }} key={+new Date() + Math.random()} target="_blank" rel="noopener noreferrer">
            设置子项
          </a>
          <Popconfirm
            key="del"
            title="确定要删除此条数据吗？"
            onConfirm={() => {

              dictTypeApi.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>
      ],
    },
  ];
  // 子项列表
  const subitem = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInTable: true,
      hideInForm: true,
      search: true,
    },
    {
      title: '外键id',
      dataIndex: 'typeId',
      ellipsis: true,
      hindeInForm: true,
      search: false,
      hideInTable: true,
    },
    {
      title: '编码',
      hideInDescriptions: true,
      dataIndex: 'code',
      copyable: true,


    },
    {
      title: '状态',
      hideInDescriptions: true,
      dataIndex: 'value',
      // copyable: true,
      search: false,

    },
    {
      title: '排序',
      dataIndex: 'sort',
      ellipsis: true,
      // hideInTable: true,
      search: false,

    },
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'id',
      render: (text: any, record: { id: any; }) => (
        <>
          <Button key="edit"
            type="primary" ghost
            className='btn1' onClick={() => {

              setModelTitle('编辑子项');
              const copyFormData = JSON.parse(JSON.stringify(record));
              console.log(copyFormData);

              copyFormData.state = copyFormData.state === '0';
              typeForm.setFieldsValue(copyFormData);
              setisitemModalOpen(true)
            }} >编辑</Button>
          <Popconfirm
            key="del"
            title="确定要删除此条数据吗？"
            onConfirm={() => {

              const EnablejsonData: dictData.delInput = {
                id: record.id,
              };

              dictDataApi.Del(EnablejsonData).then((r: MyResponse.Content) => {
                if (r.statusCode === 200) {
                  message.success(r.statusCode === 200 ? '删除成功' : r.message);
                  // 重新加载页面
                  actionRef1.current?.reload()
                }
              });
            }}
            onCancel={() => {
              message.info('已取消删除');
            }}
            okText="确认"
            cancelText="关闭"
          >
            <Button type="primary" danger ghost className='btn3'>删除</Button>

          </Popconfirm >

        </>
      )
    },
  ];

  //  提交
  const OnSubmit = async (values: dictData.updateInput) => {

    if (values.id) {
      const response = await dictDataApi.Update(values);
      if (response.statusCode === 200) {

        message.success('修改成功');
        // 重新加载页面
        actionRef1.current?.reload();

        setisitemModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '修改失败');
      }
    } else {
      const response = await dictDataApi.Add(values);
      // 重新加载页面

      actionRef1.current?.reload();
      console.log('response', response);
      if (response.statusCode === 200) {

        //  重新加载

        actionRef1.current?.reload();
        message.success('添加成功');

        // actionR.current?.reload();
        setisitemModalOpen(false);

      } else {
        message.error(JSON.stringify(response.errors) || '添加失败');
      }
    }
  };


  return (
    <>
        <ProTable<dictType.output>
          columns={columns}
          cardBordered
                bordered
                scroll={{ x: true }}
                rowClassName={(record: any, index: number, indent: number) => {
                    if (index % 2 === 0) {
                        return ''; // 偶数行的类名
                    } else {
                        return 'even-row-background'; // 奇数行的类名
                    }
                }}
          type={fromType as 'table'}
          formRef={ref}
          actionRef={actionRef}
          form={{
            ignoreRules: true,// 自定义提交按钮的属性
            submitter: {
              onReset: () => {
                ref.current?.resetFields()
                setFromType("table")
              },
              searchConfig: { resetText: fromType === 'form' ? '返回' : '重置', submitText: fromType === 'form' ? '提交' : '查询' },
            }
          }}
          onSubmit={(params: any) => {
            console.log(params);
            params.id = selectDataRow?.id
            if (fromType === 'form') {
              if (params.id) {
                dictTypeApi.Update(params).then((res: MyResponse.Content) => {
                  if (res.statusCode === 200) {
                    message.info("更新成功!");
                    setFromType('table')
                    Reolod()
                  } else {
                    message.error(res.errors);
                  }
                })
              } else {
                dictTypeApi.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: dictType.queryPage = {
              pageIndex: params.current || 1,
              pageSize: params.pageSize || 10,
              name: params.name || '',
              code: params.code || ''
            };
            const response = await dictTypeApi.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');
              setSelectDataRow(undefined)
            }}>
              <PlusOutlined />
              新建
            </Button>,
          ]}
        />
      <Modal
        maskClosable={false} title="设置子项" open={isModalOpen} footer={false} onCancel={() => {

          setIsModalOpen(false);

        }} width={1000}

      >

        <ProTable
          search={false}

          dataSource={dataSource}
          actionRef={actionRef1}
          request={async (params = {}) => {
            const jsonData: dictData.queryPage = {
              pageIndex: params.current || 1,
              pageSize: params.pageSize || 10,
              name: params.name || '',
              typeId: thisitem.id,

              // code:params.code||''
            };
            const res = await dictDataApi.PagedList(jsonData);
            console.log(res);

            if (res.statusCode === 200) {
              setdataSource(res.data.items);

            }

            return {
              data: res.data.items,
              success: true,
              total: res.data.total,
            };
          }}
          onChange={(pagination) => {
            console.log(pagination);


          }}
          pagination={{
            pageSize: 5,
            showSizeChanger:false
          }}
          rowKey="id"
          dateFormatter="string"
          headerTitle="子项列表"
          columns={subitem}

          toolBarRender={() => [
            <Button
              key="button"
              type="primary"
              onClick={() => {


                typeForm.resetFields();
                setisitemModalOpen(true)

                setModelTitle('新增子项');
                typeForm.setFieldsValue({ "typeId": thisitem.id });




              }}

            >
              新增子项
            </Button>,
          ]}
        />
      </Modal>

      <Modal
        maskClosable={false}
        // eslint-disable-next-line react/jsx-no-duplicate-props
        title={<Tag color="#cd201f">{modelTitle}</Tag>}
        // destroyOnClose={true}
        open={isitemModalOpen} onCancel={() => {
          setisitemModalOpen(false)


        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setisitemModalOpen(false);

            }}
          >
            返回
          </Button>,
          <Button key="submit" form="itemForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form
          form={typeForm}
          name="basic"
          id="itemForm"
          // initialValues={{ "typeId": thisitem.id }}

          // lCol={{ span: 4 }}
          wrapperCol={{ span: 12 }}
          onFinish={OnSubmit}
          autoComplete="off"
        >
          <Form.Item label="id" name="id" hidden>
            <Input />
          </Form.Item>

          <Form.Item
            label="外键id"
            name="typeId"
            hidden
          // rules={[{ required: true, message: '此项为必填项!' }]}
          // hidden
          >
            <Input />
          </Form.Item>
          <Form.Item label="名称" name="value" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Input />
          </Form.Item>
          <Form.Item label="编码" name="code" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Input />
          </Form.Item>
          <Form.Item label="排序" name="sort" rules={[{ required: true, message: '此项为必填项!' }]}>
            <Input />
          </Form.Item>

        </Form>
      </Modal>

      {/* <ProForm>

      </ProForm> */}
    </>
  );
};



