import React, { useState, useEffect, useRef } from 'react'
import { connect } from 'react-redux';
import moment from 'moment'
import { Button, Table, Modal, Form,Notification,Upload,Toast  } from '@douyinfe/semi-ui';
import { IconUpload,IconVigoLogo } from '@douyinfe/semi-icons';
import request from 'superagent';

const AddFirmwareModal = (props) => {
   const {modalVis,onCancel,crawapi,recordRow,actions,dispatch,qiniu} =props
   const api = useRef();
   const {domain}=qiniu //七牛服务器地址
   const {firmwareUpgrade}=actions
   const [uploadData, setUploadData] = useState({})
   const [options,setOptions]=useState([])//设备类型的下拉选项
   const [fileObj,setFileObj]=useState({})//文件对象
   const [fileUrl,setFileUrl]=useState()//文件地址
   const userId = JSON.parse(sessionStorage.getItem('pomsUser'))?.id
   const [removeFlag,setRemoveFlag]=useState(false)//文件是否清除过
   useEffect(()=>{
      //获取设备类型
      dispatch(firmwareUpgrade.getDeviceType()).then((res) => {
         setOptions( res.payload.data?.map(item=>  {
            return {
               label:item.model,
               value:item.id
            }
         }))
      })
   },[])
   // console.log('xxxx1111',recordRow)
   // console.log('xxxx11112',fileUrl)

   const okHandler= ()=>{
      // console.log('fileObj',fileObj)
        api.current.validate().then(async (res)=>{
         // console.log('ressss',res)
         // const query = {
         //    version:res?.versionNo,
         //    qiniu:domain,
         //    device_meta_id: res?.deviceName,
         //    tokenup: '22767e1f-db8d-4a1d-87d4-56347cf21247',
         //    wholeFile:fileUrl,
         // }
         // const body={
         //    filePath:fileUrl,
         //    userId:userId,
         //    comment:res?.remark,
         //    deviceMetaName:options?.find(item=>item.value===res?.deviceName)?.label,
         //    fileObj:fileObj
         // }
         // dispatch(firmwareUpgrade.upgradeFirmware(query,body)).then(res=>{
         // })
         const responseData=await request.get(qiniu+'/'+fileUrl).responseType('blob')  
         const blobData = responseData.body;
         request.post(crawapi+'/firmwareupgrade')
         // .set('Content-Type','application/octet-stream')
         .attach('file',blobData,removeFlag?fileObj.name:recordRow?recordRow.firmwareName:fileObj.name)
         .field('filePath',removeFlag?fileUrl:recordRow?recordRow.filepath:fileUrl)
         .field('userId', userId||'')
         .field('firmwareName', res?.firmwareName||'')
         .field('comment',res?.remark||'')
         .field('device_meta_name', options?.find(item=>item.value===res?.deviceName)?.label||'')
         .query({ version:res?.versionNo,device_meta_id: res?.deviceName,token:'22767e1f-db8d-4a1d-87d4-56347cf21247'})
         .end((err, response) => {
            if(response?.ok){
               Notification.success({ title: recordRow?'编辑固件包':'新增固件包',
               content: recordRow?'编辑成功':'新增成功',
               duration: 3,
               })
               setRemoveFlag(false)
               onCancel()
            }else{
               console.error('Superagent request failed:');
               Notification.error({  title: recordRow?'编辑固件包':'新增固件包',
               content: recordRow?'编辑失败':'新增失败',
               duration: 3,
                })
            }
         })

         
         
        })
    }

   //  function readFileAsBlob(file) {
   //    return new Promise((resolve, reject) => {
   //      const reader = new FileReader();
   //      reader.onload = () => {
   //        const blob = new Blob([reader.result], { type: file.type });
   //        resolve(blob);
   //      };
   
   //      reader.onerror = (error) => {
   //        reject(error);
   //      };
    
   //      reader.readAsArrayBuffer(file);
   //    });
   //  }

   return <>   
     <Modal visible={modalVis} onCancel={onCancel} title='固件上传' onOk={okHandler} >
    
         <Form initValues={{
           'firmwareName':recordRow?.firmwareName,
           'deviceName':recordRow?.device_meta_id,
           'versionNo':recordRow?.versionNo,
            'files':recordRow?[{ url: `${domain}/${recordRow?.filepath}`, name: recordRow?.firmwareName }]:[],
            'remark':recordRow?.remark
         }}  getFormApi={formApi => api.current = formApi}   labelCol={{ span: 7,offset:1}}  wrapperCol={{span: 15,offset:1}} labelPosition='left' >
            <Form.Input   field='firmwareName' label='固件版本名称:' style={{with:'80%'}}  rules={[{ required: true, message: '固件版本名称必填' }]}></Form.Input>
            <Form.Select  disabled={recordRow?true:false} field='deviceName' label='设备型号:' placeholder='请选择设备型号' optionList={options}   rules={[{ required: true, message: '设备型号必填' }]}></Form.Select>
            <Form.Input disabled={recordRow?true:false} field='versionNo' label='版本号:'  rules={[{ required: true, message: '版本号必填' }]}></Form.Input>
            <Form.Upload  limit={1}
                           action={`/_upload/attachments`}
                           field='files'  label='文件上传'
                           rules={[{ required: true, message: '文件上传必填' }]}
                           onRemove={() => {
                              setUploadData({})
                              setRemoveFlag(true)
                           }}
                           onSuccess={ async(responseBody, file,all) => {
                              // console.log('file111',file)
                           setFileObj(file)
                           setFileUrl(responseBody?.uploaded)
                           setUploadData({
                                       name: file.name,
                                       size: file.size,
                                       url: responseBody?.uploaded,
                                       uploadTime: moment().format("YYYY-MM-DD HH:mm:ss")
                                    })
                                 }}
                                >
                                <Button icon={<IconUpload />} theme="light">
                                    点击上传
                                </Button>
                            </Form.Upload>
            <Form.TextArea field='remark' label='备注:'   placeholder='请输入项目介绍'></Form.TextArea>
            
        </Form> 


     </Modal>
    </>
}


function mapStateToProps (state) {
    const { auth, global } = state;
    return {
       user: auth.user,
       actions: global.actions,
       crawapi: global.crawapi,
       qiniu:global.qiniu,

    };
 }
 
export default connect(mapStateToProps)(AddFirmwareModal)