/**
 * 物料基础信息管理
 * @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, Select } from 'antd';
import { useEffect, useRef, useState } from 'react';
import MaterialsInfoAPI from '@/api/materialService'
import { dictDataApi } from '@/api/dictType/service';
const Index = () => {
  //表单
  const [typeForm] = Form.useForm();
  const [materiaType, setMateriaType] = useState<any[]>([]);
  //编辑/新增弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalText, setModalText] = useState<string>('新增信息');
  const actionRef = useRef<ActionType>();


  const GetMaterialType = () => {
    const jsonData: dictData.queryParms = {
      typeCode: 'wllx'
    }
    dictDataApi.List(jsonData).then((res: MyResponse.Content) => {
      if (res.statusCode === 200) {
        setMateriaType(res.data)
      }
    })
  }
  //方法
  const OnSubmit = async (values: MaterialsTypes.Info) => {
    if (values.id) {

      const response = await MaterialsInfoAPI.Update(values);
      if (response.statusCode === 200) {
        message.success('修改成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(response.errors || '修改失败');
      }
    } else {
      const response = await MaterialsInfoAPI.Add(values);
      if (response.statusCode === 200) {
        message.success('添加成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(response.errors || '添加失败');
      }
    }
  }
  useEffect(() => {
    GetMaterialType();
  }, [])
  //表单名
  const columns: ProColumns<MaterialsTypes.Info>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tooltip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '物料名称',
      dataIndex: 'name',
    },
    {
      title: '物料编码',
      dataIndex: 'code',
    },
    {
      title: '物料单位',
      dataIndex: 'unit',
      hideInSearch: true
    },
    {
      title: '物料类型',
      dataIndex: 'type',
      hideInSearch: true,
      render(dom, entity, index, action, schema) {
        return <>{materiaType.find(x => x.id == entity.type)?.value}</>
      },
    },
    {
      title: '每升重量(g)',
      dataIndex: 'weightPerLiter',
      hideInSearch: true,
      tooltip: "每一升物料的重量,用于计算使用多少个桶"
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed:'right',
      render: (_, record) => [
        <Button
          key="edit"
          type="primary"
          size='small'
          onClick={async () => {
            GetMaterialType();
            setIsModalOpen(true)
            setModalText('编辑信息');
            const copyFormData = JSON.parse(JSON.stringify(record));
            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          key="del"
          title="确定要删除此条数据吗？"
          onConfirm={() => {
            const delData: MaterialsTypes.MaterialsInfoDelInput = {
              id: record.id,

            };
            MaterialsInfoAPI.Del(delData).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" size='small' danger >删除</Button>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <>
      <ProTable<MaterialsTypes.Info>
        key="myTable"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        bordered
        scroll={{ x: true }}
        rowClassName={(record: any, index: number, indent: number) => {
          if (index % 2 === 0) {
            return ''; // 偶数行的类名
          } else {
            return 'even-row-background'; // 奇数行的类名
          }
        }}
        request={async (params = {}) => {
          const jsonData: MaterialsTypes.Page = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
            code: params.code,
          };
          const response = await MaterialsInfoAPI.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);
              GetMaterialType();
              setModalText('新增信息');

            }}
          >
            添加物料
          </Button>,
        ]}
      />
      <Modal
        maskClosable={false}
        key="01"
        width={800}
        title={<Tag color="#cd201f">{modalText}</Tag>}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setIsModalOpen(false);
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="materialsForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form
          form={typeForm}
          labelAlign='right'
          name="basic"
          id="materialsForm"
          labelCol={{ 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="unit"
            rules={[{ required: true, message: '此项必填！' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="物料类型"
            name="type"
            rules={[{ required: true, message: '此项必填！' }]}
          >

            <Select>
              {materiaType.map((item, index) => {
                return <Select.Option value={item.id} key={item.id}>
                  <span>{item.value}</span>
                </Select.Option>
              })}
            </Select>
          </Form.Item>
          <Form.Item
            tooltip="每一升物料的重量,用于计算使用多少个桶"
            label="每升重量(g)"
            name="weightPerLiter"
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
export default Index
