/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-08-13 11:38:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /TracerMethodology_PC/src/pages/UserMana/index.js
 */

// import { PlusOutlined } from '@ant-design/icons';
import { Cascader, Form, Button, Drawer, Table } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {
  ProFormDatePicker,
  ProFormSelect,
} from '@ant-design/pro-form';
import { getAfterIncomeCollectionList, getAfterIncomeCollectionTableData } from './service';
import { getResponsibilityCenterList } from '@/pages/responsibilityCenter/service';
import { getCostProjecttList } from '@/pages/costProjectMana/service';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import './index.less';

const AfterCollectionSearch = () => {

  const [currentTime, setCurrentTime] = useState(moment().format('YYYY-MM'));
  const [selectableResponsibilityList, setSelectableResponsibilityList] = useState([]);
  const [selectedResponsibilityCode,setSelectedResponsibilityCode] = useState(null);
  const [selectedAccountingCode,setSelectedAccountingCode] = useState(null)
  
  // const [selectableCostProjectList, setSelectableCostProjectList] = useState([])

  const columns = [
    {
      title: '选择时间',
      key: 'date',
      hideInTable: true,
      dataIndex: 'date',
      renderFormItem: (item, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {

        if (type === 'form') {
          return null;
        }
        return (
          <Form.Item >
            <ProFormDatePicker initialValue={currentTime} fieldProps={{ picker: 'month', format: (value) => { return value.format('YYYY-MM') }, locale: locale,onChange:(moment)=>{setCurrentTime(moment.format('YYYYMM'))} }} name="date" />
          </Form.Item>
        )
      },
    },
    {
      title: '执行责任中心',
      key: 'responsibilityCode',
      hideInTable: true,
      fieldProps: (form, config) => {
        console.log({ form, config });
      },
      dataIndex: 'responsibilityName',
      renderFormItem: (item, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        // console.log({item,type, defaultRender,formItemProps, fieldProps,rest,form })
        if (type === 'form') {
          return null;
        }

        return (
          <Form.Item name="responsibilityCode">
            <Cascader options={selectableResponsibilityList}
              fieldNames={{
                label: 'responsibilityName',
                value: 'responsibilityCode',
                children: 'child',
              }}
              onChange={(val)=>{setSelectedResponsibilityCode(val[0])}}
              {...fieldProps}
            />
          </Form.Item>
        )
      },
    },
    {
      title: '成本项目',
      key: 'accountingCode',
      hideInTable: true,
      dataIndex: 'accountingCode',
      renderFormItem: (item, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        // console.log({item,type, defaultRender,formItemProps, fieldProps,rest,form })
        if (type === 'form') {
          return null;
        }

        return (
          <Form.Item name="accountingCode">
            <ProFormSelect
              request={async () => {
                const resp = await getCostProjecttList({ pageSize: 100 });
                const { status, data: { list } } = resp;
                if (status == 200) {
                
                  const arr = list.map(item => ({
                    'label': item.productName,
                    'value': item.productCode
                  }));

                  return arr;
                }
              }}
              fieldProps={{
                  onChange:(value)=>{setSelectedAccountingCode(value)}
              }}
              width="md"
              name="accountingCode"
            />
          </Form.Item>
        )
      },
    },
    {
      title: '年份',
      dataIndex: 'year',
      key: 'year',
      hideInSearch: true,
    },
    {
      title: '月份',
      dataIndex: 'month',
      key: 'month',
      hideInSearch: true,
    },
    {
      title: '科室编码',
      dataIndex: 'departmentCode',
      key: 'departmentCode',
      hideInSearch: true,
    },
    {
      title: '科室名称',
      dataIndex: 'departmentName',
      key: 'departmentName',
      hideInSearch: true,
    },
    {
      title: '责任中心编码',
      dataIndex: 'responsibilityCode',
      key: 'responsibilityCode',
      hideInSearch: true,
    },
    {
      title: '责任中心名',
      dataIndex: 'responsibilityName',
      key: 'responsibilityName',
      hideInSearch: true,
    },
    {
      title: '会计科目编码',
      dataIndex: 'accountingCode',
      key: 'accountingCode',
      hideInSearch: true,
    },
    {
      title: '会计科目名',
      dataIndex: 'accountingName',
      key: 'accountingName',
      hideInSearch: true,
    },
    {
      title: '成本项目编码',
      dataIndex: 'productCode',
      key: 'productCode',
      hideInSearch: true,
    },
    {
      title: '成本项目名',
      dataIndex: 'productName',
      key: 'productName',
      hideInSearch: true,
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      hideInSearch: true,
    },
  ];




  const actionRef = useRef();
  const [totalCount, setTotalCount] = useState(0);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [reportTableColumns, setReportTableColumns] = useState([]);
  const [totalData,setTotalData] = useState([]);

  //获取列表
  const getList = async (params = {}, sort, filter) => {
    const { date } = params;
    console.log(moment(date).format('YYYY-MM'));
    const res = await getAfterIncomeCollectionList({ ...params, date: moment(date).format('YYYYMM') });
    if (res && res.status) {
      const { data: { totalAmount } } = res;
      setTotalCount(totalAmount);
      return {
        data: res.data.list,
        total: res.data.totalCount,
        success: res.success,
      };
    }

  };


  const renderDrawerHandle = () => {
   
      setDrawerVisible(true);

    
  }

  const getReportData = async (params = {}, sort, filter)=>{

    const resp = await getAfterIncomeCollectionTableData({...params,date:currentTime,responsibilityCode:selectedResponsibilityCode,accountingCode:selectedAccountingCode});
    const { status, data: { titleMap, realData, totalMap } } = resp;
    if (status == 200) {
      const titleMapToArr = Object.entries(titleMap);
      const totalMapToArr = Object.entries(totalMap);
      const columns = [...titleMapToArr].map((item, index) => {
        if (index == 0 || index == [...titleMapToArr].length - 1) {
          return {
            title: item[1],
            dataIndex: item[0],
            key: item[0],
            fixed:index == 0?'left':'right',
            hideInSearch: true,
            width: 100,
          }
        }
        return {
          title: item[1],
          dataIndex: item[0],
          key: item[0],
          hideInSearch: true,
          width: 500,
        }
      });
      
      setReportTableColumns(columns);
      setTotalData(totalMapToArr);

      return Promise.resolve({
        data: realData,
        success: true,
      });
    }
  }




  useEffect(async () => {
    const responsibilityList = await getResponsibilityCenterList({ pageSize: 50 });
    const { data: { list } } = responsibilityList;
    setSelectableResponsibilityList(list);
  }, []);

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button key='reportBtn' type='primary' onClick={() => renderDrawerHandle()}>报表数据</Button>
        ]}
        pagination={{
          pageSize: 10,
        }}
        search={{
          defaultCollapsed: false,
          labelWidth: 'auto',
        }}
        footer={() => <a>{`合计：${totalCount}`}</a>}

      />

      <Drawer
        title="报表数据"
        placement="right"
        width={'90%'}
        destroyOnClose={true}
        closable={true}
        onClose={() => setDrawerVisible(false)}
        visible={drawerVisible}
      >
        <ProTable
          columns={reportTableColumns}
          request={getReportData}
          actionRef={actionRef}
          rowKey="id"
          bordered
          pagination={false}
          search={false}
          scroll={{ x: 1500, y: 300 }}
          summary={() => (
            <Table.Summary fixed >
              <Table.Summary.Row className="rowCell">
                <Table.Summary.Cell className="firstCell" index={0}>合计</Table.Summary.Cell>
                {
                  totalData.map((item, index) => {
                    return (
                      <Table.Summary.Cell key={index}  className={index == totalData.length-1 ? 'ant-table-cell ant-table-cell-fix-right ant-table-cell-fix-right-last' : 'cell'} index={index+1}>{item[1]}</Table.Summary.Cell>
                    )
                  })
                }
              </Table.Summary.Row>
            </Table.Summary>
          )}
        // footer={() => <a>{`合计：${totalCount}`}</a>}

        />
      </Drawer>

    </PageContainer>
  );
};

export default AfterCollectionSearch;
