/**
 * 设备基础信息管理
 * @param Page
 * @returns
 */
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Transfer, Tag, Col } from 'antd';
import { useRef, useState, useEffect } from 'react';
import { history } from '@umijs/max';
import DeviceInfoAPI from '@/api/DeviceInfo';
import RecipeAPI from '@/api/recipeService'
import { TransferDirection } from 'antd/es/transfer';


interface RecordType {
  key: string;
  title: string;
  description: string;
  chosen: boolean;
}
let selectRecordId :string;
export default () => {
  //表单
  const [typeForm] = Form.useForm();
  //穿梭框数据
  const [materialData,setMaterialData] = useState<RecordType[]>();
  //穿梭框选择数据
  const [targetKeys,setTargetKeys] = useState<string[]>();
  
  const filterOption = (inputValue: string, option: RecordType) =>
  option.description.indexOf(inputValue) > -1;

    const handleChange = (newTargetKeys: string[]) => {
      setTargetKeys(newTargetKeys);
    };

    const handleSearch = (dir: TransferDirection, value: string) => {
      console.log('search:', dir, value);
    };
    const GetTransferData = (record: DeviceTypes.Info) => {
      const tempTargetKeys:any[] = [];
      const tempMockData:any[] = [];
 
      //获取所有配方
      RecipeAPI.List().then((item:MyResponse.Content)=>{
        if (item.statusCode===200) {
           item.data.forEach((res:MaterialsTypes.MaterialsInfo)=>{
              const data = {
              key: res.id,
              title:res.name,
              description: res.name,
           };
           tempMockData.push(data);
          });
          setMaterialData(tempMockData);
        }
     }).then(()=>{
        DeviceInfoAPI.RecipeList(record.id).then((res:MyResponse.Content)=>{
          if (res.statusCode===200) {
            res.data.forEach((item:any)=>{
              tempTargetKeys.push(item.recipesId)
            }
            )
            setTargetKeys(tempTargetKeys);
          }
        });
     });
    };
  //下拉列表
  const [isMaterialModalOpen, setIsMaterialModalOpen] = useState(false);
  const [modelTitle, setModelTitle] = useState<string>();
  //编辑/新增弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<DeviceTypes.Info>[] = [
    {
      title: '设备名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '设备编码',
      dataIndex: 'code',
      hideInSearch: true,
      
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (_, record) => [
        <Button
          key="edit"
          type="primary"  ghost
          onClick={async () => {
            setIsModalOpen(true);
            setModelTitle('编辑信息');
            const copyFormData = JSON.parse(JSON.stringify(record));
            copyFormData.state = copyFormData.state === '0' ? true : false;
            typeForm.setFieldsValue(copyFormData);
          }}
        >
          编辑
        </Button>,
         <Button
         key="xfa"
         type="primary"  ghost
         onClick={async () => {
           setIsMaterialModalOpen(true);
           console.log('record',record);
           selectRecordId = record.id
           console.log('record',selectRecordId);
           GetTransferData(record);
         }}
       >
         配方下发
       </Button>,
        <Popconfirm
          key="del"
          title="确定要删除此条数据吗？"
          onConfirm={() => {
           
            const EnablejsonData: DeviceTypes.Info = {
              id: record.id,
              name: '',
              code: ''
            };
           
            DeviceInfoAPI.Del(EnablejsonData).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>,
      ],
    },
  ];

  /*
   初始化
  */
  useEffect(() => {
    // 下拉列表信息
    const RegionDataList = () => {
     
    };
    RegionDataList();
  }, []);

  /*
   *表单提交
   */
  const OnSubmit = async (values: DeviceTypes.Info) => {
    if (values.id) {
      const response = await DeviceInfoAPI.Update(values);
      if (response.statusCode === 200) {
        message.success('修改成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(response.errors || '修改失败');
      }
    } else {
      const response = await DeviceInfoAPI.Add(values);
      console.log('response', response);
      if (response.statusCode === 200) {
        message.success('添加成功');
        actionRef.current?.reload();
        setIsModalOpen(false);
      } else {
        message.error(response.errors || '添加失败');
      }
    }
  };
  return (
    <>
      <ProTable<DeviceTypes.Info>
        key="myTable"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params = {}) => {
          const jsonData: DeviceTypes.Page = {
            pageIndex: params.current || 1,
            pageSize: params.pageSize || 10,
            name: params.name || '',
            id: '',
            code: ''
          };
          const response = await DeviceInfoAPI.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,
        }}
        dateFormatter="string"
        headerTitle="设备列表"
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              typeForm.resetFields();
              setIsModalOpen(true);
              setModelTitle('新增信息');
            }}
          >
            新建设备
          </Button>,
        ]}
      />
      <Modal
        key="01"
        width={800}
        title={<Tag color="#cd201f">{modelTitle}</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
       key="02"
       width={800}
       
       title={<Tag color="#cd201f">配方下发</Tag>}
       open={isMaterialModalOpen}
       onCancel={() => {
         setIsMaterialModalOpen(false);
       }}
       footer={[
         <Button
           key="back"
           onClick={() => {
             setIsModalOpen(false);
           }}
         >
           返回
         </Button>,
         <Button key="submit"  type="primary" onClick={()=>{
          //提交数据
            console.log('selectRecordId',selectRecordId);
            const jsonData: DeviceTypes.BatchAdd = {
                deviceId: selectRecordId,
                recipesIds:targetKeys!
            }
            DeviceInfoAPI.BatchUpdate(jsonData).then((res:MyResponse.Content)=>{
                if (res.statusCode===200) {
                   message.success("保存成功!");
                   setIsMaterialModalOpen(false);
                }else{
                  message.error(res.errors);
                }
            });
         }}>
           提交
         </Button>,
       ]}
      >
      
      <Transfer
      listStyle={{
        width: 400,
        height: 400,
      }}
      // eslint-disable-next-line react/jsx-key
      titles={[<Col><Tag key='a' color='#f50'>产品配方库</Tag> <Button type='link' onClick={()=>{
        setIsMaterialModalOpen(false);
        history.push('/store/recipe');
      }}>去添加产品配方</Button></Col>, <Tag key='b' color="#3b5999">当前设备配方</Tag>]}
      dataSource={materialData}
      showSearch
      filterOption={filterOption}
      targetKeys={targetKeys}
      onChange={handleChange}
      onSearch={handleSearch}
      render={(item) => item.title}
      ></Transfer>
      </Modal>

      
    </>
  );
};
