
import { Modal, Button, message, Form, Upload, Select ,Popconfirm} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import {GetTechnologyPage,GetProductList,GetDeviceVesionList,DeleteTechnology } from "./services"
import { history } from 'umi';
import { getDataBaseUrl } from '@/global_data';
import Technologylist from './components/technologylist'
import useFetchData from '@ant-design/pro-descriptions/lib/useFetchData';
const key = 'message';
const GoodsTypeManage = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const actionRef = useRef();
  const [DictData, setDictData] = useState([]);
  const [DeviceVesionData, setDeviceVesionData] = useState([]);
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isAddGoodsTemplate,setIsAddGoodsTemplate]=useState(false);
  const [form] = Form.useForm();
  const [ProductVesionId, setProductVesionId] = useState('');
  const [deviceTypeKey, setdeviceTypeKey] = useState('');
  const [version, setversion] = useState('');
  
  const props = {
    beforeUpload: (file) => {
      if (
        file.type !== 'application/vnd.ms-excel' &&
        file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ) {
        message.error(`${file.name} 不是 exelce 文件`);
      }
      if(ProductVesionId.length==0){
        message.error(`请选择版本`);
        Upload.LIST_IGNORE
        return  Upload.LIST_IGNORE;
      }
      if(deviceTypeKey.length==0){
        message.error(`请选择产品`);
       
        return  Upload.LIST_IGNORE;
      }
      return file.type == 'application/vnd.ms-excel' ||
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ? true
        : Upload.LIST_IGNORE;
    },
   
    name: 'file',
    data: { "id": ProductVesionId, "deviceClientType": deviceTypeKey, "version": version,"isAddGoodsTemplate":isAddGoodsTemplate},
    action: getDataBaseUrl()+'/api/goods/goodstemplateexport',
    headers: {
      Authorization: 'Bearer  ' + localStorage.getItem('token'),
    //   'Content-Type':'application/json'
    },
    onChange(info) {
        console.log(info)
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      setIsAddGoodsTemplate(false);
      if (info.file.status === 'done') {
        setIsModalOpen(false);
        actionRef.current.reload();
        message.success(`${info.file.name} 文件上传成功.`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上载失败.`);
      }
    }
  };
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key'
    },
    {
        title: '所属产品',
        dataIndex: 'productName',
        valueType: 'textarea',
      },
    {
      title: '版本号',
      dataIndex: 'vesion',
      valueType: 'textarea',
    },
    {
        title: '时间',
        dataIndex: 'createAt',
        valueType: 'textarea',
        search:false
      },
    // {
    //   title: '是否存在模板',
    //   dataIndex: 'templatePath',
    //   valueType: 'textarea',
    //   hideInSearch: true,
    //   render: (_, record) => [
    //     <div>
    //       <Tag color="#f50" style={{ textAlign: "center", display: (record.templatePath == null||record.templatePath == "") ? "none" : "block" }}  >存在模板</Tag>
    //       <Tag style={{ textAlign: "center", display: (record.templatePath == null||record.templatePath == "")? "block" : "none" }} color="#2db7f5">无模板</Tag>
    //     </div>],
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 700,
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record.technologyInfo);
            // form.setFielsValue(record)
          }} > 详情</a>,
          <a
          key="config"
          href={record.templatePath}> 下载</a>,
          <Popconfirm
          type="primary"
          key="primary11"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            DeleteTechnology(record.id).then((r) => {
              if (r.data) {
                message.success('删除成功');
                actionRef.current.reload();
              } else {
                message.error(r.errors);
              }
              
            });
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,
        // <a
        //   key="config"
        //   onClick={() => {
        //     setCurrentRow(record);
        //     setIsModalOpen(true);
        //     setIsAddGoodsTemplate(false);
        //   }} > 上传设备工艺模型</a>,
        // <a
        //   key="config"
        //   onClick={() => {
        //     setCurrentRow(record);
        //     setIsModalOpen(true);
        //     setIsAddGoodsTemplate(true);
        //   }} > 上传商品工艺模版</a>,
        // <a
        //   key="config"
        //   href={record.templatePath}

        // > 下载工艺模板</a>,
       
      ],
    },
  ];
  useEffect(() => {
    GetProductList().then((r) => {
      var arr = r.data;
      if (r.succeeded) {
        var list = [];
        arr.forEach((item) => {
          list.push({
            label: item.name,
            text:item.name,
            id: item.id,
          });
        });
        //setDicDataAny(data);
        setDictData(list);
      }
    });
  }, [])
  const handleChange = (value) => {
    console.log(`selected ${value}`);
    setdeviceTypeKey(value)
    GetDeviceVesionList(value).then((r)=>{
        var arr = r.data;
      if (r.succeeded) {
        var list = [];
        arr.forEach((item) => {
          list.push({
            label: item.vesion,
            text:item.vesion,
            id: item.id,
          });
        });
        //setDicDataAny(data);
        setDeviceVesionData(list);
      }
    })
  };
  const handleVisChange=(value)=>{
    console.log(`selected ${value}`);
    setProductVesionId(value)
    var sd=DeviceVesionData.find(x=>x.id==value);
    setversion(sd?.label)
  }
  const onCancel=()=>{
    console.log("ss")
    setdeviceTypeKey("");
    setProductVesionId('');
    setDeviceVesionData([])
    handleModalVisible(false);
  }
  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle="设备版本"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              // form.setFielsValue(currentRow)
              setIsModalOpen(true);
            }} >
            <PlusOutlined /> 导入工艺模版
          </Button>,
        ]}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetTechnologyPage(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
        </FooterToolbar>
      )}
      <Modal title="上传工艺模版" open={isModalOpen} footer={null} maskClosable={false}
      destroyOnClose onCancel={() => { setIsModalOpen(false) }}>
        <div style={{marginBottom:10}}>
            <span style={{marginRight:10}}>选择产品</span>
            <Select style={{width: '60%'}} onChange={handleChange}>
            {DictData.map((item, index) => {
              return (
                <Select.Option index={index} value={item.id} key={item.id}>
                  {item.label}
                </Select.Option>
              );
            })}
          </Select>
        </div>
        <div style={{marginBottom:10}}>
            <span style={{marginRight:10}}>选择版本</span>
            <Select style={{width: '60%'}} onChange={handleVisChange}>
            {DeviceVesionData.map((item, index) => {
              return (
                <Select.Option index={index} value={item.id} key={item.id}>
                  {item.label}
                </Select.Option>
              );
            })}
            </Select>
        </div>
        <Upload {...props} maxCount={1}>
          <Button style={{marginLeft:'55%'}}>导入工艺模版</Button>
        </Upload>
      </Modal>
        <Technologylist createModalVisible={createModalVisible} dataSource={currentRow} onCancel={onCancel}/>
    </PageContainer>
  );
};

export default GoodsTypeManage;
