/* eslint-disable array-callback-return */
/**
 * 配方信息管理
 * @param Page
 * @returns
 */
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Spin, Tag, Space } from 'antd';
import { useRef, useState } from 'react';
import RecipeInfoAPI from '@/api/recipeService'
import MaterialsInfoAPI from '@/api/materialService'


const Index = () => {
  //表单
  const [typeForm] = Form.useForm();
  //编辑/新增弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [spinStatus, setSpinStatus] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [recipeparams, setRecipeparams] = useState<any>();
  const [selectRowItem, setSelectRowItem] = useState<any>();
  const [materiallist, setMateriallist] = useState<RecipeMaterialTypes.Info[]>([]);
  const [selectMateriallist, setSelectMateriallist] = useState<RecipeMaterialTypes.Info[]>([]);
  const [imageUrl, setImageUrl] = useState<string>();
  const actionRef = useRef<ActionType>();
  const [formRef] = Form.useForm();
  const editactionformRef = useRef<EditableFormInstance>();
  const editactionRef = useRef<ActionType>();
  //方法
  const OnSubmit = async (values: RecipeTypes.Info) => {
    values.picUrl = imageUrl!;
    if (values.id) {
      const response = await RecipeInfoAPI.Update(values);
      if (response.statusCode === 200) {
        message.success('修改成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(response.errors || '修改失败');
      }
    } else {
      const response = await RecipeInfoAPI.Add(values);
      if (response.statusCode === 200) {
        message.success('添加成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(response.errors || '添加失败');
      }
    }
  }

  //表单名
  const columns: ProColumns<RecipeTypes.Info>[] = [
    {
      title: '配方名称',

      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '配方编码',
      dataIndex: 'code',
      align: 'center',

      hideInSearch: true
    },
    {
      title: '操作',
      align: 'center',

      valueType: 'option',

      key: 'option',
      render: (_, record) => [
        <Space key='nm' size="middle">
          <Button
            key="edit"
            type='primary' ghost
            onClick={async () => {
              setIsModalOpen(true)
              const copyFormData = JSON.parse(JSON.stringify(record));
              setImageUrl(copyFormData.picUrl)
              typeForm.setFieldsValue(copyFormData);
            }}
          >
            编辑
          </Button>
          <Button
            key="site"
            type='primary' ghost
            onClick={async () => {
              setIsEditModalOpen(true)
              setSpinStatus(true);
              const jsonData: RecipeMaterialTypes.Info = {
                id: '',
                materialId: '',
                recipesId: record.id,
                weight: '',
              };
              setSelectRowItem(record);
              //根据工艺列表查询功能值
              RecipeInfoAPI.MaterialList(jsonData)
                .then((res: MyResponse.Content) => {
                  if (res.statusCode === 200) {
                    setMateriallist(res.data)
                    setIsEditModalOpen(true)
                  }
                  setSpinStatus(false)
                })
                .catch(() => {
                  setIsEditModalOpen(false)
                  setSpinStatus(false)
                });
            }} >
            配置物料
          </Button>
          <Popconfirm
            key="del"
            title="确定要删除此条数据吗？"
            onConfirm={() => {
              const delData: RecipeTypes.Info = {
                id: record.id,
                name: '',
                code: '',
                picUrl: '',
                groupId: ''
              };
              RecipeInfoAPI.Del(delData).then((r) => {
                if (r.statusCode === 200) {
                  message.success(r.statusCode === 200 ? '删除成功' : r.message);
                  actionRef.current?.reload();
                }
              });
            }}
            onCancel={() => {
              message.info('已取消删除');
            }}
            okText="确认"
            cancelText="关闭"
          >
            <Button type='primary' danger ghost>删除</Button>
          </Popconfirm>
        </Space>
      ],
    },
  ];
  const editcolumns: ProColumns<RecipeMaterialTypes.Info>[] = [
    {
      title: '物料名称',
      dataIndex: 'materialId',
      valueType: 'select',
      ellipsis: true,
      request: async () => {
        const res: MyResponse.Content = await MaterialsInfoAPI.List();
        const myData: any[] = [];
        if (res.statusCode === 200) {
          setSelectMateriallist(res.data)
          res.data.map((item: MaterialsTypes.Info) => (
            myData.push({
              label: `${item.name}[${item.unit}]`,
              value: item.id,
            })
          ))
        }
        return myData;
      },
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title: '重量',
      dataIndex: 'weight',
      valueType: 'text',
      ellipsis: true,
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '重量误差(±)',
      dataIndex: 'errorWeight',
      valueType: 'text',
      ellipsis: true,
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, row) => [
        <Button
          type='primary' ghost
          key="edit"
          onClick={() => {
            console.log(row);
            editactionRef.current?.startEditable(row.id);
          }}
        >
          编辑原料
        </Button>,

      ],
    },
  ];
  return (
    <>
      {
       /*
       * 配方配方信息
       */}

      <ProTable<RecipeTypes.Info>
        key="myTable"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        params={recipeparams}
        request={async (params = {}) => {
          console.log('params', params);

          const jsonData: RecipeTypes.Page = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
            id: params.id,
            code: params.code,
            picUrl: '',
            groupId: params.groupId
          };
          const response = await RecipeInfoAPI.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);
            }}
          >
            添加配方配方
          </Button>,
        ]}
      />
      {
       /*
       * 新增配方信息
       */}
      <Modal
        maskClosable={false}
        key="01"
        width={800}
        title={<Tag color="#cd201f">新增信息</Tag>}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        footer={[
          <Button
            key="back"
            onClick={() => {
              setIsModalOpen(false);
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="myForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form
          form={typeForm}
          name="basic"
          id="myForm"
          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>
      </Modal>
      {
       /*
       * 配置物料与工艺的弹框
       */}
      <Modal
        maskClosable={false}
        key="02"
        width={1200}
        title="配置物料"
        open={isEditModalOpen}
        destroyOnClose
        onCancel={() => {
          setIsEditModalOpen(false);
          setMateriallist([]);
        }}
        onOk={() => {
          const list: RecipeMaterialTypes.Info[] = JSON.parse(JSON.stringify(materiallist));
          list.map((item) => {
            item.recipesId = selectRowItem.id;
            item.id = '';
          })
          RecipeInfoAPI.BatchAdd(list).then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
              message.success("保存成功!");
              setIsEditModalOpen(false);
            } else {
              message.error("保存失败!");
            }
          });
        }}
      >
        <Spin spinning={spinStatus}>
          <ProCard>
            <div
              style={{
                maxWidth: 1200,
                margin: 'auto',
              }}
            >
              <EditableProTable<RecipeMaterialTypes.Info>
                rowKey="id"
                controlled
                editableFormRef={editactionformRef}
                actionRef={editactionRef}
                columns={editcolumns}
                value={materiallist}

                recordCreatorProps={{
                  record: () => (
                    {
                      id: Date.now().toString(),
                      materialId: '',
                      recipesId: '',
                      weight: '',
                    })
                  ,
                }
                }
                editable={{
                  form: formRef,
                  type: 'single',
                  onValuesChange: (record, recordList: RecipeMaterialTypes.Info[]) => {
                    console.log(selectMateriallist);
                    if (!recordList) {
                      materiallist.push(record);
                      setMateriallist(materiallist);
                    } else {
                      setMateriallist(recordList);
                    }
                    console.log('materiallist', materiallist);

                  },
                  actionRender: (row, _, dom) => {
                    return [dom.delete, dom.save, dom.cancel];
                  },
                }}
              />
            </div>
          </ProCard>
        </Spin>

      </Modal>
    </>
  )
}

export default Index;
