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

import { PlusOutlined } from '@ant-design/icons';
import { Button, Space, Table, Tag,Tooltip } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { DrawerForm, formRef } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
// import CAUpload from '@/components/CAUpload';
import { getAccountProductConnectList,getAccountProductConnectableList,saveAccountProductConnected } from './service';

const ResponsibilityCenterConnect = () => {
  const columns = [
    {
      title: '会计科目名称',
      dataIndex: 'accountingName',
      key: 'accountingName',
      hideInSearch: false,
      width: '20%',
    },
    {
      title: '会计科目编号',
      dataIndex: 'accountingCode',
      key: 'accountingCode',
      hideInSearch: true,
      width: '20%'
    },
    {
      title: '成本列表',
      dataIndex: 'productVOs',
      key: 'productVOs',
      hideInSearch: false,
      render: (productVOs) => {

        if (Array.isArray(productVOs)) {
          return productVOs.map((item, index) => { return <Tag key={index}>{item.productName}</Tag> })
        } else {
          return <></>
        }
      }
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      key: 'option',
      valueType: 'option',
      width: '15%',
      render: (_, record) => {
        const { isParent } = record;
        return !isParent ? [
          <a
            key="config"
            onClick={() => {
              setDrawerVisible(true);
              setCurrentRow(record);
            }}
          >
            设置对应
          </a>,
        ] : []
      },
    }
  ];
  const drawerTableColumns = [
    {
      title: 'Id',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
    },
    {
      title: '成本中心名称',
      dataIndex: 'name',
      key: 'name',
      hideInSearch: false,
    }

  ];

  const actionRef = useRef();  //表格
  const drawerFormRef = useRef(); //DrawerForm
  const actionDrawertableRef = useRef(); //Drawertable
  const [currentRow, setCurrentRow] = useState({});
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [selectedRowKeys,setSelectedRowKeys] = useState([]);
  const [defaultExpandedRowKeys,setDefaultExpandedRowKeys] = useState([]);

  /**
   * 
   * @param {Boolean} bool 
   */
  const drawerVisibleChange = (bool) => {
    // console.log({currentRow});
    const {productVOs} = currentRow;
  
    const selected = productVOs?productVOs.map(item=>item.id):[];
    if (bool)setSelectedRowKeys(selected==undefined?[]:selected);
    setDrawerVisible(bool);
    if (!bool) setCurrentRow(undefined);
  }


  //获取责任中心对应列表
  const getList = async (params = {}, sort, filter) => {
    const res = await getAccountProductConnectList(params);
    // console.log({res});

    const defaultKeys = res.data.list.map(item=>item.id);
    setDefaultExpandedRowKeys(defaultKeys);

    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

  //获取责任中心可绑定科室列表
  const getConnectableList = async (params = {}, sort, filter)=>{
    const {responsibilityId} = currentRow;
    const res = await getAccountProductConnectableList({...params,responsibilityId});
    const {data,status} = res;
    // console.log({res,data,status});
    if(status == 200){
        return {
          data:data,
          success:true,
        }
    }
  }

  const onExpandedRowsChange = (expandedRows)=>{
    setDefaultExpandedRowKeys([].concat(expandedRows))
}



  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="id"
        childrenColumnName="child"
   
        expandable={{ defaultExpandedRowKeys: [],expandedRowKeys:defaultExpandedRowKeys,onExpandedRowsChange:onExpandedRowsChange }}
        toolBarRender={() => []}

        pagination={{
          pageSize: 10,
        }}

        search={false}

      />
      <DrawerForm
        title="可绑定成本中心列表"
        formRef={drawerFormRef}
        visible={drawerVisible}
        onVisibleChange={(visible) => drawerVisibleChange(visible)}
        // onFinish={(value) => onSubmit({ ...values, ...value })}
        onFinish={async ()=>{
             console.log({selectedRowKeys,currentRow});
             const {id} = currentRow;
             const resp = await saveAccountProductConnected({id,products:selectedRowKeys});
             const {status} = resp;
             if(status==200){
              setDrawerVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
             }
        }}
      >
        <ProTable
          columns={drawerTableColumns}
          request={getConnectableList}
          rowKey="id"
          toolBarRender={() => []}
          actionRef={actionDrawertableRef}
          pagination={{
            pageSize: 10,
          }}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selectedRowKeys,
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            onChange:(selectedRowKeys)=>{
              setSelectedRowKeys([...selectedRowKeys]);
            }
          }}
          tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
              // console.log({selectedRowKeys});
              return (
                <Space size={24}>
                  <span>
                    已选 {selectedRowKeys.length} 项
                    <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                      取消选择
                    </a>
                  </span>
                </Space>
              )
          }}
          tableAlertOptionRender={() => {
            return (
              <Space size={16}>
                {/* <a>批量绑定</a> */}
              </Space>
            );
          }}
          search={false}

        />
      </DrawerForm>
    </PageContainer>
  );
};

export default ResponsibilityCenterConnect;
