import React, {useEffect, useState} from 'react';
import {Card,Tabs,Form,Row,Col,Select,DatePicker,Button,message,Table,Radio} from "antd";
import { useRequest } from 'umi';

import { dicFindUtils,DictBizType,ApproveType,convertFieldToNum, parseAreaTreeData } from '@/utils/utils';
import moment from 'moment';
import utilsStyles from '@/utils/utils.less';
import classNames from 'classnames';
import { getTimeDistance,getForwardTimeDistance,getChildren } from '@/utils/common';
import { goodAtAnalyzingReports } from './service/energyRequest';
import { fetchOrganizationEnergy, fetchSystemTreeNode, fetchBranchTree, fetchArea } from '@/services/dict';
import IEcharts from 'react-echarts-v3/src/full.js';
import { chartSolidOptions } from './eChartData';
import { testData } from './test';
import TypeTree from './components/TypeTree';
import _ from 'lodash';
import ExportFile from '@/components/Custom/ExportFile';

import styles from './index.less';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const Option = Select.Option;
const Report = () => {
  const [form] = Form.useForm();
  const [tab, setTab] = useState('organization');
  const [wdTab,setWdTab] = useState('area');//默认是区域树

  const [pickerType,setPickerType] = useState('year');

  const [wdType,setWdType] = useState();
  const [area,setArea] = useState([]);//area,
  const [organization,setOrganization] = useState([]);//organization,
  const [system,setSystem] = useState([]);//system,
  const [branch,setBranch] = useState([]);//branch,
  

  const [pickDate,setPickDate] = useState(new Date().getFullYear());

  const [radioChange,setRadioChange] = useState('year');


  const formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 }
  };
    /**
   * @tab切换
   */
    const tabChange = (key) => {
    setTab(key);
  };
   /**
    * 统计查询
    */
  const analyReportRequest = useRequest(
    goodAtAnalyzingReports,
    {
      manual: true,
      onSuccess: (res) => {
        
      },
    },
  );

  


  const handleSubmit = ( payload = {}) => {
    form.validateFields().then(values => {
        console.log(`handleSubmit values is :`, values);
        const objectsFatherId = values?.objectsFatherId; // parent;
        const { groupBy } = values; 
        if(Boolean(objectsFatherId) === false){
          message.info(`请选择统计对象节点`);
          return false;
        }else if(!values['startTimestamp-endTimestamp']){
          message.info(`请选择统计统计时间`);
          return false;
        }
        let hasChildIds = [];//统计对象,parent + children  ids 
        hasChildIds.push(objectsFatherId);
        values = {
            ...values,
            ...payload
        };
        let findNode,childIds = [];
        if(wdTab === 'organization'){
           findNode = getChildren(organization,objectsFatherId);
        }else if(wdTab === 'area'){
           findNode = getChildren(area,objectsFatherId);
        }else if(wdTab === 'system'){
           findNode = getChildren(system,objectsFatherId)
        }else if(wdTab === 'branch'){
           findNode = getChildren(branch,objectsFatherId)
        };
        const subItems = findNode?.subList || [];
        let ids = subItems.map(item => item.id) || [];
        console.log('ids params :>> ', ids);
        hasChildIds = [
          ...hasChildIds,
          ...ids
        ];
        let params = {
          ...values,
          statisticalObjects:hasChildIds,//统计对象
        };
        // console.log('findNode :>> ', findNode);
        const timeRangle = moment(values['startTimestamp-endTimestamp']);
        if(groupBy === 'year'){
          console.log('moment(timeRangle).startOf(year) :>> ', moment(timeRangle).startOf('year').format('YYYY/MM/DD HH:mm:ss'));
          params.startTimestamp = moment(moment(timeRangle).startOf('year').format('YYYY/MM/DD HH:mm:ss'));
          params.endTimestamp = moment(moment(timeRangle).endOf('year').format('YYYY/MM/DD HH:mm:ss'));
          params.groupBy = 'month';
        }else if(groupBy === 'quarter'){
          //季报
          params.startTimestamp = moment(timeRangle).startOf('quarter');
          params.endTimestamp = moment(timeRangle).endOf('quarter');
          params.groupBy = 'month';//返回月格式
        }else if(groupBy === 'month'){
          //月报
          params.startTimestamp = moment(timeRangle).startOf('month');
          params.endTimestamp = moment(timeRangle).endOf('month');
          params.groupBy = 'day';//返回天格式
        }
        delete params['startTimestamp-endTimestamp'];
      
        console.log('after object params :>> ', params);
         analyReportRequest.run(params);

    }).catch(() => { });
};

const changeReportType = val => {
  setPickerType(val);
  form.setFieldsValue({
    'startTimestamp-endTimestamp':null
  })
};

const wdTypeChange = type => {
  console.log('wdTypeChange type :>> ', type);
   setWdType(type);
   //重置
   form.setFieldsValue({
     objectsFatherId:null
   });
   if(type ==='1'){
     setWdTab('organization')
   }else if(type === '2'){
    setWdTab('area')
   }else if(type === '3'){
    setWdTab('system')
   }else if(type === '4'){
    setWdTab('branch')
   }
};

const onDatePickerChange = (date, dateString) => {
  console.log(date, dateString);
  setPickDate(dateString);
};

const onEmitTreeData = (data,treeType) => {
      if(treeType === 'area'){
          setArea(data);
      }else if(treeType === 'organization'){
        setOrganization(data);
      }
      else if(treeType === 'system'){
        setSystem(data);
      }
      else if(treeType === 'branch'){
        setBranch(data);
      }
};


const onRadioChange = e => {
  let oValue = e.target.value;
  setRadioChange(oValue);
  setPickerType(oValue);
  const nowYear = moment().format('YYYY');
  if(oValue === 'year'){
    //年
    const nowYear = moment().format('YYYY');
    form.setFieldsValue({
      groupBy:'year',
      'startTimestamp-endTimestamp':moment(nowYear)
    });
    setPickDate(nowYear);
  }else if(oValue === 'quarter'){
    form.setFieldsValue({
      groupBy:'quarter',
      'startTimestamp-endTimestamp':moment().quarter(moment().quarter()),//设置季度
    })
    setPickDate(`${nowYear}/Q${moment().quarter()}`);
  }else if(oValue ==='month'){
    form.setFieldsValue({
      groupBy:'month',
      'startTimestamp-endTimestamp':moment(moment().format('YYYY/MM'))
    });
    setPickDate(moment().format('YYYY/MM'));
  };
  handleSubmit();
}


useEffect(()=> {
  // console.clear();
  // const newObj = JSO
  console.log('treeObj--area--- :>> ',area);
  const currentYear = new Date().getFullYear();
  console.log('currentYear :>> ', currentYear);
   if(wdTab === 'area' && area && area.length > 0 ){
     //添加长度
     //第一次发起一个请求
     const firstAreaId = area[0]?.id;
     form.setFieldsValue({
        objectsFatherId:firstAreaId,
        'startTimestamp-endTimestamp':moment(String(currentYear))
     });
     handleSubmit();
   }
},[area]);

 const tableSourceObj = analyReportRequest?.data || [];



// console.log('testData :>> ', testData);
//  const bigData = testData.data;
const bigData = tableSourceObj;
const consumptionColumns = bigData?.formBos?.[0]?.consumption || [];
let secChildArr = consumptionColumns?.map((item,secIndex) => {
  return {
    ...item,
    title:item.purposeName,
    dataIndex:`consumption`,
    children:[
        {
          title: '本期',
          dataIndex: 'value',
          render(val,record,index){
             // console.log('consumption record :>> ', record,`index is:`,index,`secIndex is:`,secIndex);
           //  console.log('consumption record :>> ', record,`index is:`,index,`secIndex is:`,secIndex);
             if(record['consumption']){
                return record['consumption'][secIndex]['value'] || 0;
             }
          }
        },
        {
          title: '上期',
          dataIndex: 'lastPeriodValue',
          render(val,record,index){
            if(record['consumption']){
              return record['consumption'][secIndex]['lastPeriodValue'] || 0;
           }
         }
        },
        {
          title: '同比',
          dataIndex: 'sameTimeLastYearValueGrowthRate',
          render(val,record,index){
            if(record['consumption']){
              return record['consumption'][secIndex]['sameTimeLastYearValueGrowthRate'] || 0;
           }
         }
        },
        {
          title: '环比',
          dataIndex: 'lastPeriodGrowthRate',
          render(val,record,index){
            if(record['consumption']){
              return record['consumption'][secIndex]['lastPeriodGrowthRate'] || 0;
            }
          }
        },
        // {
        //   title: '本年度累计',
        //   dataIndex: '暂无',
        // },
        // {
        //   title: '上年度累计',
        //   dataIndex: '暂无',
        // }
   ]
  }
}) ;

const dataSource = bigData?.formBos;
let allSource = [];
dataSource?.forEach(item => {
  allSource.push(item);
  allSource = [
    ...allSource,
    ...item.subarea
  ]
});


const columns = [
  {
    title: '2021年年度综合概况',
    dataIndex: 'fullName',
    children:[
      {
        title: '指标名称',
        dataIndex: 'indexName',
        render(val,record){
          if(record?.subarea){
            return <span style={{fontWeight:'bold'}}>{val}</span>;
          }else{
            return  `${val}(子区域)`
          }
        }
      },
      {
        title: '计量单位',
        dataIndex: 'meteringUnit',
        render(val,record){
          if(record?.meteringUnit){
            return record?.meteringUnit
          }else{
            return record?.unit
          }
        }
      },
      ...secChildArr
      // {
      //     title: '消费',
      //     dataIndex: 'purposeName',
      //     children:[
      //         {
      //           title: '本期',
      //           dataIndex: '111',
      //           },
      //         {
      //           title: '上期',
      //           dataIndex: '111',
      //         },
      //         {
      //           title: '同比',
      //           dataIndex: 'lastPeriodValue',
      //         },
      //         {
      //           title: '环比',
      //           dataIndex: 'lastPeriodGrowthRate',
      //         },
      //         {
      //           title: '本年度累计',
      //           dataIndex: '111',
      //         },
      //         {
      //           title: '上年度累计',
      //           dataIndex: '111',
      //         }
      //   ]
      // },
      // {
      //     title: '外供',
      //     dataIndex: '111',
      //     children:[
      //       {
      //         title: '本期',
      //         dataIndex: '111',
      //       },
      //       {
      //         title: '上期',
      //         dataIndex: '111',
      //       },
      //       {
      //         title: '同比',
      //         dataIndex: '111',
      //       },
      //       {
      //         title: '环比',
      //         dataIndex: '111',
      //       },
      //       {
      //         title: '本年度累计',
      //         dataIndex: '111',
      //       },
      //       {
      //         title: '上年度累计',
      //         dataIndex: '111',
      //       }
      //     ]
      // }
    ]
  },
];
let bottomListData = bigData?.dataBos || [];
bottomListData = bottomListData.map(item => {
  // const colItems = item?.datas.map(subItem => ({
  //   dataIndex:subItem.time,
  //   title:subItem.time,
  // })) || [];
  let datas = item?.datas || [];
  let keysArr = [{
    title:'所在月份',
    dataIndex:'nameInfo'
  }];
  let convertData = []; //表格转换
  let consumptionArr = [];
  let oldKeyArr = [];
  let timeDataIndex = [];
  let newKeyArr = [];
  if(datas.length > 0 ){
    //keysArr = Object.keys(datas[0]);
   // valuesArr =Object.values(datas[0]);
     datas.forEach(keyItem => {
       let obj = {
          title:keyItem.time,
          dataIndex:keyItem.time
       };
       keysArr.push(obj);
       oldKeyArr = Object.keys(datas[0]);
       timeDataIndex.push(keyItem.time);// timeDataIndex;
     }); //所在年月
     consumptionArr = datas.map(keyItem => keyItem.consumption); //同比
     console.log('oldKeyArr :>> ', oldKeyArr);
     newKeyArr = _.remove(oldKeyArr,function(n){
        return n !== 'time';
     });
     console.log('after newKeyArr :>> ', newKeyArr);
  };
    let tableColumn = keysArr; //设置表格列
    // 组装表格的数据
    newKeyArr.forEach(keyName => {
        let obj = {};
        console.log(`newKeyArr keyName is:`,keyName);
        if(keyName === 'consumption'){
          obj['nameInfo'] = '用量';
        };
        timeDataIndex.forEach((keyDataIndex,index)=>{
          //find Item
          let resultArr =  datas.filter( dataItem => dataItem.time === keyDataIndex );
          obj[keyDataIndex] = resultArr[0]?.consumption;
        });
        console.log('obj :>> ', obj);
        convertData.push(obj);
    });
  console.log(`convertData end is:`, convertData);
  return {
    ...item,
    tableColumn,
    consumptionArr,
    convertData
  };
});



// console.log('allSource :>> ', allSource);
console.log('bottomListData :>> ', bottomListData);

const plainOptions = [
  { label: '本月', value: 'month' },
  { label: '本季度', value: 'quarter' },
  { label: '本年', value: 'year' },
];
  return (
    <div>
       <div className={ utilsStyles.subMenus } style={{padding: '0 15px'}}>
            <Tabs activeKey={tab} onChange={tabChange}>
              <TabPane tab='用能统计' key='organization'/>
              {/* <TabPane tab='区域用能' key='area'/>
              <TabPane tab='系统用能' key='system'/>
              <TabPane tab='支路用能' key='branch'/> */}
            </Tabs>
        </div>
        <div className={ utilsStyles.subMenus } style={{padding: '15px'}}>
            <Form form={form} onValuesChange = { handleSubmit } initialValues={{
                statisticalDimension:"2",
                groupBy:'year',//year也是通过月统计的
              }}>
                <Row style={{ width: '100%' }} gutter ={ 20 } className ="mdForm"> 
                    <Col xxl = { 4 } md = { 8 }>
                          <Form.Item name='statisticalDimension' label='统计维度' {...formItemLayout} style={{marginBottom:12}} >
                                <Select style={{ width: '100%' }} placeholder='请选择' onChange = { wdTypeChange }>
                                    <Option value="1">部门用能</Option>
                                    <Option value="2">区域用能</Option>
                                    <Option value="3">系统用能</Option>
                                    <Option value="4">支路用能</Option>
                                </Select>
                          </Form.Item>
                    </Col>
                    <Col xxl = { 4 } md = { 8 }>
                          <Form.Item name='objectsFatherId' label='统计对象' {...formItemLayout} style={{marginBottom:0}} >
                                <TypeTree tab = { wdTab } onEmitTreeData = { onEmitTreeData } />
                          </Form.Item>
                    </Col>
                    <Col xxl = { 4 } md = { 8 }>
                        <Form.Item  name ="groupBy" label='统计周期' {...formItemLayout} style={{marginBottom:0}}>
                                <Select style={{ width: '100%' }} placeholder='请选择' onChange = { changeReportType }>
                                    <Option value="year">年报告</Option>
                                    <Option value="quarter">季报告</Option>
                                    <Option value="month">月报告</Option>
                                </Select>
                          </Form.Item>
                    </Col>
                    <Col xxl = { 4 } md ={ 8 }>
                          <Form.Item name='startTimestamp-endTimestamp' label='选择日期' {...formItemLayout} style={{marginBottom:0}} >
                                <DatePicker onChange={ onDatePickerChange } picker={ pickerType } /> 
                          </Form.Item>
                    </Col>
                    <Col xxl = { 6 } md ={ 8 }>
                        {/* <Button type="default">本月</Button>
                        <Button type="default" style={{margin:'0 10px'}}>本季度</Button>
                        <Button type="default">本年</Button> */}
                        <div style={{display:'flex',justifyContent:'space-between'}}>
                          <div>
                              <Radio.Group 
                                options={plainOptions} 
                                onChange={ onRadioChange } 
                                value={ radioChange }
                                optionType="button"
                                buttonStyle="solid"
                            />
                          </div>
                          <div>
                            <ExportFile name="能耗报表" url="/device-service/energy-analysis/trend-lines-compare/goodAtAnalyzingReports/export" data={ {...analyReportRequest?.params[0], statisticalDimension: wdType ? parseInt(wdType, 10) : 2} }>
                                  <Button type="primary">导出</Button>
                            </ExportFile>
                          </div>
                        </div>
                    </Col>
                </Row>
            </Form>
        </div>
        <Card >
            <div className =  { styles.artMain }>
                <h1 className= { styles.title }>{pickDate}{pickerType === 'year'? '年' : ''}能源资源消费及运维管理状况报告</h1>
                <Table 
                  scroll = {
                    {
                      x: window.innerWidth  < 1440 ? '150%' : null
                    }
                  }
                  rowKey = { (record,index) =>  index }
                  columns={columns}
                  dataSource={ allSource }
                  className = { styles.tableReport }
                  loading = { analyReportRequest?.loading } 
                  pagination = { false }
                  rowClassName = {
                    (record, index) => {
                      if(record?.subarea){
                        return 'import-table-title'
                      }else{
                        return ''
                      }
                    }
                  }
                    />
                   
            </div>
        </Card>
         {
           bottomListData && bottomListData?.map((dataItem,index) => {
             return  <Card key={ index } title={`${pickDate}${pickerType === 'year' ? '年' : ''}${ dataItem?.typeName }消费数据`} style={{marginTop:20}}>
                      <Table dataSource={ dataItem?.convertData } columns= { dataItem?.tableColumn }  pagination = { false }
                        rowKey = { (record) =>  record.nameInfo }
                        scroll = {{
                          x:dataItem?.tableColumn?.length > 15 ? '150%' : false
                        }}
                      />
                    <IEcharts key={index}  style={{height:'300px',marginTop:20}} className="flex-item" option={ chartSolidOptions( dataItem?.convertData ) } />
             </Card>
           })
         }         
    </div>
  );
};

export default Report;