/* 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, Upload, UploadProps, Spin, Tag, Col, Divider, Row, Card, Space, Select } from 'antd';
import { useEffect, useRef, useState } from 'react';
import RecipeInfoAPI from '@/api/recipeService'
import MaterialsInfoAPI from '@/api/materialService'
import GroupInfoAPI from '@/api/groupService'
import { LoadingOutlined, RedoOutlined, PlusSquareOutlined, EditOutlined } from '@ant-design/icons';
import { RcFile, UploadChangeParam, UploadFile } from 'antd/es/upload';
import { history } from '@umijs/max';
import styles from './index.less'

const Index = () => {
  //表单
  const [typeForm] = Form.useForm();
  //编辑/新增弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalGroupOpen, setIsModalGroupOpen] = useState(false);
  const [spinStatus, setSpinStatus] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isModalGroupFormOpen, setIsModalGroupFormOpen] = useState(false);
  const [selectGroup, setSelectGroup] = useState(0)
  const [recipeparams, setRecipeparams] = useState<any>();
  const [GroupList, setGroupList] = useState<GroupInfoTypes.Info[]>([{
    id: '-1',
    name: '全部',
    des: '全部'
  }]);
  const [selectRowItem, setSelectRowItem] = useState<any>();
  const [materiallist, setMateriallist] = useState<RecipeMaterialTypes.Info[]>([]);
  const [selectMateriallist, setSelectMateriallist] = useState<RecipeMaterialTypes.Info[]>([]);
  const [imageUrl, setImageUrl] = useState<string>();
  const [loading, setLoading] = useState(false);
  const actionRef = useRef<ActionType>();
  const [formRef] = Form.useForm();
  const editactionformRef = useRef<EditableFormInstance>();
  const editactionRef = useRef<ActionType>();
  const [groupForm] = Form.useForm();
  const [GroupEditForm] = Form.useForm();
  //方法
  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 beforeUpload = (file: RcFile) => {
    console.log('file', file);
  }

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    setLoading(true);
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      console.log('info', info);
      // Get this url from response in real world.
      setLoading(false);
      const { statusCode, data } = info.file.response;
      if (statusCode === 200) {
        console.log('data', data);
        setImageUrl("http://162.14.105.138:8333/uploads" + data);
      }
    }
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : ''}
    </div>
  )
  //表单名
  const columns: ProColumns<RecipeTypes.Info>[] = [
    {
      title: '产品图片',
      dataIndex: 'picUrl',
      width: 200,
      align: 'center',
      hideInSearch: true,
      valueType: {
        type: 'image',
        width: 60,
      }
    },
    {
      title: '产品名称',
      width: 200,
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '当前分类',
      width: 200,
      dataIndex: 'groupId',
      hideInSearch: true,
      renderText(text, record) {
        return <>{GroupList.find(x => x.id === record.groupId)?.name}</>
      },
      align: 'center',
    },
    {
      title: '产品编码',
      dataIndex: 'code',
      align: 'center',
      width: 100,
      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,
                outlet: '',
                sort: '',
                time: '',
                wos: ''
              };
              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>

          {record.groupId ?
            <Button
              onClick={() => {
                setIsModalGroupOpen(true)
                const copyFormData = JSON.parse(JSON.stringify(record));
                groupForm.setFieldsValue(copyFormData);
              }}
              key='fl' type='primary' ghost>修改分类</Button>
            :
            <Button key='fl'
              onClick={() => {
                const copyFormData = JSON.parse(JSON.stringify(record));
                groupForm.setFieldsValue(copyFormData);
                setIsModalGroupOpen(true)
              }}
              type='primary' ghost>设置分类</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 GetGroupList = () => {
    GroupInfoAPI.List().then((res: MyResponse.Content) => {
      if (res.statusCode === 200) {
        res.data.unshift(
          {
            id: '-1',
            name: '全部',
            des: '全部'
          }
        )
        setGroupList(res.data)
      }
    })
  }
  // 更新分组
  const OnGroupSubmit = (value: any) => {
    const jsonData: RecipeTypes.RecipesGroupInput = {
      GroupId: value.groupId,
      RecipesId: value.id
    }
    RecipeInfoAPI.ChangeGroup(jsonData).then((res: MyResponse.Content) => {
      if (res.statusCode === 200) {
        message.success("设置完成");
        setIsModalGroupOpen(false);
        actionRef.current?.reload();
      } else {
        message.error("设置失败");
      }
    });
  }
  // 修改分组数据
  const OnGroupEditSubmit = (value: GroupInfoTypes.Info) => {
    if (value.id) {
      GroupInfoAPI.Update(value).then((res: MyResponse.Content) => {
        if (res.statusCode) {
          message.success("修改成功");
          setIsModalGroupFormOpen(false);
          GetGroupList();
        } else {
          message.success("修改失败");
        }
      })
    } else {
      GroupInfoAPI.Add(value).then((res: MyResponse.Content) => {
        if (res.statusCode) {
          message.success("新增成功");
          setIsModalGroupFormOpen(false);
          GetGroupList();

        } else {
          message.success("新增失败");
        }
      })
    }
    GroupEditForm.resetFields();
  }
  useEffect(() => {
    GetGroupList();
  }, [])
  useEffect(() => {
    const jsonData: RecipeTypes.Page = {
      pageIndex: 1,
      pageSize: 10,
      picUrl: '',
      id: '',
      code: '',
      groupId: GroupList[selectGroup].id === '-1' ? '' : GroupList[selectGroup].id
    };
    setRecipeparams(jsonData);
  }, [selectGroup])
  const editcolumns: ProColumns<RecipeMaterialTypes.Info>[] = [
    {
      title: '物料名称/wos',
      dataIndex: 'materialId',
      valueType: 'select',
      tooltip: 'wos为每秒出水量',
      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.MaterialsInfo) => (
            myData.push({
              label: `${item.name}-[${item.wos}${item.unit}]`,
              value: item.id,
            })
          ))
        }
        return myData;
      },
      formItemProps: (_form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },

    {
      title: '通道号',
      dataIndex: 'outlet',
      tooltip: "设备出料口编号",
      valueType: 'text',
      ellipsis: true,
      formItemProps: (_form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '重量(g)',
      dataIndex: 'time',
      valueType: 'text',
      ellipsis: true,
      formItemProps: (_form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '步骤',
      dataIndex: 'sort',
      valueType: 'text',
      tooltip: "步骤不可重复",
      ellipsis: true,
      formItemProps: (_form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
          // ,
          //  () => ({
          //   validator(_, value) {
          //     if (!materiallist[rowIndex]) {
          //       if (!materiallist.find(x => x.sort === value)) {
          //         return Promise.resolve();
          //       }
          //     } else {
          //       if (materiallist.filter(x => x.sort === value && x.id !== materiallist[rowIndex].id).length < 1) {
          //         return Promise.resolve();
          //       }
          //     }
          //     return Promise.reject(new Error('已存在步骤!'));
          //   },
          // })
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, row) => [
        <Button
          type='primary' ghost
          key="edit"
          onClick={() => {
            editactionRef.current?.startEditable(row.id);
          }}
        >
          编辑
        </Button>,
        <Button
          type='primary' ghost
          key="wl"
          onClick={() => {
            window.open(`${window.location.href.replace('recipe', 'material')}`, '_about')
          }}
        >
          去修改出水量
        </Button>
      ],
    },
  ];
  return (
    <>
      {
       /*
       * 产品配方信息
       */}
      <Row wrap={false} gutter={[10, 10]}>
        <Col flex={0.1}>
          <Card>
            <Space size="middle">
              <Button type='primary'
                onClick={() => {
                  setIsModalGroupFormOpen(true)
                  GroupEditForm.resetFields();
                }}><PlusSquareOutlined /> 新增分组</Button>
              <Button onClick={() => {
                GetGroupList()
              }}><RedoOutlined />刷新</Button>
            </Space>
            <Divider />
            <div className={styles.tag}>
              {GroupList.map((item, index) => (

                <div key={index} onClick={() => {
                  setSelectGroup(index);
                }} className={`${styles.tag_item} ${index === selectGroup ? styles.tag_item_activeItem : ''}`}>
                  <Space size="middle">
                    <div title={item.des}>{item.name}</div>
                    {

                      item.id === "-1" ? '1111111' : <div className={styles.tag_item_editicon}><EditOutlined style={{ fontSize: '20px' }} title='修改名称' onClick={(e) => {
                        e.stopPropagation();
                        const copyFormData = JSON.parse(JSON.stringify(GroupList[index]));
                        GroupEditForm.setFieldsValue(copyFormData);
                        setIsModalGroupFormOpen(true)
                      }} twoToneColor="#eb2f96"></EditOutlined></div>}
                  </Space>
                  <div className={index === selectGroup ? styles.tag_item_active : ''}></div>
                </div>
              ))}
            </div>
          </Card>
        </Col>
        <Col flex={4} >
          <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>,
            ]}
          />
        </Col>
      </Row>
      {
       /*
       * 新增产品信息
       */}
      <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="recipeForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form
          form={typeForm}
          name="basic"
          id="recipeForm"
          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="picUrl"
            rules={[

              () => ({
                validator() {
                  if (!imageUrl) {
                    return Promise.reject(new Error('此项必填!'));
                  } else {
                    return Promise.resolve();
                  }
                },
              })
              ,
            ]}
          >
            <Upload
              name='file'
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://162.14.105.138:8333/api/files/single"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
            <div>
              {uploadButton}
            </div>
          </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}
                // onChange={setMateriallist}
                recordCreatorProps={{
                  record: () => (
                    {
                      id: Date.now().toString(),
                      materialId: '',
                      recipesId: '',
                      outlet: '',
                      sort: '',
                      time: '',
                      wos: '',
                    })
                  ,
                }
                }
                editable={{
                  form: formRef,
                  type: 'single',
                  onValuesChange: (record, recordList: RecipeMaterialTypes.Info[]) => {
                    console.log(selectMateriallist);

                    recordList.map((res) => {
                      if (!res.wos) {
                        res.wos = selectMateriallist.find((x) => x.id === res.materialId)?.wos;
                      }
                    });
                    if (!recordList) {
                      record.wos = selectMateriallist.find((x) => x.id === record.materialId)?.wos;
                      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>
      {
       /*
       * 新增分类的弹框
       */}
      <Modal
        maskClosable={false}
        open={isModalGroupFormOpen}
        destroyOnClose
        title={<Tag color='#cd201f'>编辑分类</Tag>}
        onCancel={() => {
          GroupEditForm.resetFields();
          setIsModalGroupFormOpen(false)
        }}
        footer={[
          <Popconfirm
            key="del"
            title="确定要删除此条数据吗？"
            onConfirm={() => {
              console.log('sss', GroupEditForm.getFieldValue('id'));
              const delJosnData: GroupInfoTypes.Info = {
                id: GroupEditForm.getFieldValue('id'),
                name: '',
                des: ''
              };
              GroupInfoAPI.Del(delJosnData).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  message.success("删除成功!");
                  setIsModalGroupFormOpen(false);
                  GetGroupList();
                }
              })
            }}
            onCancel={() => { }}
          >
            <Button
              key="back"
            // onClick={() => {
            //   setIsModalGroupFormOpen(false)
            // }}
            >
              删除分组
            </Button>
          </Popconfirm>,
          <Button key="submit" form="groupEditForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Form
          form={GroupEditForm}
          name="basic"
          id="groupEditForm"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 12 }}
          onFinish={OnGroupEditSubmit}
          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="des"
            rules={[{ required: true, message: '此项必填！' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      {
       /*
       * 设置分类的弹框
       */}
      <Modal
        maskClosable={false} open={isModalGroupOpen}
        title={<Tag color='#cd201f'>设置分类</Tag>}
        centered
        onCancel={() => setIsModalGroupOpen(false)}
        destroyOnClose
        footer={[
          <Button
            key="back"
            onClick={() => {
              setIsModalOpen(false);
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="groupForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}
      >
        <Divider />
        <Form
          form={groupForm}
          id='groupForm'
          onFinish={OnGroupSubmit}
        >
          <Form.Item name="id" hidden >

          </Form.Item>
          <Form.Item name="groupId" rules={[{ required: true, message: '此项为必填项!' }]}>
            <Select placeholder='请选择分类'>
              {GroupList.map((item) => {
                if (item.id !== '-1') {
                  return <Select.Option value={item.id} key={item.id}>
                    <span>{item.name}</span>
                  </Select.Option>
                }


              })}
            </Select>
          </Form.Item>
        </Form>
        <Divider />
      </Modal>
    </>
  )
}

export default Index;
