import React, { useState, useEffect,useRef } from 'react';
import { Modal, Row, Col, Checkbox, Select,message,Switch} from 'antd';
import ProTable from '@ant-design/pro-table';
import {
  GetDeviceList,
  GetGoodsPage,
  GetGoodsTypeTree,
  GetProductTopicslist,
  DevicePushRecodeAdd
} from '../services';
const PushFrom = (props) => {
  const [deviceData, setdeviceData] = useState([]);
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [dataSource,setdataSource]= useState([]);
  const [treeData, setTreeData] = useState();
  const [DeviceIds, setDeviceIds] = useState();
  const [DeviceInfo, setDeviceInfo] = useState([]);
  const [TopicsData, setTopicsData] = useState([]);
  const [isGlogy, setisGlogy] = useState(false);
  const [total,settotal]=useState(0);
  const actionRef = useRef();
  useEffect(() => {
    console.log(props.values)
    
    GetDeviceList().then((r)=>{
      setDeviceInfo(r.data)
      if(r.data.length>0){
        var data=r.data.map(x=>{
          return {value:x.id,label:x.name}
        })
        setdeviceData(data)
      }
     
    })
    GetGoodsTypeTree().then((r) => {
        setTreeData(r.data);
      });
      // var params={current:1,pageSize:10}
      // GetGoodsData(params)
  },[props.values])
  const GetGoodsData=(params)=>{
    GetGoodsPage(params).then((r) => {
        setdataSource(r.data.data);
        //console.log(goodsData)
        //total = r.data.total;
        settotal( r.data.total)
      });
  }
 const handleChange=(value)=>{
    setDeviceIds(value)
    var params={current:1,pageSize:10,deviceId:value}
    GetGoodsData(params)
    var de=DeviceInfo.find(x=>x.id==value);
    console.log("ddddd",de)
    GetProductTopicslist({productId:de?.productId,productVesionId:de?.productVersionId,IsDefault:true}).then((r)=>{
      setTopicsData(r.data)
    })
 }
 const onChange=(checked)=>{
  if(!DeviceIds){
    message.error('请先选择设备');
  }else{
    setisGlogy(checked)
 
  }
  
 }
 const HandleOk= async(values)=>{
  await DevicePushRecodeAdd(values).then((res)=>{
    if(res.data){
      message.success('操作成功');
      setSelectedRows([])
      setDeviceIds()
    }else{
      message.error(res.errors);
    }
    props.HandleOk(res.data)
  })
}
 const columns=[
    {
        title: '编码',
        dataIndex: 'code',
        valueType: 'textarea',
        hideInTable: true,
        hideInSearch: true,
      },
      {
        title: '名称',
        dataIndex: 'name',
        valueType: 'textarea',
      },
      {
        title: '商品类型',
        dataIndex: 'goodsTypeName',
        valueType: 'treeSelect',
        fieldProps: {
          showSearch:true,
          allowClear:true,
          options: treeData
        },
      },
 ]
  return (
    <Modal
      title={'下发数据'}
      width={1040}
      visible={props.createModalVisible}
      bodyStyle={{ padding: '32px 40px 1px 48px' }}
      okText="确定"
      cancelText="取消"
      onOk={() => {
        if(!DeviceIds){
          message.error('请选择设备');
        }else{
          var de=DeviceInfo.find(x=>x.id==DeviceIds);
          var data=[];
          console.log("de",de)
          selectedRowsState.map(x=>{
              if(x.goodstechnology.length>0){
                x.goodstechnology.map(y=>{
                  data.push(y)
                })
                
              }
            // }
          })
          if(data.length==0){
            message.error('选择的商品还没有工艺');
          }else{
            var parm={deviceId:de.id,deviceName:de.name,deviceAutoKey:de.autoKey,type:4,data:data,productVersion:de.vesion,productKey:de.prductKey,topicsData:TopicsData}
            console.log("parm",parm)
            HandleOk(parm)
            console.log(de)
            
          }
         
        }
      }}
      onCancel={() => {
        props.onCancel();
        setSelectedRows([])
        setDeviceIds()
      }}
      destroyOnClose
    >
      <Row gutter={26} style={{marginBottom:20}}>
    <Col lg={24} md={24} sm={24}>
        选择设备：
        <Select
        
        allowClear
        style={{width: '60%'}}
        placeholder="请选择要下发设备"
        onChange={handleChange}
        options={deviceData}
        />
    </Col>
   
</Row>
{/* <Row style={{marginBottom:20}}>
  <Col lg={24} md={24} sm={24}>
    是否包含工艺：
    <Switch checkedChildren="是" unCheckedChildren="否" checked={isGlogy} value={isGlogy} onChange={onChange} />
  </Col>  
</Row> */}
<Row gutter={26}>
    <Col span={24}>
        选择数据：
        <ProTable
          headerTitle=""
          actionRef={actionRef}
          rowKey="id"
          pagination={{ defaultPageSize: 10}}
          search={{
            labelWidth: 120,
          }}
          //dataSource={dataSource}
          columns={columns}
          request={async (params) => {
            var total = 0;
            var data = [];
            const res = await GetGoodsPage(params);
            if (res.statusCode == 200) {
              setdataSource(res.data.data);
              data = res.data.data;
              total = res.data.total;
            }
            return {
              data: data,
              success: true,
              total: total,
            };
  
          }}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        >
          </ProTable>
    </Col>
</Row>
    </Modal>
  );
};

export default PushFrom;
