import * as React from 'react';
import Box from "@mui/material/Box";
import 'handsontable/dist/handsontable.full.min.css';
//import 'handsontable/styles/ht-theme-main.min.css';
import { HandsonTable } from 'handsontable/base';
import {HotTable} from "@handsontable/react";
//import { registerAllModules } from 'handsontable/registry';
import {RichTreeView } from "@mui/x-tree-view/RichTreeView";
import { Grid } from '@mui/material';
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 { registerPlugin, NestedRows } from 'handsontable/plugins';
//registerPlugin(NestedRows);
import Service from './Service';


import { textRenderer, registerRenderer } from 'handsontable/renderers';
export default function Djcs({name, bh, rgde, jxde, clde, beizhu, clickCallback}) {
     
    registerRenderer('customStylesRenderer', (hotInstance, TD, ...rest) => {
         textRenderer(hotInstance, TD, ...rest);
         TD.style.fontWeight = 'bold';
         TD.style.color = 'green';
         TD.style.background = '#d7f1e1';
       });

       registerRenderer('highlightRowRenderer', (hotInstance, TD, ...rest) => {
          textRenderer(hotInstance, TD, ...rest);
          TD.style.color = 'green';
          TD.style.background = '#d7f1e1';
        });
    const [detail, setDetail] = React.useState([
                    {
                    "序号": null, "清单编码": null, "名称" : null, "项目特征" : null, 
                    "计算规则" : null, "单位" : null, "数量" : null, 
                    "综合单价" : null, "合价" : null, "人工费" : null, "主材费" : null,
                     "设备费" : null, "辅材费" : null, "材料费" : null, 
                    "机械费" : null, "管理费" : null, "利润"  : null, "暂估价" : null, "综合人工工日" : null }
    ]);
    const hotRef = React.useRef(null);
    const [value, setValue] = React.useState("1");
    const [rcjhl, setRcjhl] = React.useState([]);
    const [rcjhl2, setRcjhl2] = React.useState([]);
    const [fuzhu, setFuzhu] = React.useState([]);
    const [tuijian, setTuijian] = React.useState([]);

    const [highlight, setHighlight] = React.useState([]);
    const selectedRow = React.useRef(-1);

    const rgdeRef = React.useRef(null);
    const jxdeRef = React.useRef(null);
    const cldeRef = React.useRef(null);
    const isQdrcj = React.useRef(false);
    React.useEffect(
        () => {
          Service.generateDjcs(name, bh).then(x=>{
          setDetail(x);
          selectedRow.current = -1;
          });
        }, [bh]
      );
    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([i+1, beizhu["BZBH"][key], beizhu["SM"][key]]);
                }
                setFuzhu(result);
            }
        }, [beizhu]
      );

    React.useEffect(
        () => {
          console.log("rgde changed");
          console.log(rgde);
          rgdeRef.current = rgde;
          jxdeRef.current = jxde;
          cldeRef.current = clde;
          if (isQdrcj.current) {
             setHighlight([]);
          } else {
          let toHighlight = [];
          for(let i = 1; i < rcjhl.length; i++) {
              let entry = rcjhl[i];
              let bianhao = entry[1];
              let rcjlb = entry[8];
              if (Number(rcjlb) == Number(1) && rgde) {
                  for (let j = 0; j < rgde.length; j++) {
                      if (rgde[j]["CLBH"] == bianhao) {
                          let danjia = Number(entry[5]);
                          if (danjia != rgde[j]["YSJG"]) {
                               console.log(`[${i},5]danjia bu yizhi`);
                               toHighlight.push({row: i, col: 5, renderer: "customStylesRenderer"});
                          }
                          let hanliang = Number(entry[10]);
                          if (hanliang != rgde[j]["gr"]) {
                               console.log(`[${i}, 10]hanliang bu yizhi`);
                               toHighlight.push({row: i, col: 10, renderer: "customStylesRenderer"});
                          }

                      }              
                  }

              }   
              if (Number(rcjlb) == Number(3) && jxde ) {
                   for (let j = 0; j < jxde.length; j++) {
                      if (jxde[j]["jxbh"] == bianhao) {
                         let danjia = Number(entry[5]);
                         if (danjia != jxde[j]["tbdj"]) {
                              console.log(`[${i},5]danjia bu yizhi`);
                              toHighlight.push({row: i, col: 5, renderer: "customStylesRenderer"});
                         }
                         let hanliang = Number(entry[10]);
                         if (hanliang != jxde[j]["sl"]) {
                              console.log(`[${i}, 10]hanliang bu yizhi`);
                              toHighlight.push({row: i, col: 10, renderer: "customStylesRenderer"});
                         }
                      }
                   }

              }   
              if (Number(rcjlb) == Number(2) && clde ) {
                   for (let j = 0; j < clde.length; j++) {
                      if (clde[j]["CLBH"] == bianhao) {
                         let danjia = Number(entry[5]);
                         if (danjia != clde[j]["YSJG"]) {
                              console.log(`[${i},5]danjia bu yizhi`);
                              toHighlight.push({row: i, col: 5, renderer: "customStylesRenderer"});
                         }
                         let hanliang = Number(entry[10]);
                         if (hanliang != clde[j]["SL"]) {
                              console.log(`[${i}, 10]hanliang bu yizhi`);
                              toHighlight.push({row: i, col: 10, renderer: "customStylesRenderer"});
                         }
                      }
                   }

              }   
          }
          console.log(toHighlight);
          setHighlight(toHighlight);
          }


          let bzrcjhl = [["人材机编码", "名称", "单位", "单价", "合价", "含量"]] 
          if (rgde)
          for (let i = 0; i  < rgde.length; i++) {
               bzrcjhl.push([rgde[i]["CLBH"], rgde[i]["CLMC"], rgde[i]["JLDW"], rgde[i]["YSJG"], rgde[i]["gf"], rgde[i]["gr"]]);
          }
          
          if (clde)
          for (let i = 0; i  < clde.length; i++) {
               bzrcjhl.push([clde[i]["CLBH"], clde[i]["CLMC"], clde[i]["JLDW"], clde[i]["YSJG"], clde[i]["HJ"], clde[i]["SL"]]);
          }
          if (jxde)
          for (let i = 0; i  < jxde.length; i++) {
               bzrcjhl.push([jxde[i]["jxbh"], jxde[i]["jxmc"], jxde[i]["DW"], jxde[i]["tbdj"], jxde[i]["hj"], jxde[i]["sl"]]);
          }
          setRcjhl2(bzrcjhl);
        }, [rgde, jxde, clde]
      );

      const handleChange = (event, newValue) => {
        setValue(newValue);
      };


    return (

               <Stack spacing={2}>
                 <Box>
                 <HotTable 
                 nestedRows={true}
                    data={detail
                    }

                 afterSelection={(row, column)=>{
                        selectedRow.current = row;
                        console.log(row);
                        let bt = "Djcs" ;
                        let selected = hotRef.current?.hotInstance?.getData()[row];
                        if (selected[0] != null) {
                             Service.generateQingdanrcj(name, bh,bt,selected[1]).then(x=>{
                                 setRcjhl(x);
                                 isQdrcj.current=true;
                                 setHighlight([]);
                               });
                               Service.generateQingdanTuijian(name, bh,bt,selected[1]).then(x=>{
                                   setTuijian(x);
                                   //isQdrcj.current = true;
                                   //setHighlight([]);
                                });
                        }else{
                            let qdbm = null;
                            for (let i = row - 1;  i > -1; i= i - 1) {
                                let above = hotRef.current?.hotInstance?.getData()[i];
                                if (above[0] != null) {
                                    qdbm = above[1];
                                    break;
                                }
                                 
                            }
                             clickCallback(qdbm, selected[1]);
                             Service.generateDingercj(name, bh,bt,qdbm, selected[1]).then(x=>{
                               setRcjhl(x);
                               isQdrcj.current = false;
                               
                               let toHighlight = [];
                               for(let i = 1; i < x.length; i++) {
                                   let entry = x[i];
                                   let bianhao = entry[1];
                                   let rcjlb = entry[8];
                                   if (Number(rcjlb) == 1 &&  rgdeRef.current  ) {
                                      for (let j = 0;j < rgdeRef.current.length; j++) {
                                         if (rgdeRef.current[j]["CLBH"] == bianhao) {
                                              let danjia = Number(entry[5]);
                                              if (danjia != rgdeRef.current[j]["YSJG"]) {
                                                   console.log(`[${i},5]danjia bu yizhi`);
                                                   toHighlight.push({row: i, col: 5, renderer: "customStylesRenderer"});
                                              }
                                              let hanliang = Number(entry[10]);
                                              if (hanliang != rgdeRef.current[j]["gr"]) {
                                                   console.log(`[${i}, 10]hanliang bu yizhi`);
                                                   toHighlight.push({row: i, col: 10, renderer: "customStylesRenderer"});
                                              }
                                         }
                                      }

                                   }   
                                   if (Number(rcjlb) == 3 && jxdeRef.current  ) {
                                      for (let j = 0; j < jxdeRef.current.length; j++) {
                                         if (jxdeRef.current[j]["jxbh"] == bianhao) {
                                               let danjia = Number(entry[5]);
                                               if (danjia != jxdeRef.current[j]["tbdj"]) {
                                                    console.log(`[${i},5]danjia bu yizhi`);
                                                    toHighlight.push({row: i, col: 5, renderer: "customStylesRenderer"});
                                               }
                                               let hanliang = Number(entry[10]);
                                               if (hanliang != jxdeRef.current[j]["sl"]) {
                                                    console.log(`[${i}, 10]hanliang bu yizhi`);
                                                    toHighlight.push({row: i, col: 10, renderer: "customStylesRenderer"});
                                               }
                                         }
                                      }

                                   }   
                                   if (Number(rcjlb) == 2 && cldeRef.current  ) {
                                      for (let j = 0; j < cldeRef.current.length; j++) {
                                         if (cldeRef.current[j]["CLBH"] == bianhao) {
                                               let danjia = Number(entry[5]);
                                               if (danjia != cldeRef.current[j]["YSJG"]) {
                                                    console.log(`[${i},5]danjia bu yizhi`);
                                                    toHighlight.push({row: i, col: 5, renderer: "customStylesRenderer"});
                                               }
                                               let hanliang = Number(entry[10]);
                                               if (hanliang != cldeRef.current[j]["SL"]) {
                                                    console.log(`[${i}, 10]hanliang bu yizhi`);
                                                    toHighlight.push({row: i, col: 10, renderer: "customStylesRenderer"});
                                               }
                                         }
                                      }

                                   }   
                               }
                               setHighlight(toHighlight);
                             });

                        }
                            

                    }}
                    cells={(row, col, prop) => {
                         if (row == selectedRow.current) {
                           return {
                             // row options, which apply to each cell of the second row
                             // and to each cell of the fifth row
                             renderer: "highlightRowRenderer"
                           };
                         }
                       }
                    }
                    ref = {hotRef}
                    contextMenu={true}
                    bindRowsWithHeaders={true}
                    fixedRowsTop={0}
                    fixedColumnsStart={2}
                    manualColumnResize={true}
                    rowHeaders={true}
                    colHeaders={["ID", "序号", "清单编码", "名称", "项目特征", "计算规则", "单位", "数量", "综合单价", "合价", "人工费", "主材费", "设备费", "辅材费", "材料费", "机械费", "管理费", "利润" , "暂估价", "综合人工工日" ]}
                    height="400"
                    selectionMode="single"
                    autoWrapRow={false}
                    autoWrapCol={false}
                    readOnly={true}
                    licenseKey="non-commercial-and-evaluation" // for non-commercial use only
                  />
                  </Box>
                   <Box >
                   
                   <TabContext value={value}>
                       <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                         <TabList onChange={handleChange} aria-label="lab API tabs example">
                           <Tab label="人材机含量" value="1" />
                           <Tab label="标准定额人材机含量" value="2" />
                           <Tab label="定额附注" value="3" />
                           <Tab label="组价推荐" value="4" />
                         </TabList>
                       </Box>
                       <TabPanel value="1">
                          <HotTable 
                          nestedRows={false}
                             data={rcjhl
                             }
                             cell={highlight}
                             manualColumnResize={true}
                             rowHeaders={true}
                             colHeaders={true}
                             height="300"
                             readOnly={true}
                             fixedRowsTop={1}
                             selectionMode="single"
                             autoWrapRow={false}
                             autoWrapCol={false}
                             licenseKey="non-commercial-and-evaluation" // for non-commercial use only
                           />

                       </TabPanel>
                       <TabPanel value="2">
                          <HotTable 
                          nestedRows={false}
                             data={rcjhl2
                             }
                             manualColumnResize={true}
                             rowHeaders={true}
                             colHeaders={true}
                             height="300"
                             readOnly={true}
                             fixedRowsTop={1}
                             selectionMode="single"
                             autoWrapRow={false}
                             autoWrapCol={false}
                             licenseKey="non-commercial-and-evaluation" // for non-commercial use only
                           />

                       </TabPanel>
                       <TabPanel value="3">
                          <HotTable 
                          nestedRows={false}
                             data={fuzhu
                             }
                             manualColumnResize={true}
                             rowHeaders={true}
                             colHeaders={true}
                             height="300"
                             readOnly={true}
                             fixedRowsTop={1}
                             selectionMode="single"
                             autoWrapRow={false}
                             autoWrapCol={false}
                             licenseKey="non-commercial-and-evaluation" // for non-commercial use only
                           />

                       </TabPanel>

                       <TabPanel value="4">
                          <HotTable 
                          nestedRows={false}
                             data={tuijian
                             }
                             manualColumnResize={true}
                             rowHeaders={true}
                             colHeaders={true}
                             height="300"
                             readOnly={true}
                             fixedRowsTop={1}
                             selectionMode="single"
                             autoWrapRow={false}
                             autoWrapCol={false}
                             licenseKey="non-commercial-and-evaluation" // for non-commercial use only
                           />

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

                  </Stack>



    );
}
