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


import { Space, Table, Tag } from 'antd';
import React, { useState, useRef } from 'react';

import { PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { DrawerForm } from '@ant-design/pro-form';

import { getResponsibilityCenterConnectList,getResponsibilityCenterConnectableList,saveResponsibilityCenterConnected } from './service';

const ResponsibilityCenterConnect = () => {
  const columns = [
    {
      title: '责任中心名称',
      dataIndex: 'responsibilityName',
      key: 'responsibilityName',
      hideInSearch: false,
      width: '20%',
      ellipsis: true,
    },
    {
      title: '责任中心Id',
      dataIndex: 'responsibilityId',
      key: 'responsibilityId',
      hideInSearch: true,
      width: '20%',
      ellipsis: true,
    },
    {
      title: '部门列表',
      dataIndex: 'departments',
      key: 'departments',
      hideInSearch: false,
      ellipsis: true,
      render: (departments) => {

        if (Array.isArray(departments)) {
          return departments.map((item, index) => { return <Tag key={index}>{item.departmentName}</Tag> })
        } else {
          return <></>
        }
      }
    },
    {
      title:'操作',
      dataIndex: 'option',
      key: 'option',
      valueType: 'option',
      width: '15%',
      render: (_, record) => {
        const {isGatherCenter } = record;
        // console.log({record});
        return isGatherCenter==2 ? [
          <a
            key="config"
            onClick={() => {
              setDrawerVisible(true);
              setCurrentRow(record);
            }}
          >
            绑定科室
          </a>,
        ] : []
      },
    }
  ];
  const drawerTableColumns = [
    {
      title: 'Id',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '科室名称',
      dataIndex: 'departmentName',
      key: 'departmentName',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '科室编码',
      dataIndex: 'departmentCode',
      key: 'departmentCode',
      hideInSearch: true,
      ellipsis: true,
    },

  ];

  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 {departments=[]} = currentRow;
    const selected = departments.map(item=>item.departmentId);
    if (bool)setSelectedRowKeys(selected==undefined?[]:selected);
    setDrawerVisible(bool);
    if (!bool) setCurrentRow(undefined);
  }


  //获取责任中心对应列表
  const getList = async (params = {}, sort, filter) => {
    const res = await getResponsibilityCenterConnectList(params);
    const defaultKeys = res.data.list?res.data.list.map(item=>item.responsibilityId):[];
    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 getResponsibilityCenterConnectableList({...params,responsibilityId});
    const {data,status} = res;

    if(status == 200){
        return {
          data:data,
          success:true,
        }
    }
  }

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


  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="responsibilityId"
        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 {responsibilityId} = currentRow;
             const resp = await saveResponsibilityCenterConnected({responsibilityId,departmentIds: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;
