import { PlusOutlined } from '@ant-design/icons';
import type {
  ActionType,
  ProColumns,
  ProFormInstance,
} from '@ant-design/pro-components';
import ReactFlow from 'react-flow-renderer';
import {
  DragSortTable,
  ProCard,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Flex, Form, Input, message, Modal, Popconfirm, Select, Space, Steps } from 'antd';
import { useState, useRef, useEffect } from 'react';
import { FlowView, SelectType, useFlowViewer, useNodesState } from '@ant-design/pro-flow';
import { createStyles } from 'antd-style';
//引入接口
import dayjs from 'dayjs'
import { v4 as uuid } from 'uuid'
import productlineInfoAPI from '@/api/productlineInfo/service'
import processAPI from '@/api/process/service';
import deviceAPI from '@/api/DeviceInfo';
import productlineInfoStepsAPI from '@/api/productlinesteps/service'
import { edges, nodes as newnodes } from './data';

export default () => {
  const [fromType, setFromType] = useState<any>('table')
  const ref = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();

  const Reolod = () => {
    ref.current?.resetFields()
    actionRef.current?.reload()
  }

  const [flowOpen, setFlowOpen] = useState<boolean>(false)
  const [flowItemOpen, setFlowItemOpen] = useState<boolean>(false)

  const [deviceOpen, setDeviceOpen] = useState<boolean>(false)

  const [selectProcess, setSelectProcess] = useState<any>(0)

  const columns: ProColumns<productlineInfoTypes.output>[] = [
    {
      title: '主键',
      dataIndex: 'id',
      formItemProps: {
        hidden: true
      },
      hideInSearch: true
    },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
      formItemProps: {
        rules: [{ required: true, message: '此项为必填项!' }]
      }
    },
    {
      title: '描述',
      dataIndex: 'describe',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (_, record) => {
        return <>{dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss")}</>
      },
      search: false,
      hideInForm: true
    },
    {
      title: '操作',
      valueType: 'option',
      fixed:'right',
      render: (text, row) => [
        <Space key={+new Date() + Math.random()}>
           <Button type='primary'  size='small' onClick={() => {
            setFlowOpen(true)
            setStepparams({ lineId: row.id })
          }} key={+new Date() + Math.random()} target="_blank" rel="noopener noreferrer">
            配置工序与设备
          </Button>
          <Button type='primary' size='small' onClick={() => {
            setFromType('form')
            ref.current?.setFieldsValue(row)
          }} key={+new Date() + Math.random()} target="_blank" rel="noopener noreferrer">
            编辑
          </Button>
          <Popconfirm
            key="del"
            title="确定要删除此条数据吗？"
            onConfirm={() => {

              productlineInfoAPI.Del(row).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  message.info("删除成功!");
                  Reolod()
                } else {
                  message.error(res.errors);
                }
              })
            }}
            onCancel={() => {
              message.info('已取消删除');
            }}
            okText="确认"
            cancelText="关闭"
          >
            <Button type='primary' danger size='small'>
              删除
              </Button>
          </Popconfirm>
        </Space>
      ],
    },
  ];
  const useStyles = createStyles(() => {
    return {
      container: {
        width: '100%',
        height: '400px',
      },
    };
  });
  const [selectLineItem, setSelectLineItem] = useState<any>();
  const [processList, setProcessList] = useState<any[]>();
  const [stepparams, setStepparams] = useState<any>();
  const [dongtaiformRef] = Form.useForm();
  const { styles } = useStyles();
  const { selectNode, selectEdges, selectNodes } = useFlowViewer();
  const [nodes, , onNodesChange] = useNodesState(newnodes);
  const [node, setNode] = useState(null);
  const sortActionRef = useRef<ActionType>();
  const [proList, setProList] = useState<any[]>([]);
  const [deviceList, setDeviceList] = useState<any[]>([]);
  const [form] = Form.useForm();
  const [deviceform] = Form.useForm();
  const processIdFlag = Form.useWatch('processId', form);
  useEffect(() => {
    processAPI.List({ name: '' }).then((v: MyResponse.Content) => {
      if (v.statusCode === 200) {
        console.log('processAPI.List', v.data);
        setProList(v.data)
      }
    })
    deviceAPI.selectlist().then((v: MyResponse.Content) => {
      if (v.statusCode === 200) {
        console.log('v.data', v.data);
        setDeviceList(v.data)
      }
    })

  }, [])

  return (
    <>
      <ProTable<productlineInfoTypes.output>
        columns={columns}
        type={fromType as 'table'}
        formRef={ref}
        cardBordered
        bordered
        scroll={{ x: true }}
        rowClassName={(record: any, index: number, indent: number) => {
          if (index % 2 === 0) {
            return ''; // 偶数行的类名
          } else {
            return 'even-row-background'; // 奇数行的类名
          }
        }}
        actionRef={actionRef}
        onSubmit={(params: any) => {
          console.log(params);
          if (fromType === 'form') {
            if (params.id) {
              productlineInfoAPI.Update(params).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  message.info("更新成功!");
                  setFromType('table')
                  Reolod()
                } else {
                  message.error(res.errors);
                }
              })
            } else {
              productlineInfoAPI.Add(params).then((res: MyResponse.Content) => {
                if (res.statusCode === 200) {
                  message.info("新增成功!");
                  setFromType('table')
                  Reolod()
                } else {
                  message.error(res.errors);
                }
              })
            }
          }
        }}

        form={{
          ignoreRules: true,// 自定义提交按钮的属性
          submitter: {
            onReset: () => {
              ref.current?.resetFields()
              setFromType("table")
            },
            searchConfig: { resetText: fromType === 'form' ? '返回' : '重置', submitText: fromType === 'form' ? '提交' : '查询' },
          }
        }}
        request={async (params = {}) => {
          const jsonData: productlineInfoTypes.queryPage = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
          };
          const response = await productlineInfoAPI.PagedList(jsonData);
          if (response.statusCode === 200) {
            return {
              data: response.data.items,
              success: true,
              total: response.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        pagination={{
          pageSize: 10,
          showSizeChanger: false
        }}
        rowKey="id"
        dateFormatter="string"
        headerTitle="列表"
        toolBarRender={() => [
          <Button key="3" type="primary" onClick={() => {
            setFromType('form');
          }}>
            <PlusOutlined />
            新建
          </Button>,
        ]}
      />
      <Modal open={flowOpen} maskClosable={false} footer={null} width={"80%"} height={"80%"} title='配置工艺流程' onOk={() => { setFlowOpen(false) }} onCancel={_ => setFlowOpen(false)}>

        <DragSortTable<productlinestepsTypes.base_dto>
          toolBarRender={() => [
            <Button
              key={new Date().toDateString()}
              type="primary"
              onClick={() => {
                form.resetFields();

                setFlowItemOpen(true)
              }}
            >
              添加步骤
            </Button>,
          ]}
          actionRef={sortActionRef}

          columns={[

            {
              title: '工序',
              dataIndex: 'step',
              tooltip:"拖拽更改顺序",
              align: 'center',
              hideInSearch: true,
              render: (dom, rowData, index) => {
                return (
                  <span className="customRender">{`${index + 1}`}</span>
                );
              },
            },
            {
              title: '主键',
              dataIndex: 'id',
              align: 'center',

              hideInSearch: true,
            },
            {
              title: '工艺名称',
              dataIndex: 'processId',
              align: 'center',
              width:120,
              hideInSearch: true,
              render(dom, entity, index, action, schema) {
                return <>{proList.find((x) => x.id == entity.processId)?.name}</>
              },
            },
            {
              title: '工艺类型',
              dataIndex: 'processType',
              align: 'center',
              width:120,
              hideInSearch: true,
              render(dom, entity, index, action, schema) {
                return <>{proList.find((x) => x.id == entity.processId)?.processType == 0 ? "人工" : "设备"}</>
              },
            },
            {
              title: '工艺设备',
              dataIndex: 'deviceId',
              align: 'center',
              hideInSearch: true,
              valueType:'select',
              request:async ()=>{
                  const data: MyResponse.Content = await deviceAPI.selectlist()
                  const chan: any[] = data.data;
                  chan.map((item) => (
                    item.label = item.value,
                    item.value = item.key
                  ))
                  return chan;
                },
            },
            {
              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));
                      form.setFieldsValue(copyFormData);

                      setFlowItemOpen(true)
                      // setIsSetpModalOpen(true);
                    }}
                  >
                    编辑
                  </Button>
                  <Button disabled={proList.find((x) => x.id == record.processId)?.processType == 0}
                    key={uuid()}
                    type='primary' ghost
                    onClick={async () => {
                      // setIsModalOpen(true)


                      productlineInfoAPI.devicelist({stepId:record.id,lineId:''}).then((res:MyResponse.Content)=>{
                          if (res.statusCode===200) {
                           
                            const copyFormData = JSON.parse(JSON.stringify(record));
                            copyFormData.deviceId = res.data.map((item:any)=>item.deviceId)
                            deviceform.setFieldsValue(copyFormData);
                              console.log('配置设备',copyFormData);
                              
                            setDeviceOpen(true)        
                          }else{
                            const copyFormData = JSON.parse(JSON.stringify(record));
                            deviceform.setFieldsValue(copyFormData);
                              console.log('配置设备',copyFormData);
                              
                            setDeviceOpen(true)      
                          }
                      })
                     
                      // setIsSetpModalOpen(true);
                    }}
                  >
                    配置设备
                  </Button>
                  <Popconfirm
                    key={uuid()}
                    title="确定要删除此条数据吗？"
                    onConfirm={() => {
                      const delData: productlinestepsTypes.delInput = {
                        id: record.id,
                      };
                      productlineInfoStepsAPI.Del(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.lineId) {
            //   return {
            //     data: [],
            //     success: false,
            //     total: 0,
            //   };
            // }
            const jsonData: productlinestepsTypes.queryParms = {
              lineId: params.lineId
            };
            const response = await productlineInfoStepsAPI.List(jsonData);
            if (response.statusCode === 200) {
              setProcessList(response.data)

              return {
                data: response.data,
                success: true,
              };
            } 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);
            productlineInfoStepsAPI.BatchUpdateStep(newDataSource).then((res: MyResponse.Content) => {
              if (res.data) {
                sortActionRef.current?.reload();
                message.success('修改列表排序成功');
              }
            });

          }}
        />

      </Modal>
      <Modal open={flowItemOpen} maskClosable={false} title='添加步骤'
        footer={[
          <Button
            key="back"
            onClick={() => {
              setFlowItemOpen(false)
            }}
          >
            返回
          </Button>,
          <Button key="submit" form="addprocessForm" type="primary" htmlType="submit">
            提交
          </Button>,
        ]}

        onOk={() => { setFlowItemOpen(false) }} onCancel={_ => setFlowItemOpen(false)}>
        <Form
          id='addprocessForm'
          form={form}
          onFinish={(v) => {
            console.log(v);
            if (v.id) {
              const jsonData: productlinestepsTypes.addInput = {
                step: 0,
                processId: v.processId,
                id: v.id,
                lineId: stepparams.lineId,
                processName: ''
              }
              productlineInfoStepsAPI.Update(jsonData).then((v: MyResponse.Content) => {
                if (v.statusCode === 200) {
                  setFlowItemOpen(false)
                  sortActionRef.current?.reload();
                }
              })
            } else {
              const jsonData: productlinestepsTypes.addInput = {
                step: 0,
                processId: v.processId,
                id: '',
                lineId: stepparams.lineId,
                processName: ''
              }
              productlineInfoStepsAPI.Add(jsonData).then((v: MyResponse.Content) => {
                if (v.statusCode === 200) {
                  setFlowItemOpen(false)
                  sortActionRef.current?.reload();
                }
              })
            }

          }}>
          <Form.Item label="主键"
            name="id"
            hidden={true}>
          </Form.Item>
          <Form.Item label="步骤"
            name="step"
            hidden={true}>
          </Form.Item>
          <Form.Item label="工艺"
            name="processId" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Select onChange={(v: processType.output) => {
            }} placeholder='请选择工艺' style={{ width: 375 }}>
              {
                proList.map((item: processType.output) => {
                  return <Select.Option value={item.id} key={item.id}>
                    <span>{item.name}</span>
                  </Select.Option>
                })
              }
            </Select>
          </Form.Item>
        </Form>
        
      </Modal >

      <Modal open={deviceOpen} maskClosable={false}  width={500} title='配置工艺所需设备'
       footer={[
        <Button
          key="back"
          onClick={() => {
            setDeviceOpen(false)
          }}
        >
          返回
        </Button>,
        <Button key="submit" form="adddeviceForm" type="primary" htmlType="submit">
          提交
        </Button>,
      ]}
      onOk={() => { setDeviceOpen(false) }} onCancel={() => { setDeviceOpen(false) }}>
        {/*
           工艺
           */}
        <Form 
        form={deviceform}
        id='adddeviceForm'
        onFinish={(v) => {
            console.log(v,stepparams);
            const jsonData:productlineInfoTypes.batchDevice = {
              id: v.id,
              lineId:stepparams.lineId,
              deviceId: v.deviceId
            }
            productlineInfoAPI.Batchdevice(jsonData).then((res:MyResponse.Content)=>{
              if (res.statusCode===200) {
                message.info("更新成功!");
                setDeviceOpen(false)
                sortActionRef.current?.reload();
              }else{
                message.info(res.errors);
                sortActionRef.current?.reload();
              }
            })

          }}>
             <Form.Item label="主键"
            name="id"
            hidden={true}>
          </Form.Item>
          <Form.Item label="请选择设备"
            name="deviceId" rules={[{ required: true, message: '此项为必填项!' }]} >
            <Select mode="multiple" placeholder='请选择设备' style={{ width: 375 }}>
              {
                deviceList.map((item: MySelectType.Select) => {
                  return <Select.Option value={item.key} key={item.key}>
                    <span>{item.value}</span>
                  </Select.Option>
                })
              }
            </Select>
          </Form.Item>

        </Form>
      </Modal>
    </>
  );
};