/* 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, Row, Col } from 'antd';
import { useRef, useState } from 'react';
import CraftsInfoAPI from '@/api/craftsinfo'
import MaterialsInfoAPI from '@/api/materialService'
import './index.less'


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

  //表单名
  const columns: ProColumns<CraftsTypes.Info>[] = [
    {
      title: '工艺名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '工艺描述',
      dataIndex: 'description',
      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));
              typeForm.setFieldsValue(copyFormData);
            }}
          >
            编辑
          </Button>
          <Popconfirm
            key="del"
            title="确定要删除此条数据吗？"
            onConfirm={() => {
              const delData: CraftsTypes.Info = {
                id: record.id,
                name: '',
              };
              CraftsInfoAPI.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: '重量(g)',
      dataIndex: 'weight',
      valueType: 'text',
      ellipsis: true,
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    //  {
    //    title: '步骤',
    //    dataIndex: 'sort',
    //    valueType: 'text',
    //    tooltip: "步骤不可重复",
    //    ellipsis: true,
    //    formItemProps: () => {
    //      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={() => {
            console.log(row);
            editactionRef.current?.startEditable(row.id);
          }}
        >
          编辑原料
        </Button>,

      ],
    },
  ];
  return (
    <>
      {
       /*
       * 工艺信息
       */}
      <Row wrap={false} gutter={[10, 10]}>
        <Col flex={0.1}>
          <ProTable<CraftsTypes.Info>
            key={+new Date() + Math.random()}
            columns={columns}
            actionRef={actionRef}
            className='box'
            cardBordered
            dateFormatter="string"
            headerTitle='工艺列表'
            rowClassName={(_, index) => (index === rowIndex ? 'rowBgColor' : '')}
            onRow={(record, index) => {
              return {
                onClick: () => {
                  if (record.id) {
                    setRowIndex(index)
                    setStepparams({ craftId: record.id })
                    setStepTitle(`[${record.name}]步骤列表`)
                  }
                },
              };
            }}
            request={async (params = {}) => {


              const jsonData: CraftsTypes.Page = {
                pageIndex: params.current || 1,
                pageSize: params.pageSize || 10,
                name: params.name || '',
                deviceType: 1,
              };
              const response = await CraftsInfoAPI.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
            }}

            toolBarRender={() => [
              <Button
                key="button"
                type="primary"
                onClick={() => {
                  typeForm.resetFields();
                  setIsModalOpen(true);
                }}
              >
                添加工艺
              </Button>,
            ]}
          />
        </Col>
        <Col flex={4} >
          <ProTable<CraftsTypes.Info>
            key={+new Date() + Math.random()}

            columns={
              [
                {
                  title: '步骤',
                  dataIndex: 'step',
                  align: 'center',
                  hideInSearch: true
                },
                {
                  title: '步骤名称',
                  dataIndex: 'name',
                  align: 'center',
                  hideInSearch: true
                },
                {
                  title: '功能参数',
                  dataIndex: 'value',
                  align: 'center',
                  hideInSearch: true
                },
                {
                  title: '物料信息',
                  dataIndex: 'materials',
                  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));
                          typeForm.setFieldsValue(copyFormData);
                        }}
                      >
                        编辑
                      </Button>
                      <Popconfirm
                        key="del"
                        title="确定要删除此条数据吗？"
                        onConfirm={() => {
                          const delData: CraftsTypes.Info = {
                            id: record.id,
                            name: '',
                            deviceType: 0,
                            description: ''
                          };
                          CraftsInfoAPI.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>
                  ],
                },
              ]
            }
            actionRef={actionRef}
            cardBordered
            params={stepparams}
            request={async (params = {}) => {
              const jsonData: CraftsTypes.Pztj_CraftStepsPageInput = {
                pageIndex: params.current || 1,
                pageSize: params.pageSize || 10,
                craftId: params.craftId,
              };
              const response = await CraftsInfoAPI.craftsStepPage(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={stepTitle}
            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="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 = '';
          })
          //    CraftsInfoAPI.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;
