// 桶管理
import './index.less'
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Tag, QRCode, Table } from 'antd';
import { useRef, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import BucketInfoAPI from '@/api/Bucket';
import { multiply } from 'lodash';


const bucket = () => {
  //表单
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [typeForm] = Form.useForm();
  //  下拉列表
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [modelTitle, setModelTitle] = useState<string>();
  //编辑/新增弹窗
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [isModalOpen, setIsModalOpen] = useState(false);
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const actionRef = useRef<ActionType>();
  // 二维码下载弹窗
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [isopenshow, setopenshow] = useState(false);
  // 下载回显的数据
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [information, setinformation] = useState<BucketTypes.Info>({
    id: '',
    name: '',
    code: '',
  });

  // 桶记录弹窗

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [isrecord, setrecord] = useState(false)




  const columns: ProColumns<BucketTypes.Info>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,

    },
    {
      title: '桶名称',
      dataIndex: 'name',
      ellipsis: true,
      align: 'center',
    },

    {
      title: '桶编号',
      dataIndex: 'code',
      hideInSearch: true,
      ellipsis: true,
      align: 'center',
    },
    {
      title: '当前原料',
      dataIndex: 'materialName',
      ellipsis: true,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '桶二维码',
      dataIndex: 'type',
      align: 'center',
      ellipsis: true,
      hideInSearch: true,
      width: 160,
      render: (_, record) => {
        return (
          <div className='qrcodebox'>
            <div id="myqrcode" >
              <QRCode size={120} bordered={false} value={record.code} />
            </div>
            {/* 下载二维码点击事件 */}
            <a onClick={() => {
              const canvas = document.getElementById('myqrcode')?.querySelector<HTMLCanvasElement>('canvas');
              if (canvas) {
                const url = canvas.toDataURL();
                const a = document.createElement('a');
                a.download = 'QRCode.png';
                a.href = url;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
              }
            }}>下载</a>
          </div>
        )
      }

    },
    {
      title: '桶类型',
      dataIndex: 'lx',
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '桶容积',
      dataIndex: 'rj',
      align: 'center',
      ellipsis: true,
      hideInSearch: true,

    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 220,

      render: (_, record) => [


        <Button
          key="edit"
          type="primary" ghost
          className='btn1'
          onClick={async () => {
            setIsModalOpen(true);
            setModelTitle('编辑信息');
            const copyFormData = JSON.parse(JSON.stringify(record));
            console.log(copyFormData);

            copyFormData.state = copyFormData.state === '0';
            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑
        </Button>,

        // <Button
        //   key="xz"
        //   type="primary" ghost
        //   onClick={async () => {
        //     setopenshow(true);
        //     setinformation(record)
        //   }}
        // >
        //   下载
        // </Button>,

        <Button
          key="jl"
          type="primary" ghost
          className='btn2'
          onClick={async () => {
            setrecord(true)
            setinformation(record);
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            await chart(record);
          }}
        >
          记录
        </Button>,

        <Popconfirm
          key="del"
          title="确定要删除此条数据吗？"
          onConfirm={() => {

            const EnablejsonData: BucketTypes.Info = {
              id: record.id,
              name: '',
              code: '',

            };

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

        </Popconfirm >


      ],
    },
  ];


  // 定义桶记录里面的列表
  const data: ColumnsType<BucketTypes.Info> = [
    {
      title: '',
      dataIndex: 'id',
      render: () => null,


    },
    {
      title: '工单ID',
      dataIndex: 'code',
      // key: 'code22',
      align: 'center'
    },
    {
      title: '工单名称',
      dataIndex: 'name',
      // key: 'age',
      align: 'center',

      ellipsis: true,
    },

    {
      title: '原料',
      dataIndex: 'materialName',
      // key: 'age1',
      align: 'center'
    },
    {
      title: '原料重量',
      dataIndex: 'age2',
      // key: 'age2',
      align: 'center'
    },
    {
      title: '时间',
      dataIndex: 'createTime',
      // key: 'age3',
      align: 'center'
    },


  ];

  // eslint-disable-next-line react-hooks/rules-of-hooks
  // const [aaadata, setaaadata] = useState()

  // 桶记录内的列表状态
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [condition, setcondition] = useState()

  // 定义一个桶函数
  const chart = async (record: any) => {
    //  自定义属性
    const chartcheet: BucketTypes.BucketMaterialsRecordQueryPageInput = {
      pageIndex: 1,
      pageSize: 10,
      bucketId: record.id,
      // name: '',
      // id: '',
      // code: ''
    };


    try {
      // 调用接口
      const response = await BucketInfoAPI.materialtrecored(chartcheet);
      // 如果调用成功
      if (response.statusCode === 200) {
        console.log(response);
        // 将数据更新到列表最新状态
        setcondition(response.data.items);

      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }

  }

  //  表单提交
  const OnSubmit = async (values: BucketTypes.Info) => {

    if (values.id) {
      const response = await BucketInfoAPI.Update(values);
      if (response.statusCode === 200) {
        message.success('修改成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(JSON.stringify(response.errors) || '修改失败');
      }
    } else {
      const response = await BucketInfoAPI.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<BucketTypes.Info>
        key="myTable"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params = {}) => {
          const jsonData: BucketTypes.Page = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
            id: '',
            code: '',

          };
          const response = await BucketInfoAPI.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="bucketForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form
          form={typeForm}
          name="basic"
          id="bucketForm"

          // lCol={{ span: 4 }}
          wrapperCol={{ span: 12 }}
          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="code2" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Input />
          </Form.Item>

          <Form.Item label="桶二维码" name="des"  >
            <Input />
          </Form.Item> */}

          <Form.Item label="桶类型" name="lx" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Input />
          </Form.Item>
          <Form.Item label="桶容积" name="rj" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Input />
          </Form.Item>

        </Form>
      </Modal>

      {/* 下载二维码 */}
      <Modal
        maskClosable={false}
        key="xzModal"
        width={400}
        title={<Tag color="#cd201f">二维码</Tag>}
        open={isopenshow}


        onCancel={() => {
          setopenshow(false);

        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setopenshow(false);
            }}
          >
            返回
          </Button>,

        ]}
      >
        <div className='container'>
          <div className='left'>
            <div >桶编号 : {information?.code}</div>
            <div >桶名称 : {information?.name}</div>
            <div >当前原料 : </div>
          </div>
          <div className='right'>
            <div id="myqrcode" >
              <QRCode value={information?.code} style={{ border: 'none' }} />

            </div>
          </div>
        </div>

      </Modal>
      {/* 桶记录 */}
      <Modal
        maskClosable={false}
        key="tjl01"
        width={800}
        title={<Tag color="#cd201f">桶记录</Tag>}
        open={isrecord}
        onCancel={() => {
          setrecord(false)
        }}

        footer={[
          <Button
            key="back"
            onClick={() => {
              setrecord(false)

            }}
          >
            返回
          </Button>,

        ]}
      >
        <div>
          <div>桶编号 :  {information?.code} </div>
          <div>桶名称 :{information?.name} </div>
          <Table columns={data} dataSource={condition} />
        </div>

      </Modal>

    </>
  );
};

export default bucket;
