import * as React from 'react';
import Box from "@mui/material/Box";
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";
//registerPlugin(NestedRows);
import Service from './Service';
import { Table, ConfigProvider } from "antd";
import EditableSelect from './EditableSelect';
import EditableSelectGC from './EditableSelectGC';
import Editable from './Editable';
import Button from '@mui/material/Button';
import {TabulatorFull as Tabulator} from "tabulator-tables"; //import Tabulator library
import "tabulator-tables/dist/css/tabulator.min.css"; //import Tabulator stylesheet
import './Tabulator.css';
import {copy} from './utils';

export default function Qufei({id, qufeiCallback}) {
    
  const [detail, setDetail] = React.useState([]);

const hotRef = React.useRef(null);
const myRef = React.useRef();
const myTable = React.useRef(null);
const [expandedRowKeys, setExpandedRowKeys] = React.useState([]);
const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);



const apply = () => {
  let checked = check(myTable.current.getData());
  if (checked) {
    let origin = myTable.current.getData();
    let y = origin.map(z=>{
      z["children"] = z['_children'];
      return z;
    });
    let t = y.map(z=>{
      if (z.hasOwnProperty("children")) {
        let children = z["children"];
        for (let i = 0; i < children.length; i++) {
          let child = children[i];
          if (child.hasOwnProperty("_children")) {
            child["children"] = child["_children"];
          }
        }
      }
      return z;
      });
    qufeiCallback(id, t);
  }
};

const check = (data) => {
  for(let i = 0; i < data.length; i++) {
    if (data[i]['管理费（%）'].length == 0) {
      return false;
    }
    if (data[i]['利润（%）'].length == 0) {
      return false;
    }
    if (data[i].hasOwnProperty('_children')) {
       let checked = check(data[i]['_children']);
       if (!checked) {
          return false;
       }
       return true;
    }
    else {
      return true;
    }
    

  }
};


const rowSelection = {
  selectedRowKeys,
  onChange: (selectedRowKeys) => {
       //console.log(selectedRowKeys);
       if (selectedRowKeys.length > 0) {
            setExpandedRowKeys([selectedRowKeys.at(-1)]);
       } else {
       setSelectedRowKeys(selectedRowKeys);
       //handleSelection(selectedRowKeys);
       }
  }
};

const traverse = (data) => {
  for(let i = 0; i < data.length; i++) {
    if (data[i]['工程类型'].length > 0 && data[i]['工程类别'].length > 0) {
        if (data[i]['工程类型'] == '建筑工程') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '32';
            data[i]['利润（%）'] = '12';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '29';
            data[i]['利润（%）'] = '12';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '26';
            data[i]['利润（%）'] = '12';
            data[i]['备注'] = '';
          }
        }
        if (data[i]['工程类型'] == '单独预制构件制作') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '15';
            data[i]['利润（%）'] = '6';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '13';
            data[i]['利润（%）'] = '6';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '11';
            data[i]['利润（%）'] = '6';
            data[i]['备注'] = '';
          }
        }
        if (data[i]['工程类型'] == '打预制桩、单独构件吊装') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '11';
            data[i]['利润（%）'] = '5';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '9';
            data[i]['利润（%）'] = '5';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '7';
            data[i]['利润（%）'] = '5';
            data[i]['备注'] = '';
          }
        }
        if (data[i]['工程类型'] == '制作兼打桩') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '17';
            data[i]['利润（%）'] = '7';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '15';
            data[i]['利润（%）'] = '7';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '12';
            data[i]['利润（%）'] = '7';
            data[i]['备注'] = '';
          }
        }
        if (data[i]['工程类型'] == '大型土石方工程') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '7';
            data[i]['利润（%）'] = '4';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '7';
            data[i]['利润（%）'] = '4';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '7';
            data[i]['利润（%）'] = '4';
            data[i]['备注'] = '';
          }
        }
        if (data[i]['工程类型'] == '单独装饰工程') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '43';
            data[i]['利润（%）'] = '15';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '43';
            data[i]['利润（%）'] = '15';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '43';
            data[i]['利润（%）'] = '15';
            data[i]['备注'] = '';
          }
        }
        if (data[i]['工程类型'] == '安装工程') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '48';
            data[i]['利润（%）'] = '14';
            data[i]['备注'] = '计算基础：人工费';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '44';
            data[i]['利润（%）'] = '14';
            data[i]['备注'] = '计算基础：人工费';
          } else {
            data[i]['管理费（%）'] = '40';
            data[i]['利润（%）'] = '14';
            data[i]['备注'] = '计算基础：人工费';
          }
        }
        if (data[i]['工程类型'] == '通用项目、道路、排水工程') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '26';
            data[i]['利润（%）'] = '10';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '23';
            data[i]['利润（%）'] = '10';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '20';
            data[i]['利润（%）'] = '10';
            data[i]['备注'] = '';
          }
        }
        if (data[i]['工程类型'] == '桥梁、水工构筑物') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '35';
            data[i]['利润（%）'] = '10';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '32';
            data[i]['利润（%）'] = '10';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '29';
            data[i]['利润（%）'] = '10';
            data[i]['备注'] = '';
          }
        }
        if (data[i]['工程类型'] == '给水、燃气与集中供热') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '45';
            data[i]['利润（%）'] = '13';
            data[i]['备注'] = '计算基础：人工费';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '41';
            data[i]['利润（%）'] = '13';
            data[i]['备注'] = '计算基础：人工费';
          } else {
            data[i]['管理费（%）'] = '37';
            data[i]['利润（%）'] = '13';
            data[i]['备注'] = '计算基础：人工费';
          }
        }
        if (data[i]['工程类型'] == '路灯及交通设施工程') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '43';
            data[i]['利润（%）'] = '13';
            data[i]['备注'] = '计算基础：人工费';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '43';
            data[i]['利润（%）'] = '13';
            data[i]['备注'] = '计算基础：人工费';
          } else {
            data[i]['管理费（%）'] = '43';
            data[i]['利润（%）'] = '13';
            data[i]['备注'] = '计算基础：人工费';
          }
        }
        if (data[i]['工程类型'] == '（市）大型土石方工程') {
          if (data[i]['工程类别'] == '一类工程') {
            data[i]['管理费（%）'] = '7';
            data[i]['利润（%）'] = '4';
            data[i]['备注'] = '';
          } else if (data[i]['工程类别'] == '二类工程') {
            data[i]['管理费（%）'] = '7';
            data[i]['利润（%）'] = '4';
            data[i]['备注'] = '';
          } else {
            data[i]['管理费（%）'] = '7';
            data[i]['利润（%）'] = '4';
            data[i]['备注'] = '';
          }
        }

    }
    if (data[i].hasOwnProperty("_children")) {
      traverse(data[i]['_children']);
    }
  }
  return data;
};



const handleChangeLR = (value) => {
  
    let selected = value.row.getData()['key'];
    let all = value.row.table.getData();
    if (all[0]['key'] == selected) {
      //总选择
      let newData = copy(all);
      newData[0]['利润（%）'] = value.value;
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        child['利润（%）'] = value.value;
        for(let j = 0; j < child['_children'].length; j++) {
          child['_children'][j]['利润（%）'] = value.value;
        }
      }
      myTable.current.replaceData(newData);

    }
    else if (all[0]["_children"].filter(x=>x['key'] == selected).length > 0) {
      //某个单项工程
      let newData = copy(all);
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        if (child['key'] == selected) {
          child['利润（%）'] = value.value;
          for(let j = 0; j < child['_children'].length; j++) {
            child['_children'][j]['利润（%）'] = value.value;
          }
        }
        
      } 
      myTable.current.replaceData(newData);
    } else {
      //具体一行
      let newData = copy(all);
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        
        for(let j = 0; j < child['_children'].length; j++) {
          if (child['_children'][j]['key'] == selected) {  
              child['_children'][j]['利润（%）'] = value.value;
          }
        }
        
        
      } 
      myTable.current.replaceData(newData);
    }


  
};


const handleChangeGLF = (value) => {
  
    let selected = value.row.getData()['key'];
    let all = value.row.table.getData();
    if (all[0]['key'] == selected) {
      //总选择
      let newData = copy(all);
      newData[0]['管理费（%）'] = value.value;
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        child['管理费（%）'] = value.value;
        for(let j = 0; j < child['_children'].length; j++) {
          child['_children'][j]['管理费（%）'] = value.value;
        }
      }
      myTable.current.replaceData(newData);

    }
    else if (all[0]["_children"].filter(x=>x['key'] == selected).length > 0) {
      //某个单项工程
      let newData = copy(all);
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        if (child['key'] == selected) {
          child['管理费（%）'] = value.value;
          for(let j = 0; j < child['_children'].length; j++) {
            child['_children'][j]['管理费（%）'] = value.value;
          }
        }
        
      } 
      myTable.current.replaceData(newData);
    } else {
      //具体一行
      let newData = copy(all);
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        
        for(let j = 0; j < child['_children'].length; j++) {
          if (child['_children'][j]['key'] == selected) {  
              child['_children'][j]['管理费（%）'] = value.value;
          }
        }
        
        
      } 
      myTable.current.replaceData(newData);
    }


  
};


const handleChange = (value) => {
  
    let selected = value.row.getData()['key'];
    let all = value.row.table.getData();
    if (all[0]['key'] == selected) {
      //总选择
      let newData = copy(all);
      newData[0]['工程类别'] = value.value;
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        child['工程类别'] = value.value;
        for(let j = 0; j < child['_children'].length; j++) {
          child['_children'][j]['工程类别'] = value.value;
        }
      }
      myTable.current.replaceData(traverse(newData));

    }
    else if (all[0]["_children"].filter(x=>x['key'] == selected).length > 0) {
      //某个单项工程
      let newData = copy(all);
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        if (child['key'] == selected) {
          child['工程类别'] = value.value;
          for(let j = 0; j < child['_children'].length; j++) {
            child['_children'][j]['工程类别'] = value.value;
          }
        }
        
      } 
      myTable.current.replaceData(traverse(newData));
    } else {
      //具体一行
      let newData = copy(all);
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        
        for(let j = 0; j < child['_children'].length; j++) {
          if (child['_children'][j]['key'] == selected) {  
              child['_children'][j]['工程类别'] = value.value;
          }
        }
        
        
      } 
      myTable.current.replaceData(traverse(newData));
    }


  
};

const handleChangeGC = (value) => {

    let selected = value.row.getData()['key'];
    let all = value.row.table.getData();
    if (all[0]['key'] == selected) {
      //总选择
      let newData = copy(all);
      newData[0]['工程类型'] = value.value;
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        child['工程类型'] = value.value;
        for(let j = 0; j < child['_children'].length; j++) {
          child['_children'][j]['工程类型'] = value.value;
        }
      }
      myTable.current.replaceData(traverse(newData));

    }
    else if (all[0]["_children"].filter(x=>x['key'] == selected).length > 0) {
      //某个单项工程
      let newData = copy(all);
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        if (child['key'] == selected) {
          child['工程类型'] = value.value;
          for(let j = 0; j < child['_children'].length; j++) {
            child['_children'][j]['工程类型'] = value.value;
          }
        }
        
      } 
      myTable.current.replaceData(traverse(newData));
    } else {
      //具体一行
      let newData = copy(all);
      for(let i = 0; i < newData[0]["_children"].length; i++) {
        let child = newData[0]['_children'][i];
        
        for(let j = 0; j < child['_children'].length; j++) {
          if (child['_children'][j]['key'] == selected) {  
              child['_children'][j]['工程类型'] = value.value;
          }
        }
        
        
      } 
      myTable.current.replaceData(traverse(newData));
    }


  
};


React.useEffect(
  () => {
    myTable.current = new Tabulator(myRef.current, {

      index: "key",
      height: 600,
    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){
        //console.log(row);
        //console.log(level);
        return true; //expand rows where the "driver" data field is true;
    },
    columns: [ //Define Table Columns 序号", "名称", "取费基数", "计算基础","费率", "金额", "类别
                 {title:"名称", field:"名称", width:250, headerSort:false, formatter:"textarea"}, //hide this column first
                 {title:"工程类型", field:"工程类型", width:100 , headerSort:false, formatter:"textarea", editor: "list", editorParams: {
                   values: [
                    { //option group
                      label:"建筑工程",
                      options:[ //options in option group
                          {
                              label:"建筑工程",
                              value:"建筑工程",
                             
                          },
                          {
                              label:"单独预制构件制作",
                              value:"单独预制构件制作",
                          },
                          {
                            label:"打预制桩、单独构件吊装",
                            value:"打预制桩、单独构件吊装",
                          },
                          {
                          label:"制作兼打桩",
                          value:"制作兼打桩",
                          },
                          {
                            label:"大型土石方工程",
                            value:"大型土石方工程",
                            },
                      ]
                    },
                    { //option group
                      label:"单独装饰工程",
                      options:[ //options in option group
                          {
                              label:"单独装饰工程",
                              value:"单独装饰工程",
                             
                          },
                      ]
                    },
                    { //option group
                      label:"安装工程",
                      options:[ //options in option group
                          {
                              label:"安装工程",
                              value:"安装工程",
                             
                          },
                      ]
                    },
                    { //option group
                      label:"市政工程",
                      options:[ //options in option group
                          {
                              label:"通用项目、道路、排水工程",
                              value:"通用项目、道路、排水工程",
                             
                          },
                          {
                            label:"桥梁、水工构筑物",
                            value:"桥梁、水工构筑物",
                           
                        },
                        {
                          label:"给水、燃气与集中供热",
                          value:"给水、燃气与集中供热",
                         
                      },
                      {
                        label:"路灯及交通设施工程",
                        value:"路灯及交通设施工程",
                       
                    },
                    {
                      label:"（市）大型土石方工程",
                      value:"（市）大型土石方工程",
                     
                  },
                      ]
                    },
                   ]
                 }},
                 {title:"工程类别", field:"工程类别", width:100, headerSort:false, formatter: "textarea" , editor: "list", editorParams: {
                   values: ["一类工程", "二类工程", "三类工程"]
                 }

                 },
                 {title:"管理费（%）", field:"管理费（%）", width:100, headerSort:false, formatter:"textarea", editor: "input"},
                 {title:"利润（%）", field:"利润（%）", width:150, headerSort:false, formatter:"textarea", editor: "input" },
                 {title:"备注", field:"备注", width:200, headerSort:false, formatter:"textarea"},
               
         ]

    });//init table

  



  myTable.current.on("tableBuilt", () => {
    Service.generateQufei(id).then(x=>{

      console.log(x);
      let y = x.map(z=>{
        z["_children"] = z['children'];
        return z;
      });
      let t = y.map(z=>{
        if (z.hasOwnProperty("_children")) {
          let children = z["_children"];
          for (let i = 0; i < children.length; i++) {
            let child = children[i];
            if (child.hasOwnProperty("children")) {
              child["_children"] = child["children"];
            }
          }
        }
        return z;
        });
         myTable.current.replaceData(t);
     });

   
    });

    myTable.current.on("cellEdited", function(cell){
      console.log(cell._cell);
      if (cell._cell.column.field == '工程类型') {
        handleChangeGC(cell._cell);
      }
      if (cell._cell.column.field == '工程类别') {
        handleChange(cell._cell);
      } 
      if (cell._cell.column.field == '管理费（%）') {
        handleChangeGLF(cell._cell);
      } 
      if (cell._cell.column.field == '利润（%）') {
        handleChangeLR(cell._cell);
      } 
    });
  
     
  }, [id]
);


    return (
                 <Box sx={{ width: '70vw'}}>
                <Button variant="outlined" onClick={apply}>应用</Button>
                 
                <div ref={myRef}> 
                </div>

                 </Box>

                  



    );
}