/* eslint-disable array-callback-return */
/**
 * 工艺信息管理
 * @param Page
 * @returns
 */
import { ActionType, BetaSchemaForm, DragSortTable, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Spin, Tag, Space, Select, Card, Col, Row } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { v4 as uuid } from 'uuid'
import CraftsInfoAPI from '@/api/craftsinfo'
import DeviceInfoAPI from '@/api/DeviceInfo'
import DeviceProductAPI from '@/api/deviceInfo/services/deviceProduct';
import DeviceProductFunctionAPI from '@/api/deviceInfo/services/deviceProductFunction';
import MaterialAPI from '@/api/materialService';
import './index.less'

interface paramsType {
  paramType: string | number,
  paramName: string;
  paramUnit: string;
  paramCode: string;
}

const Index = () => {
  //表单
  const [typeForm] = Form.useForm();
  //编辑/新增弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [spinStatus, setSpinStatus] = useState(false);
  const [isSchemaModalOpen, setIsSchemaModalOpen] = useState(false);
  const [isSetpModalOpen, setIsSetpModalOpen] = useState(false);
  const [devices, setDevices] = useState<any>([]);
  const [deviceProducts, setDevicesProducts] = useState<any>([]);
  const [stepparams, setStepparams] = useState<any>();
  const [materialList, setMaterialList] = useState<any>();


  const [stepTitle, setStepTitle] = useState<any>('步骤列表');
  const [rowIndex, setRowIndex] = useState<any>();
  const [selectRowItem, setSelectRowItem] = useState<CraftsTypes.craftsInfoOutput>();
  const [deviceFun, setDeviceFun] = useState<deviceProductFunction.output[]>([]);

  const [deviceParm, setDeviceParm] = useState<any>([]);


  const actionRef = useRef<ActionType>();
  const [formRef] = Form.useForm();
  const [dongtaiformRef] = Form.useForm();
  const sortActionRef = useRef<ActionType>();
  const editactionRef = useRef<ActionType>();


  useEffect(() => {
    DeviceInfoAPI.selectlist().then((res: MyResponse.Content) => {
      // 设备的数组
      if (res.statusCode === 200) {
        setDevices(res.data)
      }
    })

    DeviceProductAPI.SelectList().then((res: MyResponse.Content) => {
      if (res.statusCode === 200) {
        setDevicesProducts(res.data)
      }
    })
    MaterialAPI.selectlist().then((res: MyResponse.Content) => {
      if (res.statusCode === 200) {
        const data: any[] = res.data;
        data.map((item) => (
          item.label = item.value,
          item.value = item.key
        ))
        setMaterialList(res.data)
      }
    })
  }, [])
  useEffect(() => {




  }, [deviceParm])

  //表单名
  const columns: ProColumns<CraftsTypes.Info>[] = [
    {
      dataIndex: 'id',
      align: 'center',
      hideInTable: true,
      hideInForm: true,
      readonly: true,
      search: false,
    },
    {
      title: '设备产品',
      dataIndex: 'deviceProductId',
      align: 'center',
      valueType: 'select',
      request: async () => {
        const data: MyResponse.Content = await DeviceProductAPI.SelectList()
        const chan: any[] = data.data;
        chan.map((item) => (
          item.label = item.value,
          item.value = item.key
        ))
        return chan;
      },
    },
    {
      title: '工艺名称',
      dataIndex: 'name',
      align: 'center',
      search: false
    },
    {
      title: '工艺描述',
      dataIndex: 'description',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      render: (_, record) => [
        <Button
          key={uuid()}
          type='primary' ghost
          onClick={async () => {
            setIsModalOpen(true)
            console.log('record', record);

            const copyFormData = JSON.parse(JSON.stringify(record));
            setSelectRowItem(record)
            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          key='craftinfoDel'
          title="确定要删除此条数据吗？"
          onConfirm={() => {
            const delData: CraftsTypes.Info = {
              id: record.id,
              step: 0,
              craftId: '',
              deviceProductId: ''
            };
            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>
      ],
    },
  ];
  return (
    <>
      {
        /*
        * 工艺信息
        */}
      <Row wrap={false} gutter={[10, 10]}>
        <Col flex={0.1}  >
          <ProTable<CraftsTypes.Info>
            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)
                    setSelectRowItem(record)
                    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: 0,
              };
              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={uuid()}
                type="primary"
                onClick={() => {
                  typeForm.resetFields();
                  setIsModalOpen(true);
                  setSelectRowItem({
                    id: '',
                    name: '',
                    step: 0,
                    craftId: '',
                    deviceType: 0
                  })
                }}
              >
                添加工艺
              </Button>,
            ]}
          />
        </Col>
        <Col flex={4} >
          <DragSortTable<CraftsTypes.Info>
            toolBarRender={() => [
              <Button
                key={uuid()}
                type="primary"
                onClick={() => {
                  typeForm.resetFields();
                  setIsSetpModalOpen(true);
                }}
              >
                添加步骤
              </Button>,
            ]}
            actionRef={sortActionRef}
            headerTitle={stepTitle}
            columns={[
              {
                title: '步骤',
                dataIndex: 'step',
                align: 'center',
                hideInSearch: true,
                render: (dom, rowData, index) => {
                  return (
                    <span className="customRender">{`${index + 1}`}</span>
                  );
                },
              },
              {
                title: '步骤描述',
                dataIndex: 'description',
                align: 'center',
                hideInSearch: true
              },
              {
                title: '功能',
                dataIndex: 'deviceProductFunctionName',
                align: 'center',
                hideInSearch: true,
              },
              {
                title: '操作',
                align: 'center',

                valueType: 'option',

                key: 'option',
                render: (_, record, index, action) => [
                  <Space key={uuid()} size="middle">
                    <Button
                      key={uuid()}
                      type='primary' ghost
                      onClick={async () => {
                        // setIsModalOpen(true)
                        const copyFormData = JSON.parse(JSON.stringify(record));
                        console.log('copyFormData', copyFormData);

                        typeForm.setFieldsValue(copyFormData);
                        setIsSetpModalOpen(true);
                      }}
                    >
                      编辑
                    </Button>
                    <Button
                      key={uuid()}
                      type='primary' ghost
                      onClick={async () => {
                        setIsSchemaModalOpen(true)
                        setDeviceParm([]);
                        setSpinStatus(true)
                        const copyFormData = JSON.parse(JSON.stringify(record));
                        formRef.setFieldsValue(copyFormData);
                        console.log('record', record);

                        const jsonData: deviceProductFunction.queryParms = {
                          deviceProductId: selectRowItem?.deviceProductId
                        };
                        DeviceProductFunctionAPI.List(jsonData).then((res: MyResponse.Content) => {
                          if (res.succeeded) {
                            setDeviceFun(res.data);
                            setTimeout(() => {
                              const out = res.data.find(x => x.id === record.deviceProductFunctionId);
                              if (out?.params) {
                                const b = JSON.parse(out?.params);
                                console.log(b);
                                const c: any[] = [];
                                b.map((paramsItem: paramsType) => {
                                  const element = {
                                    title: paramsItem.paramName,
                                    dataIndex: paramsItem.paramCode,
                                    width: 'md',
                                    renderFormItem: (dom, rowData, index) => {
                                      return (
                                        paramsItem.paramType
                                          === 1 ? <Select mode='multiple' options={materialList}></Select> : <Input addonAfter={paramsItem.paramUnit} />
                                      );
                                    },
                                    colProps: {
                                      xs: 24,
                                      md: 12,
                                    },
                                  }
                                  c.push(element)
                                })
                                setDeviceParm(c);
                              }
                              if (dongtaiformRef) {
                                const element = JSON.parse(record.params!)
                                dongtaiformRef.setFieldsValue(element)
                              }
                              setSpinStatus(false)
                            }, 200);
                          }
                        })
                      }}
                    >
                      配置设备参数
                    </Button>
                    <Popconfirm
                      key={uuid()}
                      title="确定要删除此条数据吗？"
                      onConfirm={() => {
                        const delData: CraftsTypes.Info = {
                          id: record.id,
                          step: 0,
                          craftId: '',
                          deviceProductId: ''
                        };
                        CraftsInfoAPI.DelStep(delData).then((r) => {
                          if (r.statusCode === 200) {
                            message.success(r.statusCode === 200 ? '删除成功' : r.message);
                            action?.reload();
                          }
                        });
                      }}
                      onCancel={() => {
                        message.info('已取消删除');
                      }}
                      okText="确认"
                      cancelText="关闭"
                    >
                      <Button type='primary' danger ghost>删除</Button>
                    </Popconfirm>
                  </Space>
                ],
              },
            ]}
            rowKey="step"
            search={false}
            pagination={{ pageSize: 100,showSizeChanger:false  }}
            
            params={stepparams}
            request={async (params = {}) => {
              if (!params.craftId) {
                return {
                  data: [],
                  success: false,
                  total: 0,
                };
              }
              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,
                };
              }
            }}
            dragSortKey="step"
            onDragSortEnd={(beforeIndex: number, afterIndex: number,newDataSource: any[]) => {

              console.log('newDataSource',newDataSource);
              
              // 模拟将排序后数据发送到服务器的场景
              // remoteData = newDataSource;
              // 请求成功之后刷新列表
              newDataSource.map((item, index) => {
                item.step = index + 1;
              })
              console.log('排序后的数据', newDataSource);
              CraftsInfoAPI.BatchUpdateStep(newDataSource).then((res: MyResponse.Content) => {
                if (res.data) {
                  sortActionRef.current?.reload();
                  message.success('修改列表排序成功');
                }
              });

            }}
          />
        </Col>
      </Row>
      {
        /*
        * 新增工艺信息
        */}
      <Modal
        maskClosable={false}
        key={uuid()}
        width={800}

        title={<Tag color="#cd201f">工艺信息</Tag>}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        footer={false}
      >
        <BetaSchemaForm<CraftsTypes.craftsInfoOutput>

          onFinish={async (values) => {
            if (selectRowItem?.id) {
              values.id = selectRowItem.id
              CraftsInfoAPI.Update(values).then((res: MyResponse.Content) => {
                if (res.data) {
                  message.success("修改成功！");
                  setIsModalOpen(false)
                  actionRef.current?.reload();
                } else {
                  message.success(res.errors);
                }
              });
            } else {
              CraftsInfoAPI.Add(values).then((res: MyResponse.Content) => {
                if (res.data) {
                  message.success("添加成功！");
                  setIsModalOpen(false)
                  actionRef.current?.reload();
                } else {
                  message.success(res.errors);
                }
              });
            }
          }}
          form={typeForm}
          columns={columns}
        />

      </Modal>
      <Modal
        maskClosable={false}
        destroyOnClose
        width={800}
        open={isSetpModalOpen}
        onCancel={() => {
          setIsSetpModalOpen(false);
        }}
        footer={false}
        title={<Tag color="#cd201f"> 添加步骤 </Tag>}
      >
        <ProForm form={typeForm} onFinish={async (value: CraftsTypes.Pztj_CraftStepsAddInput) => {
          value.craftId = stepparams.craftId;
          console.log(value);
          if (value.id) {
            CraftsInfoAPI.UpdateStep(value).then((res: MyResponse.Content) => {
              if (res.data) {
                message.success('提交成功');
                setIsSetpModalOpen(false);
                sortActionRef.current?.reload()
              } else {
                message.success(res.errors);
              }
            })
          } else {
            CraftsInfoAPI.StepAdd(value).then((res: MyResponse.Content) => {
              if (res.data) {
                message.success('提交成功');
                setIsSetpModalOpen(false);
                sortActionRef.current?.reload()
              } else {
                message.success(res.errors);
              }
            })
          }
        }}>
          <Form.Item label="步骤Id" name="id" hidden>
            <Input></Input>
          </Form.Item>
          <Form.Item>
            <div>将自动生成步骤序号</div>
          </Form.Item>
          <Form.Item label="步骤说明" name="description">
            <Input></Input>
          </Form.Item>
        </ProForm>
      </Modal>


      {
        /*
        * 配置设备参数弹框
        */}
      <Modal
        maskClosable={false}
        destroyOnClose
        width={800}
        title={<Tag color="#cd201f"> 配置设备参数信息</Tag>}
        open={isSchemaModalOpen}
        onCancel={() => {
          setIsSchemaModalOpen(false);
          dongtaiformRef.resetFields()
          setDeviceParm([]);
        }}
        footer={false}
      >
        <Spin spinning={spinStatus}>
          <Form
            form={formRef}
            name="basic1"
            id="myForm1111"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 12 }}
            autoComplete="off"
          >
            <Form.Item label="id" name="id" hidden>
              <Input />
            </Form.Item>
            <Form.Item
              label="设备功能信息"
              name="deviceProductFunctionId"
              rules={[{ required: true, message: '此项必填！' }]}
            >
              <Select onChange={(value: string, index) => {

                const out = deviceFun.find(x => x.id === value);
                if (out?.params) {
                  const b = JSON.parse(out?.params);
                  console.log(b);
                  const c: any[] = [];
                  b.map((paramsItem: paramsType) => {
                    const element = {
                      title: paramsItem.paramName,
                      dataIndex: paramsItem.paramCode,
                      width: 'md',
                      renderFormItem: (dom, rowData, index) => {
                        return (
                          paramsItem.paramType
                            === 1 ? <Select mode='multiple' options={materialList}></Select> : <Input addonAfter={paramsItem.paramUnit} />
                        );
                      },
                      colProps: {
                        xs: 24,
                        md: 12,
                      },
                    }
                    c.push(element)
                  })
                  setDeviceParm(c);
                } else {
                  setDeviceParm([]);
                }
              }} placeholder="下拉选择功能">
                {
                  deviceFun.map((item: deviceProductFunction.output) => {
                    return <Select.Option value={item.id} key={item.id}>
                      <span>{item.name}</span>
                    </Select.Option>
                  })
                }
              </Select>
            </Form.Item>
          </Form>
          <Card>
            <BetaSchemaForm<any>
              trigger={<a>点击我</a>}
              rowProps={{
                gutter: [16, 16],
              }}
              colProps={{
                span: 12,
              }}
              grid={true}
              onFinish={async (values) => {
                console.log(formRef.getFieldsValue());

                const froms: CraftsTypes.craftsInfoOutput = formRef.getFieldsValue()
                if (!froms.deviceProductFunctionId) {
                  message.error("请选择设备产品功能");
                  return;
                }
                console.log(froms.deviceProductFunctionId);

                const jsonData: CraftsTypes.craftsInfoUpdateInput = {
                  id: froms.id,
                  deviceProductFunctionId: froms.deviceProductFunctionId,
                  params: JSON.stringify(values),
                  deviceProductId: ''
                }
                CraftsInfoAPI.UpdateStep(jsonData).then((res: MyResponse.Content) => {
                  if (res.data) {
                    sortActionRef.current?.reload();
                    message.success("成功！");
                    setIsSchemaModalOpen(false)
                  }
                });
              }}
              columns={deviceParm}
              form={dongtaiformRef}
            />
          </Card>
        </Spin>
      </Modal>
    </>
  )
}

export default Index;
