import * as React from 'react';
import Box from "@mui/material/Box";
import Table from 'rsuite/Table';
import 'rsuite/Table/styles/index.css';
import Checkbox from 'rsuite/Checkbox';
import 'rsuite/Checkbox/styles/index.css';
import { CustomProvider, Input, InputNumber } from 'rsuite';
import 'rsuite/InputNumber/styles/index.css';
import zhCN from 'rsuite/locales/zh_CN';
import { Grid } from '@mui/material';
import Tooltip from '@mui/material/Tooltip';
import AddIcon from '@mui/icons-material/Add';
import Typography from '@mui/material/Typography';

import DeleteIcon from '@mui/icons-material/DeleteOutlined';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import Tab from "@mui/material/Tab";
import TabContext from "@mui/lab/TabContext";
import TabList from "@mui/lab/TabList";
import TabPanel from "@mui/lab/TabPanel";
import Stack from "@mui/material/Stack";
import Service from './Service';
import Button from '@mui/material/Button';
import ButtonGroup from '@mui/material/ButtonGroup';
import {extractFuzhu} from './utils';
import {shanchu, undo, redo, danxiangdinge, updateDercj, changguidinge, handleBeizhu, huan, updateShuliang, handleYuban, updateDeMingcheng, handleRcjbc} from './editor';

import { DataGrid, GridActionsCellItem, zhCN as zhCN_MUI, GridToolbarContainer } from '@mui/x-data-grid';


import { v4 as uuidv4 } from 'uuid';

import {copy} from './utils';


import {TabulatorFull as Tabulator} from "tabulator-tables"; //import Tabulator library
import './Tabulator.css';
const {Column, HeaderCell, Cell} = Table;


/**
 * 
本条规定了工程量清单编码的表示方式：十二位阿拉伯数字及其设置规定。
各位数字的含义是：一、二位为专业工程代码（01—房屋建筑与装饰工程；02—仿古建筑工程；
03—通用安装工程；04—市政工程；05—园林绿化工程；06—矿山工程；07—构筑物工程；08—城市
轨道交通工程；09—爆破工程。以后进入国标的专业工程代码以此类推）；三、四位为附录分类顺序码；
五、六位为分部工程顺序码；七、八、九位为分项工程项目名称顺序码；十至十二位为清单项目名称
顺序码。
 */








export default function Qingdan3({name, bh, bt,  beizhu/*后台传回来的附注信息，要整理后才能成为展示用的行*/ , beizhuFK, clickCallback, loadingCallback, dingeclick, tihuanCallback, tihuanClick, bctihuanClick, bctihuanCallback, suanshiCallback}) {
    
     const myTable = React.useRef(null);
     const myRef = React.useRef(null);
     const [valueTab, setValueTab] = React.useState("1");
     const handleChange = (event, newValue) => {
          setValueTab(newValue);
        };
     const onCellDoubleClick = (params, event, detail) => {
         
          if (params.field == '人材机编码') {
               console.log(params);
               bctihuanCallback(params.id);
          }
     };
     const [rcjhl, setRcjhl] = React.useState([]);
     const [rcjhl2, setRcjhl2] = React.useState([]);
     const [fuzhu, setFuzhu] = React.useState([]);//展示用的附注行
     const [tuijian, setTuijian] = React.useState([]);
     const [fuzhuEnable, setFuzhuEnable] = React.useState(false);
     const [yubanEnable, setYubanEnable] = React.useState(false);

     const highlight = React.useRef([]);
     const debmRef = React.useRef(null);

     const tuijianRef = React.useRef(null);
     const tuijianTable = React.useRef(null);
     const rcj2Ref = React.useRef(null);
     const rcj2Table = React.useRef(null);
     const rcjRef = React.useRef(null);
     const rcjTable = React.useRef(null);
     const [detail, setDetail] = React.useState([
                    
     ]);

     const selectedRowKeysTable = React.useRef([]);
     const selectedRowKeysTableParent = React.useRef(null);
     const beizhuFKRef = React.useRef(null);


     const rgdeRef = React.useRef(null);
     const jxdeRef = React.useRef(null);
     const cldeRef = React.useRef(null);
     const isQdrcj = React.useRef(false);
     ///备注
     const onSelectChange = (newSelectedRowKeys) => {
          const [newData, newHl] = handleBeizhu(beizhuFKRef.current, selectedRowKeysTable.current[0], newSelectedRowKeys, fuzhu);
                                       if (newData) {
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                                          myTable.current.deselectRow();
                                          myTable.current.updateData(newData.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
                                            myTable.current.element.children[1].scrollTop = former;
                                            myTable.current.element.children[1].scrollLeft = former2;
                                              let getRow = myTable.current.getRows(); //get array of currently selected row components.
                                              let component = null;
                                              for(let i = 0; i < getRow.length; i++) {
                                                   let entry = getRow[i]._row.modules.dataTree.children;
                                                   for(let j = 0; j < entry.length; j++) {
                                                        let child = entry[j];
                                                        if(child.data['key'] == selectedRowKeysTable.current[0]) {
                                                             component = child.component;
                                                             break;
                                                        }
                                                        
                                                   }

                                              }
                                              component.select();
                                          
                                          });
                                          let y =[];
                                          for (let i = 1; i < newHl.length; i++) {
                                            y.push({
                                          'ID' : newHl[i][0],
                                          '人材机编码' : newHl[i][1],
                                          '名称' : newHl[i][2],
                                          '规格型号': newHl[i][3],
                                          '单位' : newHl[i][4],
                                          '单价' : newHl[i][5],
                                          '产地' : newHl[i][6],
                                          '供应厂商' : newHl[i][7],
                                          '人材机类别' : newHl[i][8],
                                          '甲供标志': newHl[i][9],
                                          '含量' : newHl[i][10],
                                          '合价' : newHl[i][11],
                                          '暂估价标志' : newHl[i][12],
                                          '主要材料标志' : newHl[i][13],
                                          '主材标志' : newHl[i][14],
                                          '设备标志' : newHl[i][15] ,
                                          'key' : newHl[i][16],
                                          'bc': newHl[i][17]

                                          });
                                        }
                                         setRcjhl(y);
                                         if (rcjTable.current) {
                                            rcjTable.current.replaceData(y);
                                         }
     
                                       }
        };

        //预拌砂浆
        const onSelectChange2 = (event) => {
          
          setValueYuban(event.target.value);
          const [newData, newHl]  = handleYuban(selectedRowKeysTable.current[0], [event.target.value]);
          if (newData) {
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                                          myTable.current.deselectRow();
               myTable.current.updateData(newData.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
               
                                            myTable.current.element.children[1].scrollTop = former;
                                            myTable.current.element.children[1].scrollLeft = former2;
                                              let getRow = myTable.current.getRows(); //get array of currently selected row components.
                                              let component = null;
                                              for(let i = 0; i < getRow.length; i++) {
                                                   let entry = getRow[i]._row.modules.dataTree.children;
                                                   for(let j = 0; j < entry.length; j++) {
                                                        let child = entry[j];
                                                        if(child.data['key'] == selectedRowKeysTable.current[0]) {
                                                             component = child.component;
                                                             break;
                                                        }
                                                        
                                                   }

                                              }
                                              component.select();
              
               
                });
               let y =[];
               for (let i = 1; i < newHl.length; i++) {
                 y.push({
               'ID' : newHl[i][0],
               '人材机编码' : newHl[i][1],
               '名称' : newHl[i][2],
               '规格型号': newHl[i][3],
               '单位' : newHl[i][4],
               '单价' : newHl[i][5],
               '产地' : newHl[i][6],
               '供应厂商' : newHl[i][7],
               '人材机类别' : newHl[i][8],
               '甲供标志': newHl[i][9],
               '含量' : newHl[i][10],
               '合价' : newHl[i][11],
               '暂估价标志' : newHl[i][12],
               '主要材料标志' : newHl[i][13],
               '主材标志' : newHl[i][14],
               '设备标志' : newHl[i][15] ,
               'key' : newHl[i][16],
               'bc': newHl[i][17]

               });
             }
              setRcjhl(y);
              if (rcjTable.current) {
                 rcjTable.current.replaceData(y);
              }

            }
        
        };


     /**fuzhu select */
    
     const [checked, setChecked] = React.useState(false);
     const [indeterminate, setIndeterminate] = React.useState(false);
     const [checkedKeys, setCheckedKeys] = React.useState([]);
     const setCheckedKeys_ = (keys) => {
      setCheckedKeys(keys);
      if (keys.length == fuzhu.length) {
           setChecked(true);
           setIndeterminate(false);
      } else if (keys.length == 0) {
           setChecked(false);
           setIndeterminate(false);
      } else {
           setIndeterminate(true);
           setChecked(false);
      }
      onSelectChange(keys);
     };
     const setCheckedKeys_2 = (keys) => {
      setCheckedKeys(keys);
      if (keys.length == fuzhu.length) {
           setChecked(true);
           setIndeterminate(false);
      } else if (keys.length == 0) {
           setChecked(false);
           setIndeterminate(false);
      } else {
           setIndeterminate(true);
           setChecked(false);
      }
      //onSelectChange(keys);
     };
     const handleCheckAll = (value, checked) => {
      const keys = checked? fuzhu.map(item => item.id) : [];
      setCheckedKeys_(keys);
 
     }
     const handleCheck = (value, checked) => {
      const keys = checked? [...checkedKeys, value] : checkedKeys.filter(item => item != value);
      setCheckedKeys_(keys);
 
     }
 
     const CheckCell = ({rowData, onChange, checkedKeys, dataKey, disabled, ...props}) => {
       return <Cell {...props} style={{ padding: 0}}>
           <div style={{lineHeight: '40px'}}>
              <Checkbox value = {rowData[dataKey]}
              inline
              disabled={disabled}
              onChange={onChange}
              checked={checkedKeys.some(item => 
               { 
                    
                    let hit = item === rowData[dataKey];
                    
                 return   hit;
               })}
              ></Checkbox>
           </div>
       </Cell>
     };

   

     const [valueYuban, setValueYuban] = React.useState("");


     var editCheck = function(cell){
          //cell - the cell component for the editable cell
      
          //get row data
          //console.log(cell);
          if(cell._cell.row.data['序号']) return false;
          return true;
      }

      var editCheckJg = function(cell){
          //cell - the cell component for the editable cell
      
          //get row data
          //console.log(cell);
          if(isQdrcj.current) return false;
          //if (cell._cell.row.getData()['人材机编码'].includes('10000F')) {
          //     return false;
          //}
          if (cell._cell.row.getData()['人材机编码'].includes('000FE')) {////安装费用
               return false;
          }
          if (cell._cell.row.getData()['人材机编码'] == '00EXP001') {//回程费
               return false;
          }
          if (cell._cell.row.getData()['人材机编码'] == '99EXP007') {//
               return false;
          }
          if (cell._cell.row.getData()['人材机编码'] == '99EXP022') {//
               return false;
          }
          if (cell._cell.row.getData()['人材机编码'] == '31130104') {//
               return false;
          }
          if (cell._cell.row.getData()['甲供标志'] == 'true') {
               return false;
          }

          return true;
      }
      var editCheckRcj = function(cell){
          //cell - the cell component for the editable cell
      
          //get row data
          //console.log(cell);
          if(isQdrcj.current) return false;
          //if (cell._cell.row.getData()['人材机编码'].includes('10000F')) {
          //     return false;
          //}
          if (cell._cell.row.getData()['人材机编码'].includes('000FE')) {//安装费用
               return false;
          }
          if (cell._cell.row.getData()['人材机编码'] == '00EXP001') {//回程费
               return false;
          }
          if (cell._cell.row.getData()['人材机编码'] == '99EXP007') {//
               return false;
          }
          if (cell._cell.row.getData()['人材机编码'] == '99EXP022') {//
               return false;
          }
          if (cell._cell.row.getData()['人材机编码'] == '31130104') {//
               return false;
          }
          

          return true;
      }


     var sparklineFormatter = function(cell, formatterParams, onRendered){
          for (let i = 0; i < highlight.current.length; i++) {
               let entry = highlight.current[i];
               if (entry.row + 1 == cell._cell.row.position && entry.col + 1 == cell._cell.column.getPosition()) {
                    cell.getElement().style.fontWeight = 'bold';
                    cell.getElement().style.color = 'green';
                    cell.getElement().style.background = '#d7f1e1';
               }
              }
              return Number(cell.getValue()).toFixed(2).toString(); 
          };

     var sparklineFormatter2 = function(cell, formatterParams, onRendered){
               for (let i = 0; i < highlight.current.length; i++) {
                    let entry = highlight.current[i];
                    if (entry.row + 1 == cell._cell.row.position && entry.col + 1 == cell._cell.column.getPosition()) {
                         cell.getElement().style.fontWeight = 'bold';
                         cell.getElement().style.color = 'green';
                         cell.getElement().style.background = '#d7f1e1';
                    }
                   }
                   return cell.getValue(); 
               };



     const resetUI = () => {
          selectedRowKeysTable.current = [];
          selectedRowKeysTableParent.current = null;
               setRcjhl([]);
               if (rcjTable.current) {
                    rcjTable.current.replaceData([]);
               }
               setFuzhu([]);
               setRcjrows([]);
               setShowToolbar(false);
               setValueYuban("");
               setYubanEnable(false);
               isQdrcj.current = true;
               highlight.current = [];
               setTuijian([]);
               if (tuijianTable.current) tuijianTable.current.replaceData([]);
     };

      function handleSelect(row){
          selectedRowKeysTable.current = [row._row['data']['key']];
          if (row._row.data['序号'] != null && row._row.data['序号'].length >0) {
               selectedRowKeysTableParent.current = row._row['data']['key'];

               setFuzhu([]);
               setRcjrows([]);//补充人材机
               setYubanEnable(false);
               setValueYuban("");
               setShowToolbar(false);
               Service.generateQingdanrcj(name, bh,bt,row._row.data['清单编码']).then(x=>{
                
                
                    let y =[];
                    for (let i = 1; i < x.length; i++) {
                         y.push({
                              'ID' : x[i][0],
                              '人材机编码' : x[i][1],
                              '名称' : x[i][2],
                              '规格型号': x[i][3],
                              '单位' : x[i][4],
                              '单价' : x[i][5],
                              '产地' : x[i][6],
                              '供应厂商' : x[i][7],
                              '人材机类别' : x[i][8],
                              '甲供标志': x[i][9],
                              '含量' : x[i][10],
                              '合价' : x[i][11],
                              '暂估价标志' : x[i][12],
                              '主要材料标志' : x[i][13],
                              '主材标志' : x[i][14],
                              '设备标志' : x[i][15] ,
                              'key' : '',
                              'bc': ''

                         });
                    }
                    setRcjhl(y);
                    if (rcjTable.current) {
                         rcjTable.current.replaceData(y);
                    }
                
                  isQdrcj.current = true;
                  highlight.current = [];
               });
               Service.generateQingdanTuijian(name, bh,bt,row._row.data['清单编码']).then(x=>{
                setTuijian(x);
                if (tuijianTable.current) tuijianTable.current.replaceData(x);
                
             });
          }else{
               setTuijian([]);
               if (tuijianTable.current) tuijianTable.current.replaceData([]);
              let row_parent = row._row;
              while(row_parent.modules.dataTree.parent) {
                   row_parent = row_parent.modules.dataTree.parent;
              }
              

               //console.log(name, bh,bt,qdbm, selected[1]);
               debmRef.current = row._row['data']['清单编码'];
               selectedRowKeysTableParent.current = row_parent['data']['key'];
               let qdbm = row_parent['data']['清单编码'];
               let debm = row._row['data']['清单编码'];
               console.log('debm=');
               console.log(debm);
               let danwei = row._row['data']['单位'];

               clickCallback(bt, qdbm, debm, row._row['data']['名称']);/**dingercj need row key */
               Service.generateDingercj(name, bh,bt,qdbm, debm, danwei, row._row['data']['key']).then(x=>{
                 console.log(x);
                 let y =[];
                              for (let i = 1; i < x[0].length; i++) {
                                   y.push({
                                        'ID' : x[0][i][0],
                                        '人材机编码' : x[0][i][1],
                                        '名称' : x[0][i][2],
                                        '规格型号': x[0][i][3],
                                        '单位' : x[0][i][4],
                                        '单价' : x[0][i][5],
                                        '产地' : x[0][i][6],
                                        '供应厂商' : x[0][i][7],
                                        '人材机类别' : x[0][i][8],
                                        '甲供标志': x[0][i][9],
                                        '含量' : x[0][i][10],
                                        '合价' : x[0][i][11],
                                        '暂估价标志' : x[0][i][12],
                                        '主要材料标志' : x[0][i][13],
                                        '主材标志' : x[0][i][14],
                                        '设备标志' : x[0][i][15] ,
                                        'key' : x[0][i][16],
                                        'bc': x[0][i][17]
          
                                   });
                              }
                              setRcjhl(y);
                              if (rcjTable.current) {
                                   rcjTable.current.replaceData(y);
                              }
                 setShowToolbar(true);
                 setFuzhuEnable(x[1]);
                 setYubanEnable(x[1]);
                 if (x[2]== null || x[2].length == 0) {
                    setValueYuban("");
                 } else {
                    setValueYuban(x[2][0]);
                 }
                 setRcjrows(x[3]);//buchongrcj
                 //hotRcjRef.current?.hotInstance?.loadData(x);
                 isQdrcj.current = false;
                 let toHighlight = [];
                 highlight.current = toHighlight;
               });

          }

      }

     /**补充人材机 */
     const [rcjrows, setRcjrows] = React.useState([]);
     const [showToolbar, setShowToolbar] = React.useState(false);
     const rcjcolumns = [
          {
               field: 'actions',
               type: 'actions',
               headerName: '操作',
               width: 100,
               cellClassName: 'actions',
               getActions: ({ id }) => {
                
         
                
         
                 return [
               
                   <GridActionsCellItem
                     icon={<DeleteIcon />}
                     label="Delete"
                     onClick={handleDeleteClick(id)}
                     color="inherit"
                   />,
                 ];
               },
             },
          { field: '人材机编码', headerName: '人材机编码', width: 120, editable: false },
          {
            field: '名称',
            headerName: '名称',
            width: 120,
            align: 'left',
            headerAlign: 'left',
            editable: true,
          },
          {
            field: '规格型号',
            headerName: '规格型号',
            width: 100,
            editable: true,
          },
          {
            field: '单位',
            headerName: '单位',
            width: 80,
            editable: true,
          },
          {
               field: '单价',
               headerName: '单价',
               width: 80,
               editable: true,
             },
             {
               field: '产地',
               headerName: '产地',
               width: 80,
               editable: true,
             },
             {
               field: '供应厂商',
               headerName: '供应厂商',
               width: 80,
               editable: true,
             },
          {
               field: '人材机类别',
               headerName: '人材机类别',
               width: 120,
               editable: false,
             },
             {
               field: '甲供标志',
               headerName: '甲供标志',
               width: 80,
               editable: true,
               type: 'singleSelect',
               valueOptions: ['true', 'false'] 
             },
             {
               field: '含量',
               headerName: '含量',
               width: 80,
               editable: true,
             },
            /* {
               field: '合价',
               headerName: '合价',
               width: 80,
               editable: true,
             },*/
             {
               field: '暂估价标志',
               headerName: '暂估价标志',
               width: 100,
               editable: true,
               type: 'singleSelect',
               valueOptions: ['true', 'false'] 
             },
             {
               field: '主要材料标志',
               headerName: '主要材料标志',
               width: 120,
               editable: true,
               type: 'singleSelect',
               valueOptions: ['true', 'false'] 
             },
             {
               field: '主材标志',
               headerName: '主材标志',
               width: 80,
               editable: true,
               type: 'singleSelect',
               valueOptions: ['true', 'false'] 
             },
             {
               field: '设备标志',
               headerName: '设备标志',
               width: 80,
               editable: true,
               type: 'singleSelect',
               valueOptions: ['true', 'false'] 
             },
       
        ];

    
      
        const handleDeleteClick = (id) => () => {
          setRcjrows(rcjrows.filter((row) => row.id !== id));
          const [newData, newHl] = handleRcjbc(selectedRowKeysTable.current[0], rcjrows.filter((row) => row.id !== id));
          if (newData) {
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                                          myTable.current.deselectRow();
               myTable.current.updateData(newData.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
                                            myTable.current.element.children[1].scrollTop = former;
                                            myTable.current.element.children[1].scrollLeft = former2;
                                              let getRow = myTable.current.getRows(); //get array of currently selected row components.
                                              let component = null;
                                              for(let i = 0; i < getRow.length; i++) {
                                                   let entry = getRow[i]._row.modules.dataTree.children;
                                                   for(let j = 0; j < entry.length; j++) {
                                                        let child = entry[j];
                                                        if(child.data['key'] == selectedRowKeysTable.current[0]) {
                                                             component = child.component;
                                                             break;
                                                        }
                                                        
                                                   }

                                              }
                                              component.select();

               });
               let y =[];
               for (let i = 1; i < newHl.length; i++) {
                 y.push({
               'ID' : newHl[i][0],
               '人材机编码' : newHl[i][1],
               '名称' : newHl[i][2],
               '规格型号': newHl[i][3],
               '单位' : newHl[i][4],
               '单价' : newHl[i][5],
               '产地' : newHl[i][6],
               '供应厂商' : newHl[i][7],
               '人材机类别' : newHl[i][8],
               '甲供标志': newHl[i][9],
               '含量' : newHl[i][10],
               '合价' : newHl[i][11],
               '暂估价标志' : newHl[i][12],
               '主要材料标志' : newHl[i][13],
               '主材标志' : newHl[i][14],
               '设备标志' : newHl[i][15],
               'key' : newHl[i][16],
               'bc': newHl[i][17]

               });
             }
              setRcjhl(y);
              if (rcjTable.current) {
                 rcjTable.current.replaceData(y);
              }

            }

        };
      
      
        const processRowUpdate = (newRow) => {
          const updatedRow = { ...newRow, isNew: false };
          setRcjrows(rcjrows.map((row) => (row.id === newRow.id ? updatedRow : row)));
          const [newData, newHl] = handleRcjbc(selectedRowKeysTable.current[0], rcjrows.map((row) => (row.id === newRow.id ? updatedRow : row)));
          if (newData) {
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                                          myTable.current.deselectRow();
               myTable.current.updateData(newData.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
                                            myTable.current.element.children[1].scrollTop = former;
                                            myTable.current.element.children[1].scrollLeft = former2;
                                              let getRow = myTable.current.getRows(); //get array of currently selected row components.
                                              let component = null;
                                              for(let i = 0; i < getRow.length; i++) {
                                                   let entry = getRow[i]._row.modules.dataTree.children;
                                                   for(let j = 0; j < entry.length; j++) {
                                                        let child = entry[j];
                                                        if(child.data['key'] == selectedRowKeysTable.current[0]) {
                                                             component = child.component;
                                                             break;
                                                        }
                                                        
                                                   }

                                              }
                                              component.select();

               });
               let y =[];
               for (let i = 1; i < newHl.length; i++) {
                 y.push({
               'ID' : newHl[i][0],
               '人材机编码' : newHl[i][1],
               '名称' : newHl[i][2],
               '规格型号': newHl[i][3],
               '单位' : newHl[i][4],
               '单价' : newHl[i][5],
               '产地' : newHl[i][6],
               '供应厂商' : newHl[i][7],
               '人材机类别' : newHl[i][8],
               '甲供标志': newHl[i][9],
               '含量' : newHl[i][10],
               '合价' : newHl[i][11],
               '暂估价标志' : newHl[i][12],
               '主要材料标志' : newHl[i][13],
               '主材标志' : newHl[i][14],
               '设备标志' : newHl[i][15] ,
               'key' : newHl[i][16],
               'bc': newHl[i][17]

               });
             }
              setRcjhl(y);
              if (rcjTable.current) {
                 rcjTable.current.replaceData(y);
              }

            }
          return updatedRow;
        };

        function EditToolbar(props) {
          const { setRcjrows } = props;
        
          const handleClick = () => {
            const id = uuidv4();
            let a = [];
            let temp = debmRef.current;
            let temp2 = temp.split('-')[0];
            setRcjrows((oldRows) => {
               a = [
                 ...oldRows,
                 { id, '人材机编码': temp2.concat('10000F'), '名称': '', '规格型号': '', '单位': '', '单价':'0','产地': '', '供应厂商': '', '人材机类别':'2',
                '甲供标志':'', '含量':'1', '暂估价标志':'', '主要材料标志':'true', '主材标志':'true', '设备标志':'' },
               ];
               return a;
             });
             const [newData, newHl] = handleRcjbc(selectedRowKeysTable.current[0], a);
             if (newData) {
               let former = myTable.current.element.children[1].scrollTop;
               let former2 = myTable.current.element.children[1].scrollLeft;
               myTable.current.deselectRow();
               myTable.current.updateData(newData.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
                       myTable.current.element.children[1].scrollTop = former;
                       myTable.current.element.children[1].scrollLeft = former2;
                         let getRow = myTable.current.getRows(); //get array of currently selected row components.
                         let component = null;
                         for(let i = 0; i < getRow.length; i++) {
                              let entry = getRow[i]._row.modules.dataTree.children;
                              for(let j = 0; j < entry.length; j++) {
                                   let child = entry[j];
                                   if(child.data['key'] == selectedRowKeysTable.current[0]) {
                                        component = child.component;
                                        break;
                                   }
                                   
                              }

                         }
                         component.select();
               });
               let y =[];
               for (let i = 1; i < newHl.length; i++) {
                 y.push({
               'ID' : newHl[i][0],
               '人材机编码' : newHl[i][1],
               '名称' : newHl[i][2],
               '规格型号': newHl[i][3],
               '单位' : newHl[i][4],
               '单价' : newHl[i][5],
               '产地' : newHl[i][6],
               '供应厂商' : newHl[i][7],
               '人材机类别' : newHl[i][8],
               '甲供标志': newHl[i][9],
               '含量' : newHl[i][10],
               '合价' : newHl[i][11],
               '暂估价标志' : newHl[i][12],
               '主要材料标志' : newHl[i][13],
               '主材标志' : newHl[i][14],
               '设备标志' : newHl[i][15],
               'key' : newHl[i][16],
               'bc': newHl[i][17]

               });
             }
             setRcjhl(y);
              if (rcjTable.current) {
                 rcjTable.current.replaceData(y);
              }
          }
            
          };
        
          return (
            <GridToolbarContainer>
              <Button disabled={!showToolbar}
              color="primary" startIcon={<AddIcon />} onClick={handleClick}>
                补充
              </Button>
            </GridToolbarContainer>
          );
        }
   
    

   
     
    



     React.useEffect(() => {
        
          myTable.current = new Tabulator(myRef.current, {
               index: "key",
               height: 380,
               renderVertical: "basic",
             data: detail, //link data to table
             reactiveData: false, //enable data reactivity
             dataTreeStartExpanded:true,
             dataTree: true,
             selectableRows:1, //make rows selectable
             editTriggerEvent:"dblclick", //trigger edit on double click
             dataTreeStartExpanded:function(row, level){
                 return true; //expand rows where the "driver" data field is true;
             },
             columns: [ //Define Table Columns
                          {title:"序号", field:"序号", width:80, headerSort:false, frozen: true}, //never hide this column
                          {title:"清单编码", field:"清单编码", width:120,headerSort:false, frozen: true ,formatter:"textarea" },
                          {title:"名称", field:"名称", width:150, headerSort:false, formatter:"textarea", editor: "input", editable: editCheck}, //hide this column first
                          {title:"项目特征", field:"项目特征", width:200 , headerSort:false, formatter:"textarea"},
                          {title:"计算规则", field:"计算规则", width:300, headerSort:false, formatter:"textarea"},
                          {title:"单位", field:"单位", width:100, headerSort:false},
                          {title:"数量", field:"数量", width:100, headerSort:false, editor: "input", editable: editCheck },
                          {title:"综合单价", field:"综合单价", width:100, headerSort:false, formatter:"money"},
                          {title:"合价", field:"合价", width:100, headerSort:false, formatter:"money"},
                          {title:"人工费", field:"人工费", width:100, headerSort:false, formatter:"money"},
                          {title:"主材费", field:"主材费", width:100, headerSort:false, formatter:"money"},
                          {title:"设备费", field:"设备费", width:100, headerSort:false, formatter:"money"},
                          {title:"辅材费", field:"辅材费", width:100, headerSort:false, formatter:"money"},
                          {title:"材料费", field:"材料费", width:100, headerSort:false, formatter:"money"},
                          {title:"机械费", field:"机械费", width:100, headerSort:false, formatter:"money"},
                          {title:"管理费", field:"管理费", width:100, headerSort:false, formatter:"money"},
                          {title:"利润", field:"利润", width:100, headerSort:false, formatter:"money"},
                          {title:"暂估价", field:"暂估价", width:100, headerSort:false, formatter:"money"},
                          {title:"综合人工工日", field:"综合人工工日", width:100, headerSort:false},
                  ]
           }); 
           
           myTable.current.on("cellDblClick", function(e, cell){
               //e - the click event object
               //cell - cell component
               console.log(cell);
           });
     
           myTable.current.on("rowSelected", handleSelect);
           
     
           myTable.current.on("cellEdited", function(cell){
               let key = cell._cell.row.data['key'];
               myTable.current.deselectRow();
               if(cell._cell.column.field == '名称') {
                    let newData = updateDeMingcheng(cell._cell.row.data['名称'], selectedRowKeysTable.current[0]);
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                    myTable.current.updateData(newData.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function() {
                       myTable.current.element.children[1].scrollTop = former;
                       myTable.current.element.children[1].scrollLeft = former2;
                         let getRow = myTable.current.getRows(); //get array of currently selected row components.
                         let component = null;
                         for(let i = 0; i < getRow.length; i++) {
                              let entry = getRow[i]._row.modules.dataTree.children;
                              for(let j = 0; j < entry.length; j++) {
                                   let child = entry[j];
                                   if(child.data['key'] == key) {
                                        //console.log(child);
                                        component = child.component;
                                        break;
                                   }
                                   
                              }

                         }
                         component.select();
                     //    handleSelect(component);
                      });                
               }

               else{

               
               
               let [success, data] = updateShuliang(cell._cell.row.data['数量'], selectedRowKeysTable.current[0]);
               if (success) {
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                                myTable.current.updateData(data.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function() {
                                     myTable.current.element.children[1].scrollTop = former;
                                     myTable.current.element.children[1].scrollLeft = former2;
                                   let getRow = myTable.current.getRows(); //get array of currently selected row components.
                                   let component = null;
                                   for(let i = 0; i < getRow.length; i++) {
                                        let entry = getRow[i]._row.modules.dataTree.children;
                                        for(let j = 0; j < entry.length; j++) {
                                             let child = entry[j];
                                             if(child.data['key'] == key) {
                                                  //console.log(child);
                                                  component = child.component;
                                                  break;
                                             }
                                             
                                        }
     
                                   }
                                   component.select();
                                 //  handleSelect(component);
                                });                            
                                                            
               }
          }
           });
     
     
           myTable.current.on("tableBuilt", () => {
               if (bh != null) {
               Service.generateQingdanmingxi(name, bh, bt).then(x=>{
                    myTable.current.replaceData(x);
                    });
               }
             });
          
         
        }, [bh, bt]);






        React.useEffect(
          () => {
              console.log(beizhu);
              let result = [];
              if (beizhu != null) { 
                  let keys = Object.keys(beizhu["BZBH"]);
                  for(let i = 0; i < keys.length; i++) {
                      let key = keys[i];
                      result.push({'id': i+1, 'key': i+1, '序号': i+1, '编号': beizhu["BZBH"][key], '说明': beizhu["SM"][key], '数量': 1});//序号很重要
                  }
                  
                  let newSelect = extractFuzhu(debmRef.current);
                  setCheckedKeys_2(newSelect.map(x=>x.split('*')[0]).map(x=>Number(x)));
                  for(let i = 0; i < newSelect.length; i++) {
                    if (newSelect[i].includes('*')) {
                         let xuhao = Number(newSelect[i].split('*')[0]);
                         let coef = Number(newSelect[i].split('*')[1]);
                         for(let j = 0; j < result.length; j++) {
                              if (result[j]['id'] == xuhao) {
                                   result[j]['数量'] = coef;
                              }
                         }
                    }
                  }
                  setFuzhu(result);
                  
              }
          }, [beizhu]
        );

        React.useEffect(
          () => {
               beizhuFKRef.current = beizhuFK;
          }, [beizhuFK]
      );

  


      React.useEffect(
          () => {
               
               myTable.current.deselectRow();
               if (selectedRowKeysTable.current.length > 0 ) {
                    const [success, data, key] = changguidinge(JSON.parse(dingeclick), selectedRowKeysTable.current[0]);
                    if (success) {
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                         myTable.current.updateData(data.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
                                     myTable.current.element.children[1].scrollTop = former;
                                     myTable.current.element.children[1].scrollLeft = former2;
                              let getRow = myTable.current.getRows(); //get array of currently selected row components.
                              let component = null;
                              for(let i = 0; i < getRow.length; i++) {
                                   let entry = getRow[i]._row.modules.dataTree.children;
                                   for(let j = 0; j < entry.length; j++) {
                                        let child = entry[j];
                                        if(child.data['key'] == key) {
                                             //console.log(child);
                                             component = child.component;
                                             break;
                                        }
                                        
                                   }

                              }
                              
                              component.select();
                              handleSelect(component);

                                   
                               
                          });
                    }
               }
              
          }, [dingeclick]//常规添加定额
      );

      React.useEffect(
          () => {
               
                    let obj = JSON.parse(bctihuanClick);
                    if (obj != null) {
                        processRowUpdate({'id': obj['old'], '人材机编码': obj['newBianhao'], '名称': obj['newName'], 
                        '规格型号': '', '单位': obj['newDW'], '单价': obj['newJia'], '产地': '', '供应厂商': '',
                         '人材机类别':obj['RcjLb'], '甲供标志': '', '含量': '', '暂估价标志':'', '主要材料标志':'', '主材标志':'','设备标志':''});
                    }
                    
               
               
          }, [bctihuanClick]//替换定额人材机
      );


      React.useEffect(
          () => {
               if (selectedRowKeysTable.current.length > 0 && JSON.parse(tihuanClick) != null) {
                    const data = huan(JSON.parse(tihuanClick), selectedRowKeysTable.current[0]);
                    myTable.current.deselectRow();
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                    myTable.current.updateData(data.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
                                     myTable.current.element.children[1].scrollTop = former;
                                     myTable.current.element.children[1].scrollLeft = former2;
                         let getRow = myTable.current.getRows(); //get array of currently selected row components.
                         let component = null;
                         for(let i = 0; i < getRow.length; i++) {
                              let entry = getRow[i]._row.modules.dataTree.children;
                              for(let j = 0; j < entry.length; j++) {
                                   let child = entry[j];
                                   if(child.data['key'] == selectedRowKeysTable.current[0]) {
                                        component = child.component;
                                        break;
                                   }
                              }
                         }
                         component.select();
                         //handleSelect(component);
                     });
               }
               
          }, [tihuanClick]//替换定额人材机
      );



      React.useEffect(
          () => {
               if (tuijianRef.current != null ) {
               tuijianTable.current = new Tabulator(tuijianRef.current, {
                    index: "key",
                    height: 200,
                  data: tuijian, //link data to table
                  reactiveData: false, //enable data reactivity
                  dataTreeStartExpanded:false,
                  dataTree: false,
                  selectableRows:1, //make rows selectable
                  columns: [ //Define Table Columns
                               {title:"ID", field:"ID", width:80, headerSort:false, }, //never hide this column
                               {title:"定额编号", field:"定额编号", width:120,headerSort:false,  formatter:"textarea" },
                               {title:"工程量名称", field:"工程量名称", width:150, headerSort:false, formatter:"textarea"}, //hide this column first
                               {title:"工作内容", field:"工作内容", width:150 , headerSort:false, formatter:"textarea"},
                       ]
               });
               tuijianTable.current.on("tableBuilt", () => {
                    tuijianTable.current.replaceData(tuijian);
                  });
               }
               if (rcj2Ref.current != null ) {
                    rcj2Table.current = new Tabulator(rcj2Ref.current, {
                         index: "key",
                         height: 200,
                       data: rcjhl2, //link data to table
                       reactiveData: false, //enable data reactivity
                       dataTreeStartExpanded:false,
                       dataTree: false,
                       selectableRows:1, //make rows selectable
                       columns: [ //Define Table Columns
                                    {title:"人材机编码", field:"人材机编码", width:100, headerSort:false, }, //never hide this column
                                    {title:"名称", field:"名称", width:120,headerSort:false,  formatter:"textarea" },
                                    {title:"单位", field:"单位", width:150, headerSort:false, formatter:"textarea"}, //hide this column first
                                    {title:"单价", field:"单价", width:150 , headerSort:false, formatter:"money"},
                                    {title:"合价", field:"合价", width:150 , headerSort:false, formatter:"money"},
                                    {title:"含量", field:"含量", width:150 , headerSort:false, formatter:"textarea"},
                            ]
                    });
                    rcj2Table.current.on("tableBuilt", () => {
                         rcj2Table.current.replaceData(rcjhl2);
                       });
                    }

               if (rcjRef.current != null ) {
                    
                         rcjTable.current = new Tabulator(rcjRef.current, {
                              index: "key",
                              height: 200,
                            data: rcjhl, //link data to table
                            reactiveData: false, //enable data reactivity
                            dataTreeStartExpanded:false,
                            dataTree: false,
                            selectableRows:1, //make rows selectable
                            editTriggerEvent:"dblclick",
                            columns: [ //Define Table Columns
                                         {title:"ID", field:"ID", width:80, headerSort:false, },
                                         {title:"人材机编码", field:"人材机编码", width:120, headerSort:false, formatter: sparklineFormatter2}, //never hide this column
                                         {title:"名称", field:"名称", width:120,headerSort:false,  formatter:"textarea", editor: "input", editable: editCheckRcj },
                                         {title:"规格型号", field:"规格型号", width:80, headerSort:false, editor: "input", editable: editCheckRcj },
                                         {title:"单位", field:"单位", width:80, headerSort:false, formatter:"textarea"}, //hide this column first
                                         {title:"单价", field:"单价", width:80 , headerSort:false, formatter: sparklineFormatter, editor: "input", editable: editCheckJg },
                                         {title:"产地", field:"产地", width:80, headerSort:false, },
                                         {title:"供应厂商", field:"供应厂商", width:80, headerSort:false, },
                                         {title:"人材机类别", field:"人材机类别", width:100, headerSort:false, },
                                         {title:"甲供标志", field:"甲供标志", width:80 , headerSort:false, formatter:"textarea"},
                                         {title:"含量", field:"含量", width:80 , headerSort:false, formatter:"money", formatterParams:{precision:4}, editor: "input", editable: editCheckRcj },
                                         {title:"合价", field:"合价", width:80 , headerSort:false, formatter:"money"},
                                         {title:"暂估价标志", field:"暂估价标志", width:100 , headerSort:false, formatter:"textarea"},
                                         {title:"主要材料标志", field:"主要材料标志", width:100 , headerSort:false, formatter:"textarea"},
                                         {title:"主材标志", field:"主材标志", width:80 , headerSort:false, formatter:"textarea"},
                                         {title:"设备标志", field:"设备标志", width:80 , headerSort:false, formatter:"textarea"},
                                       
                                 ]
                         });
                         rcjTable.current.on("tableBuilt", () => {
                              rcjTable.current.replaceData(rcjhl);
                            });
                         rcjTable.current.on("cellDblClick", function(e, cell){
                              //e - the click event object
                              //cell - cell component
                              //let determine = !cell._cell.row.getData()['人材机编码'].includes('10000F');
                              let determine2 = !cell._cell.row.getData()['人材机编码'].includes('000FE'); //azfy
                              let determine3 = !cell._cell.row.getData()['人材机编码'].startsWith('D'); 
                              //let determine4 = cell._cell.row.getData()['bc'] != 'true';
                              if(cell._cell.column.getPosition() == 2  && !isQdrcj.current  && determine2 && determine3 ) {
                                  tihuanCallback(cell._cell.row.position, cell._cell.column.getPosition());
                              }
                          });
                         rcjTable.current.on("cellEdited", function(cell){
                              let data =  copy(cell._cell.table.getData());
                              for(let i = 0; i < data.length; i++) {
                                   data[i]['合价'] = Number(data[i]['单价']) * Number(data[i]['含量']);
                              }
                              setRcjhl(data);
                              if (rcjTable.current) {
                                   rcjTable.current.replaceData(data);
                              }
                              let data2 = [['ID', '人材机编码', '名称', '规格型号', '单位', '单价', '产地', '供应厂商', '人材机类别', '甲供标志', '含量', '合价', '暂估价标志', '主要材料标志', '主材标志', '设备标志', 'key', 'bc']]
                              for (let i = 0; i < data.length; i++) {
                                   data2.push([data[i]['ID'], data[i]['人材机编码'], data[i]['名称'], data[i]['规格型号'], data[i]['单位'], 
                                   data[i]['单价'], data[i]['产地'], data[i]['供应厂商'], data[i]['人材机类别'], 
                                   data[i]['甲供标志'], data[i]['含量'], data[i]['合价'], data[i]['暂估价标志'], data[i]['主要材料标志'], data[i]['主材标志'], data[i]['设备标志'], data[i]['key'], data[i]['bc']]);
                              }
     
                              let newData = updateDercj(selectedRowKeysTable.current[0], data2);
                              myTable.current.deselectRow();
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                              myTable.current.updateData(newData.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function() {
                                     myTable.current.element.children[1].scrollTop = former;
                                     myTable.current.element.children[1].scrollLeft = former2;
                              let getRow = myTable.current.getRows(); //get array of currently selected row components.
                              let component = null;
                              for(let i = 0; i < getRow.length; i++) {
                                     let entry = getRow[i]._row.modules.dataTree.children;
                                     for(let j = 0; j < entry.length; j++) {
                                           let child = entry[j];
                                           if(child.data['key'] == selectedRowKeysTable.current[0]) {
                                                //console.log(child);
                                               component = child.component;
                                                break;
                                            }
                                      }
                              }
                              component.select();  
                              //handleSelect(component);
                              });
                         });
                         
                    }
          }, [valueTab]
        );

     const EditableContext = React.createContext({ editingId: null, editingKey: null });
     const [editingId, setEditingId] = React.useState(null);
     const [editingKey, setEditingKey] = React.useState(null);
     const onEdit = (id, dataKey) => {
          setEditingId(id);
          setEditingKey(dataKey);
        };

     const onEditFinished = () => {
          console.log("edit finidhed");
          setEditingId(null);
          setEditingKey(null);
          onSelectChange(checkedKeys);
        };
     const styles = `
.table-cell-editing .rs-table-cell-content {
  padding: 4px;
}
.table-cell-editing .rs-input {
  width: 100%;
}
.table-cell:focus {
  outline: none;
  box-shadow: inset 0 0 0 1px #007bff;
}
`;

const fieldMap = {
     string: Input,
     number: InputNumber,
   };

   function focus(ref) {
     setTimeout(() => {
       if (ref.current?.tagName === 'INPUT' || ref.current?.getAttribute('tabindex') === '0') {
         ref.current.focus();
       } else if (ref.current instanceof HTMLElement) {
         ref.current.querySelector('input').focus();
       }
     }, 10);
   }

   const handleChangeFuzhuSL = (id, key, value) => {
     const nextData = Object.assign([], fuzhu);
     nextData.find(item => item.id === id)[key] = value;
 
     setFuzhu(nextData);
   };


const EditableCell = ({ rowData, dataType, dataKey, onChange, ...props }) => {
     const { editingId, editingKey, onEdit, onEditFinished } = React.useContext(EditableContext);
     const editing = rowData.id === editingId && dataKey === editingKey;
     const Field = fieldMap[dataType];
     const value = rowData[dataKey];
     const text = value;
     const inputRef = React.useRef();
     const cellRef = React.useRef();
   
     const handleEdit = () => {
          if (fuzhuEnable) {
             onEdit?.(rowData.id, dataKey);
             focus(inputRef);
          }
     };
   
     const handleFinished = () => {
       onEditFinished();
       focus(cellRef);
     };
   
     return (
       <Cell
         {...props}
         ref={cellRef}
         tabIndex={0}
         className={editing ? 'table-cell-editing' : 'table-cell'}
         onDoubleClick={handleEdit}
         
       >
         {editing ? (
           <Field
             ref={inputRef}
             defaultValue={value}
             onBlur={handleFinished}
             onKeyPress={e => {
               if (e.key === 'Enter') {
                 handleFinished();
               }
             }}
             onChange={value => {
               onChange?.(rowData.id, dataKey, value);
             }}
           />
         ) : (
           text
         )}
       </Cell>
     );
   };
      

    return (
        <Stack spacing={2}>

                   <Box>
                   <Stack direction='row' spacing={2}>
                   <Button variant="outlined" size="small" onClick={() => {
                      if (selectedRowKeysTable.current.length > 0) {
                         let getRow = myTable.current.getRows(); //get array of currently selected row components.
                         let hit = false;
                         for(let i = 0; i < getRow.length; i++) {
                              if (getRow[i]._row.data['key'] == selectedRowKeysTable.current[0]) {
                                   hit = true;
                              }
                         }
                         if (hit) {
                              suanshiCallback();
                         }
                      }
                      }}
                   >定额（算式）</Button>
                   <Button variant="outlined" size="small" onClick={() => {
                      if (selectedRowKeysTable.current.length > 0) {
                         const [success, data] = danxiangdinge(selectedRowKeysTable.current[0]);
                         if(success) {
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                              myTable.current.updateData(data.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
                                     myTable.current.element.children[1].scrollTop = former;
                                     myTable.current.element.children[1].scrollLeft = former2;
                                   resetUI();
                                 });
                         }
                      }
                      }}
                   >单项定额</Button>
                      <Button variant="outlined" size="small" onClick={() => {
                      if (selectedRowKeysTable.current.length > 0) {
                         let newData = shanchu(selectedRowKeysTable.current[0]);
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                         myTable.current.updateData(newData.filter(x=>x['key'] == selectedRowKeysTableParent.current)).then(function(){
                             //if (newData.filter(x=>x['key'] == selectedRowKeysTable.current[0]).length == 0) {
                                     myTable.current.element.children[1].scrollTop = former;
                                     myTable.current.element.children[1].scrollLeft = former2;
                                  resetUI();
                             //}
                         });
                     }
                      }}
                   >删除</Button>
                   <Button variant="outlined" size="small" onClick={() => {
                   let newData = undo();
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                   myTable.current.updateData(newData).then(function(){
                                     myTable.current.element.children[1].scrollTop = former;
                                     myTable.current.element.children[1].scrollLeft = former2;
                         resetUI();
                   });
                      }}
                   >撤销</Button>
                   <Button variant="outlined" size="small" onClick={() => {
                   let newData = redo();
                                          let former = myTable.current.element.children[1].scrollTop;
                                          let former2 = myTable.current.element.children[1].scrollLeft;
                   myTable.current.updateData(newData).then(function(){
                                     myTable.current.element.children[1].scrollTop = former;
                                     myTable.current.element.children[1].scrollLeft = former2;
                      resetUI();
                   });
                      }}
                   >重做</Button>
                   <Button variant="outlined" size="small" onClick={() => {
                            console.log("save to cloud");
                            loadingCallback();
                      
                      }}
                   >保存</Button>
                  
                   </Stack>
                   <div style={{width: "70vw"}}>
                   <div ref={myRef}> 
                  </div>
                  </div>
                  </Box>

                   <Box >
                   
                   <TabContext value={valueTab}>
                       <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                         <TabList sx={{minHeight: '24px'}} onChange={handleChange} aria-label="lab API tabs example">
                           <Tab sx={{p: 0, minHeight: '24px'}} label="人材机含量" value="1" />
                           <Tab sx={{p: 0, minHeight: '24px'}} label="人材机补充" value="3" />
                           <Tab sx={{p: 0, minHeight: '24px'}} label="定额附注" value="4" />
                           <Tab sx={{p: 0, minHeight: '24px'}} label="预拌砂浆" value="5" />
                           <Tab sx={{p: 0, minHeight: '24px'}} label="组价推荐" value="6" />
                         </TabList>
                       </Box>
                       
                       <TabPanel sx={{p: 1}} value="1">
                        <div style={{width:"70vw"}}>
                       <div ref={rcjRef}></div>
                       </div>
                       </TabPanel>
                       <TabPanel sx={{p: 1}} value="2">
                       <div ref={rcj2Ref}></div>
                       </TabPanel>
                       <TabPanel sx={{p: 1}} value="3">
                       <Box
                       sx={{
                         height: 200,
                         width: '100%',
                         '& .actions': {
                           color: 'text.secondary',
                         },
                         '& .textPrimary': {
                           color: 'text.primary',
                         },
                       }}
                     >
                       <DataGrid disableColumnMenu disableColumnSorting
                         hideFooter={true}
                         rows={rcjrows}
                         columns={rcjcolumns}
                         processRowUpdate={processRowUpdate}
                         slotProps={{
                           toolbar: { setRcjrows },
                         }}
                         slots={{
                              toolbar: EditToolbar,
                            }}
                         
                         localeText={zhCN_MUI.components.MuiDataGrid.defaultProps.localeText}
                         onCellDoubleClick={onCellDoubleClick}

                       />
                     </Box>
                         </TabPanel>
                       <TabPanel sx={{p: 1}} value="4">
                       <Box sx={{maxHeight: `190px`}}>
                       <CustomProvider locale={zhCN}>
                       <EditableContext.Provider value={{ editingId, editingKey, onEdit, onEditFinished }}>
                       <style>{styles}</style>
                        <Table rowHeight={rowData=>{
                         return 40;
                        }}
                        height={200} data = {fuzhu} id="fuzhu">
                         <Column width={80} align="center">
                              <HeaderCell style={{padding: 0}}>
                                   <div style={{lineHeight: '40px'}}>
                                        <Checkbox inline checked={checked} indeterminate={indeterminate} onChange={handleCheckAll} disabled={!fuzhuEnable}
                                        ></Checkbox>
                                   </div>
                              </HeaderCell>
                              <CheckCell dataKey="id" checkedKeys={checkedKeys} onChange={handleCheck} disabled={!fuzhuEnable}></CheckCell>
                         </Column>
                         <Column width={80} align="center">
                              <HeaderCell style={{ "fontSize": "0.875rem" }}>序号</HeaderCell>
                              <Cell dataKey="序号" style={{ "fontSize": "0.875rem" }}></Cell>
                         </Column>
                         <Column width={120} align="center">
                              <HeaderCell style={{ "fontSize": "0.875rem" }}>编号</HeaderCell>
                              <Cell dataKey="编号" style={{ "fontSize": "0.875rem" }}></Cell>
                         </Column>
                         <Column width={120} align="center">
                              <HeaderCell style={{ "fontSize": "0.875rem" }}>数量</HeaderCell>
                              <EditableCell dataKey="数量" dataType="number" style={{ "fontSize": "0.875rem" }} onChange={handleChangeFuzhuSL} />
                         </Column>
                         <Column fullText width={650} align="center">
                              <HeaderCell style={{ "fontSize": "0.875rem" }}>说明</HeaderCell>
                              <Cell dataKey="说明" style={{ "fontSize": "0.875rem" }}></Cell>
                         </Column>
                        </Table>
                        </EditableContext.Provider>
                        </CustomProvider>
                       </Box>
                       </TabPanel>
                       <TabPanel sx={{p: 1}} value="5">
                        <Box sx={{maxHeight: `190px`}}>
                        <FormControl>
                         <FormLabel id="demo-controlled-radio-buttons-group">说明</FormLabel>
                          <RadioGroup
                           aria-labelledby="demo-controlled-radio-buttons-group"
                           name="controlled-radio-buttons-group"
                            value={valueYuban}
                           onChange={onSelectChange2}
                         >
                         <FormControlLabel  disabled = {!yubanEnable} value="0" control={<Radio />} label={
                                <Typography sx={{fontSize: "0.875rem"}} >无</Typography>
                            } />
                         <FormControlLabel disabled = {!yubanEnable} value="1" control={<Radio />} label={
                                <Typography sx={{fontSize: "0.875rem"}} >湿拌砂浆</Typography>
                            } />
                         <FormControlLabel disabled = {!yubanEnable} value="2" control={<Radio />} label={
                                <Typography sx={{fontSize: "0.875rem"}} >散装干拌（混）砂浆</Typography>
                            } />
                         <FormControlLabel disabled = {!yubanEnable} value="3" control={<Radio />} label={
                                <Typography sx={{fontSize: "0.875rem"}} >袋装干拌（混）砂浆</Typography>
                            } />
                         </RadioGroup>
                         </FormControl>
                       
                        </Box>
                       </TabPanel>
                       
                       <TabPanel sx={{p: 1}} value="6">
                       <div ref={tuijianRef}></div>

                       </TabPanel>
                     </TabContext>
                  </Box>
                  </Stack>
                  





    );
}
