import React,{Ref,useEffect,useState,useRef } from 'react';
import {Button,Tree,Tabs,Table,Modal,Space,Form, Input,TreeSelect,Select,Upload, message,Popconfirm,Tooltip   } from 'antd'
import { PlusOutlined,LoadingOutlined,InfoCircleOutlined } from '@ant-design/icons';
import { upload } from '@/services/news/news';
import { FormattedMessage,useIntl } from 'umi';
import { getCarList,editProductTree,getDeleteTree,pushProducts, } from '@/services/product';
import '../index.less';
import { trim } from 'lodash';

const { Option } = Select;
const { TextArea } = Input;

const CarModelsTable: React.FC<{id:any,upTree:any,treeDataAll:any}> = (prop:any) => {
  let intl = useIntl()
  const [listData, setListData] = useState([]);  //列表数据

  const [isModalOpen, setIsModalOpen] = useState(false);  //弹框
  const [modalTitle, setModalTitle] = useState(true);  //弹框标题
  const [form] = Form.useForm();
  // const [nodes, setNodes] = useState<string>();

  const [loading, setLoading] = useState(false);
  const [imgPc, setImgPc] = useState({id:undefined,url:''});   //pc图片
  const [imgM, setImgM] = useState({id:undefined,url:''});   //移动端图片
  const [htmlPath, setHtmlPath] = useState(1);   //页面路径，为1成功，为2失败不能保存
  // 页面路径是否显示
  const [pagePathShow, setPagePathShow] = useState(true);
  //弹框确定
  const handleOk = () => {
    let dataNow=form.getFieldsValue();
    
      if(dataNow.htmlUrl==undefined||trim(dataNow.htmlUrl).length==0){
        setHtmlPath(3)
      }
    form.submit();
  };
  //弹框取消
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //删除数据
  const deleteCar = async (e:any) => {
    console.log('删除：',e);
    let res:any=await getDeleteTree(e.uuid);
        if(res.code==200){
          getListData();
          prop.upTree();
          message.success(res.msg);
        }else{
          message.error(res.msg)
        }
  };
  //修改数据
  const revise = (e:any) => {
    console.log('修改',e);
    form.setFieldsValue(e);
    setHtmlPath(1);
    // setNodes(e?.nodes);
    setImgPc({id:e?.pcImg,url:e?.pcImgUrl});
    // setImgM({id:e?.mImg,url:e?.mImgUrl});
    setIsModalOpen(true);
    setModalTitle(false);
  };
  //新增
  const addDom = ()=>{
    
    
    form.resetFields();
    form.setFieldsValue({ 
      carType: undefined,
      pText: undefined,
      title:undefined,
      sort:undefined,
      uuid:undefined,
      key:undefined,
      htmlUrl:undefined,
    });
    setHtmlPath(1);
    // setNodes(undefined);
    setImgPc({id:undefined,url:''});
    // setImgM({id:undefined,url:''});
    setIsModalOpen(true);
    setModalTitle(true);
  }
  //表单数据保存
  const formSend = ()=>{
    form.validateFields();
    
    let dataNow=form.getFieldsValue();
    if(pagePathShow)dataNow.htmlUrl=trim(dataNow.htmlUrl);
    dataNow={
      ...dataNow,
      // nodes,
      pcImg:imgPc.id?imgPc.id:'',
      // mImg:imgM.id?imgM.id:'',
      fatherId:prop.id,
      carType:'model'
    }
    
    
    if(pagePathShow&&htmlPath!=1){
      return
    }
    editProductTree(dataNow).then((res:any)=>{
      if(res.code == 200){
        getListData();
        prop.upTree();
        setIsModalOpen(false);
        message.success(res.msg);
      }else{
        message.error(res.msg);
      }
    });
  }
  //树形选择
  const onChangeTreeSelect = (newValue: string) => {
    console.log(newValue,'newValue');
    
    // setNodes(newValue);
  };
  //类型选择
  const onCarTypeChange = (value: string) => {
    form.setFieldsValue({ carType: value });
  };
  //图片上传
  const handleBeforeUpload = async (file: any,type:any) => {
    const formData = new FormData();
    formData.append('file', file, file.name);
    const res = await upload(formData);
    if (res?.data?.uuid) {
      if(type == 'pc'){
        setImgPc({id:res.data.uuid,url:res.data.url})
      }else{
        setImgM({id:res.data.uuid,url:res.data.url})
      }
      
    }
    return false;
  };
  //图片删除
  const imgDele = (value: string) => {
    if(value == 'pc'){
      setImgPc({id:undefined,url:''})
    }else{
      setImgM({id:undefined,url:''})
    }
  };
  
  //表格列设置
  const columns: any = [
    {
      title: intl.formatMessage({id:'public.title'}),
      dataIndex: 'title',
      key: 'title',
      width:200,
    },
    {
      title: intl.formatMessage({id:'public.sort'}),
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
      width:100,
    },
    {
      title: intl.formatMessage({id:'public.desctiption'}),
      dataIndex: 'pText',
      key: 'pText',
      align: 'center',
      width:400,
    },
    {
      title: intl.formatMessage({id:'public.img'}),
      dataIndex: 'carImg',
      key: 'carImg',
      align: 'center',
      width:150,
      render: (text,record:any) => <img src={record?.pcImgUrl} style={{ height:'110px'}}/>,
    },
    {
      title: intl.formatMessage({id:'public.action'}),
      dataIndex: '',
      align: 'center',
      width:160,
      render: (text,record) => {
        return <Space size="middle"><Button type='text' onClick={()=>revise(record)}>{intl.formatMessage({id:'public.update'})}</Button><Button type='text' onClick={()=>deleteCar(record)}>{intl.formatMessage({id:'public.delete'})}</Button></Space>
      },
    },
  ];
  
  const getListData:any =()=>{
    if(prop.id=='')return;
    let showPage=true;
    prop.treeDataAll.map((e:any)=>{
      if(e.uuid =="9a99b2abf66e45269306c3c34bd64d8c"){
        if(e.children.filter((item:any)=>item.uuid==prop.id).length>0){
          showPage=false;
        }
      }
    });
    setPagePathShow(showPage);
    getCarList(prop.id).then((res)=>{
      if(res.code==200){
        if(res.rows.length>0){
          setListData(res.rows);
        }else{
          setListData([]);
        }
      }else{
        message.error(res.msg);
      }
    })
  }
  //发布静态化
  const pushStatusPage:any =()=>{
    if(prop.id==''){
      message.error('没有id');
      return;
    }
    pushProducts(prop.id).then((res:any)=>{
      if(res.code==200){
        message.success(res.msg)
      }else{
        message.error(res.msg);
      }
    })
  }
  useEffect(() => {
    getListData();
    
  }, [prop.id]);
  //路径校验
  const onPagePathChange=(val:any)=>{
    let str=trim(val.target.value);
    if(str.length==0||str==undefined||str==null){
      setHtmlPath(3)
    }else if(str.indexOf('?')!==-1||str.indexOf('*')!==-1||str.indexOf(':')!==-1||str.indexOf('"')!==-1||str.indexOf('<')!==-1||str.indexOf('>')!==-1||str.indexOf('|')!==-1||str.indexOf('\\')!==-1){
      setHtmlPath(2)
    }
    else{
      setHtmlPath(1)
    }
  }

  return (
      <div className='carRight'>
        <div className='carTitle'>
          
          {intl.formatMessage({id:'public.carTypeList'})}
          <Popconfirm title={intl.formatMessage({id:'public.ifConfirmPublish'})+'?'} onConfirm={pushStatusPage}>
                <Button className='btn' type="primary">{intl.formatMessage({id:'public.publishAll'})}</Button>
          </Popconfirm>
          <Button className='btn' type="primary" onClick={addDom}>{intl.formatMessage({id:'public.add'})}</Button>
        </div>
        <Table
          columns={columns}
          dataSource={listData}
          rowKey={(record:any)=>record?.uuid}
        />
        <Modal title={modalTitle?intl.formatMessage({id:'public.newCarTypeInfo'}):intl.formatMessage({id:'public.updateCarTypeInfo'})} className='carModal' open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={880}>
        <Form
            form={form}
            labelCol={{ flex: '160px' }}
            labelAlign="left"
            labelWrap
            wrapperCol={{ flex: 1 }}
            colon={false}
            style={{ maxWidth: 880 }}
            onFinish={formSend}
          >
            <Form.Item label="uuid" name="uuid" hidden>
              <Input />
            </Form.Item>
            <Form.Item label={intl.formatMessage({id:'public.carTypeName'})} name="title" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            {/* <Form.Item name="carType" label="类型" rules={[{ required: true }]}>
              <Select
                placeholder="请选择类型"
                onChange={onCarTypeChange}
                allowClear
              >
                <Option value="series">车系</Option>
                <Option value="overview">概览</Option>
              </Select>
            </Form.Item> */}
            <Form.Item label={intl.formatMessage({id:'public.sort'})} name="sort">
              <Input />
            </Form.Item>
            {/* <Form.Item label="关联节点" rules={[{ required: true }]}>
              <TreeSelect
                  showSearch
                  style={{ width: '100%' }}
                  value={nodes}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择"
                  allowClear
                  treeDefaultExpandAll
                  onChange={onChangeTreeSelect}
                  treeData={prop.treeDataMy}
                  fieldNames={{label:'title',value:'uuid'}}
                />
            </Form.Item> */}
            
            <Form.Item label={intl.formatMessage({id:'public.description'})} name="pText">
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item label={intl.formatMessage({id:'public.keyword'})} name="key">
              <Input />
            </Form.Item>
            {pagePathShow&&
            <Form.Item label={intl.formatMessage({id:'public.pagePath'})} name="htmlUrl" rules={[{ required: true }]}
            validateStatus={(htmlPath==2||htmlPath==3)?"error":""} help={htmlPath==2?intl.formatMessage({id:'public.pagePathInfo'}):htmlPath==3?intl.formatMessage({id:'public.inputPlaceholder'})+intl.formatMessage({id:'public.pagePath'}):""}
            >
              <Input suffix={<Tooltip title={intl.formatMessage({id:'public.pagePathMess'})}>
          <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)' }} />
        </Tooltip>} onChange={onPagePathChange} placeholder={intl.formatMessage({id:'public.inputPlaceholder'})+intl.formatMessage({id:'public.pagePath'})}/>
            </Form.Item>}

            <Form.Item label={intl.formatMessage({id:'public.img'})+'(PC)'} extra={intl.formatMessage({id:'public.pictureSize'})+'：1280*720'}>
                {imgPc.id && <div className='showImg'><img src={imgPc.url} /></div>}
                <div className='uploadBtn'>
                    <Upload
                        beforeUpload={(e)=>handleBeforeUpload(e,'pc')}
                        maxCount={1}
                        showUploadList={false}
                        accept={'.png, .jpg, .gif'}
                      >
                        <Button>{intl.formatMessage({id:'public.upload'})}</Button>
                    </Upload>
                </div>
                <div className='uploadBtn'><Button onClick={()=>{imgDele('pc')}} >{intl.formatMessage({id:'public.delete'})}</Button></div>
            </Form.Item>
            {/* <Form.Item label="图片(移动)">
                {imgM.id && <div className='showImg'><img src={imgM.url} /></div>}
                <div className='uploadBtn'>
                    <Upload
                        beforeUpload={(e)=>handleBeforeUpload(e,'m')}
                        maxCount={1}
                        showUploadList={false}
                        accept={'.png, .jpg, .gif'}
                      >
                        <Button>上传</Button>
                    </Upload>
                </div>
                <div className='uploadBtn'><Button onClick={()=>{imgDele('m')}}>删除</Button></div>
            </Form.Item> */}

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

export default CarModelsTable;