import * as React from 'react';
import Box from "@mui/material/Box";
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";
//registerPlugin(NestedRows);
import Service from './Service';
import { Table, ConfigProvider, Button as AButton } from "antd";
import EditableSelect from './EditableSelect';
import EditableSelectGC from './EditableSelectGC';
import Editable from './Editable';
import Button from '@mui/material/Button';

import {copy} from './utils';

export default function Qufei({id, qufeiCallback}) {
    
  const [detail, setDetail] = React.useState([
    {"序号": null, "清单编码" : 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 [expandedRowKeys, setExpandedRowKeys] = React.useState([]);
const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);



const apply = () => {
  let checked = check(detail);
  if (checked) {
    qufeiCallback(id, detail);
  }
};

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) => {
  if (selectedRowKeys.length > 0 && detail.length > 0) {
    let selected = selectedRowKeys[0];
    if (detail[0]['key'] == selected) {
      //总选择
      let newData = copy(detail);
      newData[0]['利润（%）'] = value;
      for(let i = 0; i < newData[0]["children"].length; i++) {
        let child = newData[0]['children'][i];
        child['利润（%）'] = value;
        for(let j = 0; j < child['children'].length; j++) {
          child['children'][j]['利润（%）'] = value;
        }
      }
      setDetail(newData);

    }
    else if (detail[0]["children"].filter(x=>x['key'] == selected).length > 0) {
      //某个单项工程
      let newData = copy(detail);
      for(let i = 0; i < newData[0]["children"].length; i++) {
        let child = newData[0]['children'][i];
        if (child['key'] == selected) {
          child['利润（%）'] = value;
          for(let j = 0; j < child['children'].length; j++) {
            child['children'][j]['利润（%）'] = value;
          }
        }
        
      } 
      setDetail(newData);
    } else {
      //具体一行
      let newData = copy(detail);
      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;
          }
        }
        
        
      } 
      setDetail(newData);
    }


  }
};


const handleChangeGLF = (value) => {
  if (selectedRowKeys.length > 0 && detail.length > 0) {
    let selected = selectedRowKeys[0];
    if (detail[0]['key'] == selected) {
      //总选择
      let newData = copy(detail);
      newData[0]['管理费（%）'] = value;
      for(let i = 0; i < newData[0]["children"].length; i++) {
        let child = newData[0]['children'][i];
        child['管理费（%）'] = value;
        for(let j = 0; j < child['children'].length; j++) {
          child['children'][j]['管理费（%）'] = value;
        }
      }
      setDetail(newData);

    }
    else if (detail[0]["children"].filter(x=>x['key'] == selected).length > 0) {
      //某个单项工程
      let newData = copy(detail);
      for(let i = 0; i < newData[0]["children"].length; i++) {
        let child = newData[0]['children'][i];
        if (child['key'] == selected) {
          child['管理费（%）'] = value;
          for(let j = 0; j < child['children'].length; j++) {
            child['children'][j]['管理费（%）'] = value;
          }
        }
        
      } 
      setDetail(newData);
    } else {
      //具体一行
      let newData = copy(detail);
      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;
          }
        }
        
        
      } 
      setDetail(newData);
    }


  }
};


const handleChange = (value) => {
  if (selectedRowKeys.length > 0 && detail.length > 0) {
    let selected = selectedRowKeys[0];
    if (detail[0]['key'] == selected) {
      //总选择
      let newData = copy(detail);
      newData[0]['工程类别'] = value;
      for(let i = 0; i < newData[0]["children"].length; i++) {
        let child = newData[0]['children'][i];
        child['工程类别'] = value;
        for(let j = 0; j < child['children'].length; j++) {
          child['children'][j]['工程类别'] = value;
        }
      }
      setDetail(traverse(newData));

    }
    else if (detail[0]["children"].filter(x=>x['key'] == selected).length > 0) {
      //某个单项工程
      let newData = copy(detail);
      for(let i = 0; i < newData[0]["children"].length; i++) {
        let child = newData[0]['children'][i];
        if (child['key'] == selected) {
          child['工程类别'] = value;
          for(let j = 0; j < child['children'].length; j++) {
            child['children'][j]['工程类别'] = value;
          }
        }
        
      } 
      setDetail(traverse(newData));
    } else {
      //具体一行
      let newData = copy(detail);
      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;
          }
        }
        
        
      } 
      setDetail(traverse(newData));
    }


  }
};

const handleChangeGC = (value) => {
  if (selectedRowKeys.length > 0 && detail.length > 0) {
    let selected = selectedRowKeys[0];
    if (detail[0]['key'] == selected) {
      //总选择
      let newData = copy(detail);
      newData[0]['工程类型'] = value;
      for(let i = 0; i < newData[0]["children"].length; i++) {
        let child = newData[0]['children'][i];
        child['工程类型'] = value;
        for(let j = 0; j < child['children'].length; j++) {
          child['children'][j]['工程类型'] = value;
        }
      }
      setDetail(traverse(newData));

    }
    else if (detail[0]["children"].filter(x=>x['key'] == selected).length > 0) {
      //某个单项工程
      let newData = copy(detail);
      for(let i = 0; i < newData[0]["children"].length; i++) {
        let child = newData[0]['children'][i];
        if (child['key'] == selected) {
          child['工程类型'] = value;
          for(let j = 0; j < child['children'].length; j++) {
            child['children'][j]['工程类型'] = value;
          }
        }
        
      } 
      setDetail(traverse(newData));
    } else {
      //具体一行
      let newData = copy(detail);
      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;
          }
        }
        
        
      } 
      setDetail(traverse(newData));
    }


  }
};

function selectRow(record) {
  /*
  const selectedRowKeys_ = [...selectedRowKeys];
  if (selectedRowKeys_.indexOf(record.key) >= 0) {
       selectedRowKeys_.splice(selectedRowKeys_.indexOf(record.key), 1);
  } else {
       selectedRowKeys_.push(record.key);
  }*/
   setSelectedRowKeys([record.key]);
}
React.useEffect(
  () => {
    
    Service.generateQufei(id).then(x=>{

    setDetail(x);
    });
  
     
  }, [id]
);


    return (
                 <Box>
                <Button variant="outlined" onClick={apply}>应用</Button>
                <ConfigProvider
                   theme={{
                    components: {
                      Table: {
                        /* here is your component tokens */
                        cellPaddingBlock : 8
                      },
                    },
                  }}
                   >
                 <Table 
                    dataSource={detail}
                    
                    
                    //afterSelection={handleSelection}
                    //afterSelection={handleSelection}
                    ref = {hotRef}
                    expandable = {
                         {
                              expandedRowKeys,
                              onExpand: (expandable, record) => {
                                   if (expandable) {
                                     setExpandedRowKeys([...expandedRowKeys, record.key]);
                                   } else {
                                     setExpandedRowKeys(expandedRowKeys.filter((id) => record.key !== id));
                                   }
                                 },
                              expandRowByClick: true
                         }
                    }

                    rowSelection= {rowSelection}
                    onRow={(record)=>({
                         onClick: () => {
                              selectRow(record);
                            }
                    })}
                    scroll={{ x: 'max-content' , y : 'calc(100vh - 200px)'}}
                    //pagination={{ position: ['none', 'none'] }}
                    pagination={false}
                    columns = {[
                         
                         { dataIndex: '操作',        title : '操作',        key : '操作'          , width : 30 , fixed: 'left'   },
                         { dataIndex: '名称'   ,      title : '名称'  ,       key : '名称'        , width : 250         },
                         { dataIndex: '工程类型' ,    title : '工程类型' ,  
                           key : '工程类型'    , width : 150  ,
                           render: (text, record) => {
                            //console.log("column render");
                            //console.log("text".concat(text));
                            //console.log(record);
                                   
                                      return ( 
                                           <EditableSelectGC initialText={text}  onChange={handleChangeGC}
                                           >
                                          </EditableSelectGC>
                                       );
                                    
                                    //console.log(text);
                                    
                            }
                             },
                         { dataIndex: '工程类别' ,    title : '工程类别' ,  
                           key : '工程类别'    , width : 100  ,
                           render: (text, record) => {
                            //console.log("column render");
                            //console.log("text".concat(text));
                            //console.log(record);
                                   
                                      return ( 
                                           <EditableSelect initialText={text}  onChange={handleChange}
                                           >
                                          </EditableSelect>
                                       );
                                    
                                    //console.log(text);
                                    
                            }
                             },
                         { dataIndex: '管理费（%）' ,    title : '管理费（%）' ,    key : '管理费（%）'    , width : 50   ,
                         render: (text, record) => {
                          //console.log("column render");
                          //console.log("text".concat(text));
                          //console.log(record);
                                 
                                    return ( 
                                         <Editable initialText={text}  onChange={handleChangeGLF}
                                         >
                                        </Editable>
                                     );
                                  
                                  //console.log(text);
                                  
                          }      },
                         { dataIndex: '利润（%）'    ,     title : '利润（%）'  ,       key : '利润（%）'        , width : 50  ,
                         render: (text, record) => {
                          //console.log("column render");
                          //console.log("text".concat(text));
                          //console.log(record);
                                 
                                    return ( 
                                         <Editable initialText={text}  onChange={handleChangeLR}
                                         >
                                        </Editable>
                                     );
                                  
                                  //console.log(text);
                                  
                          }
                        },
                        { dataIndex: '备注',        title : '备注',        key : '备注'          , width : 100   },

                       
                        

                         
                             
                            
                       ]}
                   
                  />
                  </ConfigProvider>


                 </Box>

                  



    );
}