import { DropboxOutlined, PlusOutlined,ArrowLeftOutlined   } from '@ant-design/icons';
import { Button, message, Input, Upload, Modal, Popconfirm,Card,Typography,Tabs  } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import ActionForm from './components/ActionForm';
import CreateTopis from './components/CreateTopis'
import {
  getGoodstechnologypage,
  addgoodstechnology,
  updategoodstechnology,
  deletegoodstechnology,
  GetDeviceVesion,
  getproducttopicspage,
  addproducttopics,
  updateproducttopics,
  deleteproducttopics,
  GetProduct
} from './services';
import { history } from 'umi';
const { Paragraph, Text } = Typography;
//页面 相当于 class


const props = {
  beforeUpload: (file) => {
    if (
      file.type !== 'application/vnd.ms-excel' &&
      file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ) {
      message.error(`${file.name} 不是 exelce 文件`);
    }
    return file.type == 'application/vnd.ms-excel' ||
      file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ? true
      : Upload.LIST_IGNORE;
  },
  name: 'file',
  action: '/saasbase/api/goodes/DeviceVersionTemplateImport',
  headers: {
    Authorization:'Bearer  ' + localStorage.getItem('token')
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  }
};

/**
 * 更新节点
 *
 * @param fields
 */


//页面 相当于 class
const bomtechnology = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createTopisModalVisible,setcreateTopisModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */
  const [currTabKey, SetCurrTabKey] = useState("basis")
  const [actionFormModalVisible, setactionFormModalVisible] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  //绑定
  const actionRef = useRef();
  const actiontopisRef= useRef();
  const actiontopismrRef= useRef();
  const [currentRow, setCurrentRow] = useState();
  const [currenttopsRow,setcurrenttopsRow] = useState();
  //选中的行
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [dataSource,setdataSource]=useState([]);
  const [datafunctionSource,setdatafunctionSource]=useState([]);
  // const [DeviceVesionData, setDeviceVesionData] = useState([]);
  // const [DeviceVesionEnum, setDeviceVesionEnum] = useState({});
  const [Product, setProduct] = useState({});
  const [total,settotal]=useState(0);
  const [totalfun,settotalfun]=useState(0);
  /** 国际化配置 */
  const [tabStatus, seTabStatus] = useState({
    operationKey: props.location.query.tabStatus ? props.location.query.tabStatus : 'basis',
    tabActiveKey: props.location.query.tabStatus ? props.location.query.tabStatus : 'basis',
  });
  useEffect(() => {
    console.log("props.location",props.location)
    SetCurrTabKey(tabStatus.tabActiveKey);
    if(!props.location.query.values.id){
      history.push({
        pathname: '/device/deviceVesion',
      });
    }else{
      // GetDeviceVesion(props.location.query.values.id).then((res)=>{
      //   let list = {};
      //   res.data.forEach((item) => {
      //     list[item.id] = { text: item.vesion };
      //   });
      //   setDeviceVesionData(res.data)
      //   setDeviceVesionEnum(list)
       
      // })
      GetProduct(props.location.query.values.productId).then((res)=>{
        setProduct(res.data)
        var params={productId:props.location.query.values.productId,productVesionId:props.location.query.values.id,isDefault:true,current:1,pageSize:10}
        LoadfunData(params)
        LoadtopisData(params);
      })
    }
   
  }, [tabStatus])
  const Btn = (record) => {
    var arr = [];
    if (record.type == 1) {
      arr.push(<a
        key="config"
        onClick={() => {
          setactionFormModalVisible(true);
          setCurrentRow(record);
          actionRef.current?.reloadAndRest?.();
        }}
      >
         参数配置
      </a>);
    }
    arr.push(
      <a
      key="config"
      onClick={() => {
        handleModalVisible(true);
        setCurrentRow(record);
        actionRef.current?.reloadAndRest?.();
      }}
    >
      更新
    </a>
    )
    arr.push(
      <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            handleRemove([record.id]);
            actionRef.current?.reloadAndRest();
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
      </Popconfirm>);

    return arr;
  }
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '功能名称',
      dataIndex: 'name',
      valueType: 'textarea',
      ellipsis: true,
      search: true,
    },
    {
      title: '功能类型',
      dataIndex: 'type',
      valueType: 'select',
      ellipsis: true,
      search: true,
      valueEnum: {
        0: {
          text: '属性',
        },
        1: {
          text: '服务',
        },
      },
    },
    // {
    //   title: '版本',
    //   dataIndex: 'vesion',
    //   valueType: 'select',
    //   ellipsis: true,
    //   search: true,
    //   valueEnum:DeviceVesionEnum
    // },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 400,
      render: (_, record) =>Btn(record),
    },
  ];
  const topicscolumns=[
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: 'Topics类',
      dataIndex: 'topics',
      valueType: 'textarea',
      with:500,
      render: (text) => <Paragraph style={{display:'inline'}} copyable>{text}</Paragraph>,
    },
    {
      title: '类型',
      dataIndex: 'topicsType',
      valueType: 'select',
      ellipsis: true,
      search: true,
      valueEnum: {
        0: {
          text: '发布',
        },
        1: {
          text: '订阅',
        },
        2: {
          text: '发布和订阅',
        },
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
      ellipsis: true,
      search: false,
      with:350,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 250,
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setcreateTopisModalVisible(true);
            setcurrenttopsRow(record);
          }} > 更新</a>,
              <Popconfirm
              type="primary"
              key="primary"
              title="确认删除吗？"
              okText="是"
              cancelText="否"
              onConfirm={ async() => {
                await deleteproducttopics([record.id]).then((r) => {
  
                  message.success('删除成功，即将刷新');
                  var params={productId:props.location.query.values.productId,current:1,pageSize:10}
                  LoadtopisData(params)
                });
              }}
              onCancel={() => { }}
            >
              <a href="#">删除</a>
            </Popconfirm>,
         
      ],
    },
  ]
  const topicsmrcolumns=[
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: 'Topics类',
      dataIndex: 'topics',
      valueType: 'textarea',
      with:500,
      render: (text) => <Paragraph style={{display:'inline'}} copyable>{text}</Paragraph>,
    },
    {
      title: '类型',
      dataIndex: 'topicsType',
      valueType: 'select',
      ellipsis: true,
      search: true,
      valueEnum: {
        0: {
          text: '发布',
        },
        1: {
          text: '订阅',
        },
        2: {
          text: '发布和订阅',
        },
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
      ellipsis: true,
      search: false,
      with:350,
    },
  ]
  const operationTabList = [
    {
      key: 'basis',
      tab: '功能',
    },
    {
      key: 'topis',
      tab: 'topics类列表',
    },
   
  ];
  /**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields) => {
  try {
    var check=true;
    console.log(fields)
    //var parm=JSON.stringify(fields)
    if(fields.dataType=="select"){
      if(!fields.enumvaluelist){
        message.error('请添加枚举值');
        check=false;
      }else{
        fields.enumValue=JSON.stringify(fields.enumvaluelist)
      }
    }
    if(fields.type==1){
      fields.dataType="";
    }
    if(check){
      if(fields.dataJson!=undefined){
        fields.dataJson=JSON.parse(fields.dataJson)
      }
      
      await addgoodstechnology(JSON.stringify(fields)).then((r) => {
        if (r.data) {
          message.success('添加成功');
          var params={productId:props.location.query.values.productId,deviceTypeKey:props.location.query.values.productId,current:1,pageSize:10}
          LoadfunData(params)
          handleModalVisible(false);
          if (actionRef.current) {
            actionRef.current.reloadAndRest();
          }
        } else {
          message.error(r.errors);
        }
      });
    }
  } catch (error) {
    message.error('添加失败请重试！');
  }
};
/**
 * 批量删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (ids) => {
  try {
    deletegoodstechnology(ids).then((r) => {
      if (r.data) {
        message.success('删除成功');
        var params={productId:props.location.query.values.productId,deviceTypeKey:props.location.query.values.productId,current:1,pageSize:10}
        LoadfunData(params)
      } else {
        message.error(r.errors);
      }
    });
    return true;
  } catch (error) {
    message.error('删除失败，请重试');
  }
};
  const handleUpdate = async (fields) => {
    try {
      var check=true;
      if(fields.dataType=="select"){
        if(fields.enumvaluelist.length==0){
          message.error('请添加枚举值');
          check=false;
        }else{
          fields.enumValue=JSON.stringify(fields.enumvaluelist)
        }
      }
      if(check){
        updategoodstechnology(fields).then((r) => {
          if (r.data) {
            message.success('修改成功');
            var params={productId:props.location.query.values.productId,deviceTypeKey:props.location.query.values.productId,current:1,pageSize:10}
            LoadfunData(params)
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reloadAndRest();
            }
          } else {
            message.error(r.errors);
          }
        });
      }
    } catch (error) {
      message.error('修改失败请重试！');
    }
  };
  const LoadtopisData= async(params)=>{
    await getproducttopicspage(params).then((r) => {
      setdataSource( r.data.data)
      settotal( r.data.total)
    });
  }
  const LoadfunData= async(params)=>{
    await getGoodstechnologypage(params).then((r) => {
      setdatafunctionSource( r.data.data)
      settotalfun( r.data.total)
    });
  }
  const onTabChange = (key) => {
    console.log(key)
    seTabStatus({ operationKey: key, tabActiveKey: key });
    // if(key=="topis"){
    //   var params={productId:props.location.query.values.id,current:1,pageSize:10}
    //   //LoadtopisData(params)
     
    // }else{
    //   var params={productId:props.location.query.values.id,current:1,pageSize:10}
    //   //LoadfunData(params)
    // }
    // //initGoodsType()
  };
  const onTabsChange=(key)=> {
    console.log(key)
    var params={}
    if(key=="1"){
      params.productId=props.location.query.values.productId
      params.productVesionId=props.location.query.values.id
      params.isDefault=true;
      params.current=1;
      params.pageSize=10
      LoadtopisData(params)
    }else{
      //actiontopisRef.current.reload();
     
      params.productId=props.location.query.values.productId
      params.productVesionId=props.location.query.values.id
      params.isDefault=false;
      params.current=1;
      params.pageSize=10
      LoadtopisData(params)
    }
  }
  const zdytopicslist={
    zdy: (
      <ProTable
      id="table1"
      actionRef={actiontopisRef}
      rowKey="id"
      pagination={{ defaultPageSize: 10,total:total }}
      search={{labelWidth: 120}}
      columns={topicscolumns}
      toolBarRender={() => [
        <Button
          type="primary"
          key="primary"
          onClick={() => {
            setcreateTopisModalVisible(true);
            setcurrenttopsRow({});
          }}
        >
          <PlusOutlined /> 新建
        </Button>,
     
      ]}
      //数据绑定
      dataSource={dataSource}
      request={async (params) => {
        var data = [];
        var total = 0;
        params.productId=props.location.query.values.productId
        params.productVesionId=props.location.query.values.id
        params.isDefault=false;
        await getproducttopicspage(params).then((r) => {
          setdataSource( r.data.data)
          data = r.data.data;
          total = r.data.total;
        });
        return {
          data: data,
          success: true,
          total: total,
        };
      }}
      // 每行选择点击事件
      rowSelection={{
        onChange: (_, selectedRows) => {
          setSelectedRows(selectedRows);
        },
      }}
    />
    ),
    mr:(
      <ProTable
      id="table3"
      actionRef={actiontopismrRef}
      rowKey="id"
      search={false}
      pagination={{ defaultPageSize: 10,total:total }}
      columns={topicsmrcolumns}
      toolBarRender={false}
      //数据绑定
      dataSource={dataSource}
      request={async (params) => {
        var data = [];
        var total = 0;
        params.productId=props.location.query.values.productId
        params.productVesionId=props.location.query.values.id
        params.isDefault=true;
        await getproducttopicspage(params).then((r) => {
          setdataSource( r.data.data)
          data = r.data.data;
          total = r.data.total;
        });
        return {
          data: data,
          success: true,
          total: total,
        };
      }}
    />
    )
  };
  const items=[{
    key: '1',
    label: '默认topics',
    children: zdytopicslist.mr,
  },
  {
    key: '2',
    label: '自定义topics',
    children:  zdytopicslist.zdy
  }]
  
  const contentList = {
    basis: (
      <Card style={{marginBottom: 24}} bordered={false}>
        <ProTable
          id="table2"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{labelWidth: 120}}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
              setCurrentRow({});
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
          //   <Button
          //   key="primary"
          //   onClick={async  () => {
               
          //       const link = document.createElement('a');
          //       link.href = "https://hbl-test-1305371387.cos.ap-chengdu.myqcloud.com//Franchisee/gzaxn@163.com/goods/133458884696092845.xlsx";
          //       link.click();  
          //   }}
          // >
          //   <UploadOutlined /> 下载设备版本工艺模板
          // </Button>,
          //  <Upload {...props}>
          //  <Button icon={<UploadOutlined />}>导入工艺模版</Button>
        //  </Upload>
        ]}
        dataSource={datafunctionSource}
        //数据绑定
        request={async (params) => {
          var data = [];
          var total = 0;
          params.productId=props.location.query.values.productId
          params.productVesionId=props.location.query.values.id
          await getGoodstechnologypage(params).then((r) => {
            data = r.data.data;
            setdatafunctionSource( r.data.data)
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        // 每行选择点击事件
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      ></ProTable>
      <CreateForm
        onFinish={async (value) => {
          console.log("jnlaile ")
          console.log(value)
          value.productId=props.location.query.values.productId
          value.deviceVersionKey=props.location.query.values.id;
          if (value.id) {
           await handleUpdate(value);
          } else {  
           await handleAdd(value);
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
        // DeviceVesionData={DeviceVesionData}
      />
      <ActionForm actionFormModalVisible={actionFormModalVisible}
      values={currentRow || {} }
      onCancel={() => {
        setCurrentRow(undefined);
        setactionFormModalVisible(false);
      }}
      />
      </Card>
    ),
    topis: (
      <Card style={{marginBottom: 24}} bordered={false}>
           <Tabs tabPosition='left' items={items} onChange={onTabsChange}/>
       
      <CreateTopis createModalVisible={createTopisModalVisible} productCode={Product.key} productVesion={props.location.query.values?.vesion}
        values={currenttopsRow || {}}
        onFinish={async (value) => {
          value.productId=props.location.query.values.productId
          value.productVesionId=props.location.query.values.id
          if (value.id) {
            await updateproducttopics(value).then((r)=>{
              if (r.data) {
                message.success('修改成功');
                actiontopisRef.current.reload();
                setcreateTopisModalVisible(false)
                //var params={productId:props.location.query.values.productId,current:1,pageSize:10}
                //LoadtopisData(params)
              } else {
                message.error(r.errors);
              }
            })
          }else{
            await addproducttopics(value).then((r)=>{
              if (r.data) {
                message.success('添加成功');
                actiontopisRef.current.reload();
                // var params={productId:props.location.query.values.productId,current:1,pageSize:10}
                // LoadtopisData(params)
                setcreateTopisModalVisible(false)
              } else {
                message.error(r.errors);
              }
            })
          }
        }}
        onCancel={() => {
          setcurrenttopsRow(undefined);
          setcreateTopisModalVisible(false);
        }}
        ></CreateTopis>
      </Card>
     
    ),
  
  };
  return (
    <PageContainer  host header={{
      title: [<a  key="back"
      onClick={() => {
        history.push({
          pathname: '/device/deviceVesion',
        });
      }}><ArrowLeftOutlined />返回</a>,
      <div style={{backgroundColor:'#f3eaea',width:'1640px',height: '54px'}}>
      <div style={{fontSize: '14px',color: 'cornflowerblue'}}>
      <span style={{marginRight:20,marginLeft:10,marginTop:10,float:'left' }}>产品版本:<span style={{marginLeft:10}}>{props.location.query.values?.vesion}</span></span>
        <span style={{marginRight:20,marginLeft:10,marginTop:10,float:'left' }}>产品名称:<span style={{marginLeft:10}}>{Product?.name}</span></span>
        <span style={{marginRight:120,marginLeft:10,marginTop:10,float:'right'}}>产品key: <Paragraph style={{display:'inline'}} copyable>{Product?.key}</Paragraph></span></div>
      </div>
    ],
      breadcrumb: {},
    }}
    title={props.location.query.isAdd ? '商品新增' : '详情'}
    tabActiveKey={currTabKey}
    onTabChange={onTabChange}
    tabList={operationTabList}
    >
      
      {contentList[tabStatus.operationKey]}
    </PageContainer>
  );
};

export default bomtechnology;
