/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-08-13 20:18:17
 * @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, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';

import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
import DrawerContent from './components/DrawerContent';
import { getVisitsAndBedDayCostSettingList, delVisitsAndBedDayCostSettingList, addVisitsAndBedDayCostSettingList, 
  getVisitsAndBedDayCostSettingListById,editVisitsAndBedDayCostSettingList } from './service';
import { getCostshareparamList } from '@/pages/costAllocationParamsSetting/service';
import { getReportProjectSettingList } from '@/pages/baseSetting/reportProjectSetting/service';

const DistrictMana = () => {
  const columns = [
    {
      title: '分配方式',
      dataIndex: 'allocation',
      key: 'allocation',
      hideInSearch: true,
      render: num => <>{num == 1 ? '按照收入比例分配' : '按照固定比例分配'}</>
    },
    {
      title: '收入类型',
      dataIndex: 'incomeType',
      key: 'incomeType',
      hideInSearch: true,
      render: num => <>{num == 1 ? '门诊方式' : '住院方式'}</>
    },
    {
      title: '对应值',
      dataIndex: 'incomeFileName',
      key: 'incomeFileName',
      hideInSearch: false,
    },
    {
      title: '分摊参数编码',
      dataIndex: 'shareParamCode',
      key: 'shareParamCode',
      hideInSearch: true,
    },
    {
      title: '分摊参数名称',
      dataIndex: 'shareParamName',
      key: 'shareParamName',
      hideInSearch: true,
    },
    {
      title: '成本对应',
      dataIndex: 'costCorrespondingName',
      key: 'costCorrespondingName',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            edithandle(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="subscribeAlert"
          title="是否确定删除?"
          onConfirm={() => {
            setCurrentRow(record);
            delListHandler(record);
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const drawerTableColumns = [
    {
      title: '分摊参数名称',
      dataIndex: 'shareParamName',
      key: 'shareParamName',
      hideInSearch: true,
    },
    {
      title: '分摊参数代码',
      dataIndex: 'shareParamCode',
      key: 'shareParamCode',
      hideInSearch: true,
    }
  ]

  const drawerTableReportColumns = [
    {
      title: '报表项目名',
      dataIndex: 'reportName',
      key: 'reportName',
      hideInSearch: true,
    },
    {
      title: '编号',
      dataIndex: 'num',
      key: 'num',
      hideInSearch: true,
    }
  ]

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const actionRef = useRef();
  const ref = useRef();   //新增表单
  const [updateFormRef,setUpdateFormRef] = useState(null);
  const [currentRow, setCurrentRow] = useState({});
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [type, setType] = useState(0);   //1 分摊参数，2 报表
  const [selectedShareparams, setSelectedShareparams] = useState(null);
  const [selectedIncome, setSelectedIncome] = useState(null);
  const [activeKey, setActiveKey] = useState('0');
  const [selectedCost, setSelectedCost] = useState(null);
  const [ifcostCorresponding, setIfcostCorresponding] = useState(true);
  const [dataById, setDataById] = useState(null);
  const [edit,setEdit] = useState(false);
  const [expandedRowKeys,setExpandedRowKeys] = useState([]);
  const [defaultReportTableSelected,setDefaultReportTableSelected] = useState([]);


  const reportTableTypes = ['损益表','完全成本法表','变动成本表','全院损益表','全成本报表'];

  /**
   *
   * @param {Boolean} bool 弹窗展示状态
   */
  const updateModalVisibleChange = (bool) => {

    
    handleUpdateModalVisible(bool);
    if (!bool) setCurrentRow(undefined);
  };

  //获取列表
  const getList = async (params = {}, sort, filter) => {
    const res = await getVisitsAndBedDayCostSettingList({...params});
    // console.log({res});
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

  //获取drawer 列表
  const getDrawerTableList = async (params = {}, sort, filter) => {
    if (type == 1) {
      const res = await getCostshareparamList({ ...params });
      return {
        data: res.data.list,
        total: res.data.totalCount,
        success: res.success,
      };
    }
    if (type == 2) {
      const res = await getReportProjectSettingList({ ...params, reportType: activeKey });

      const arr = res.data.list.map(item=>item.num);
      setExpandedRowKeys(arr);

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

  };

  /**
   *
   * @param {Object} value 删除项数据
   */
  const delListHandler = async (value) => {
    const resp = await delVisitsAndBedDayCostSettingList(value);
    // console.log({ resp });
    if (resp.status) {
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };

  const edithandle = async (record) => {
    setEdit(true);
    const { id } = record;
    //获取指定id数据
    const resp = await getVisitsAndBedDayCostSettingListById({ id });
    // console.log({ resp });
    const { status, data } = resp;
    if (status == 200) {
      setDataById(data);
    }
    setCurrentRow(record);
    handleUpdateModalVisible(true);
  }


  const openDrawerHandle = (num, bool) => {
    setType(num);
    setIfcostCorresponding(bool);
    if(!edit)setDefaultReportTableSelected([].concat([]));
    if(bool&&edit){
      console.log('成本');
      const {costFileType,costCorresponding} = dataById;
      setDefaultReportTableSelected([].concat([costCorresponding]));
      setActiveKey(`${costFileType}`);
    }
    if(!bool&&edit){
      console.log('收入');
      const {incomeFileType,incomeFieldNum} = dataById;
      setDefaultReportTableSelected([].concat([incomeFieldNum]));
      setActiveKey(`${incomeFileType}`);
    }
    setDrawerVisible(true);
  }
 


  useEffect(() => {

  }, []);


  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setEdit(false);
              handleModalVisible(true);
            }}
          >
            新增
          </Button>
        ]}

        pagination={{
          pageSize: 10,
        }}
        search={{
          defaultCollapsed: false,
          labelWidth: 'auto',
        }}

      />
      {
        <ModalForm
          title="新增诊次/床日成本设置"
          width="800px"
          labelCol={{ span: 5, offset: 3 }}
          layout={'horizontal'}
          formRef={ref}
          visible={createModalVisible}
          onVisibleChange={(bool) => {
            if (ref.current) {
              ref.current.resetFields();
            }
            handleModalVisible(bool);
          }}
          onFinish={async (value) => {
            const { allocation, incomeType } = value;
            const { shareParamCode, shareParamName } = selectedShareparams;
            const { num: incomeFieldNum, reportName: incomeFileName,reportType:incomeFileType } = selectedIncome;
            const { num: costCorresponding, reportName: costCorrespondingName,reportType:costFileType } = selectedCost;
            const data = { 
               allocation, incomeType, shareParamCode, shareParamName, incomeFieldNum,
               incomeFileName:`[${reportTableTypes[incomeFileType]}] ${incomeFileName}`,
               costCorresponding, costCorrespondingName:`[${reportTableTypes[costFileType]}] ${costCorrespondingName}`,
               incomeFileType,costFileType}
            // console.log({data});
            const success = await addVisitsAndBedDayCostSettingList(data);
            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
            //清空
            setSelectedCost(null);
            setSelectedShareparams(null);
            setSelectedIncome(null);
          }}
        >
          <ProFormSelect
            rules={[
              {
                required: true,
                message: '请选择分配方式',
              },
            ]}
            options={[
              {
                value: 1,
                label: '按收入比例分配',
              },
              // {
              //   value: 2,
              //   label: '按照固定比例分配',
              // },
            ]}
            width="sm"
            name="allocation"
            label="分配方式"
          />
          <ProFormSelect
            rules={[
              {
                required: true,
                message: '请选择收入类型',
              },
            ]}
            options={[
              {
                value: 1,
                label: '住院收入',
              },
              {
                value: 2,
                label: '门诊收入',
              },
            ]}
            width="sm"
            name="incomeType"
            label="收入类型"
          />
          <ProFormText
            fieldProps={{
              onFocus: () => { openDrawerHandle(1) },
              allowClear:false
            }}
            rules={[
              {
                required: true,
                message: '请选择分摊参数',
              },
            ]}
            width="sm"
            name="shareParamName"
            label="选择分摊参数"
          />
          <ProFormText
            fieldProps={{
              onFocus: () => { openDrawerHandle(2, false); },
              allowClear:false
            }}
            rules={[
              {
                required: true,
                message: '请选择对应收入字段',
              },
            ]}
            width="sm"
            name="incomeFileName"
            label="对应收入字段"
          />
          <ProFormText
            fieldProps={{
              onFocus: () => { openDrawerHandle(2, true); },
              allowClear:false
            }}
            rules={[
              {
                required: true,
                message: '请选择对应成本字段',
              },
            ]}
            width="sm"
            name="costCorrespondingName"
            label="对应成本字段"
          />
        </ModalForm>
      }


      {/* 抽屉内容 */}
      {
        type == 1 ? <DrawerContent
          columns={drawerTableColumns}
          visible={drawerVisible}
          currentRow={currentRow}
          title="选择分摊参数"
          type='radio'
          defaultSelected={edit?[dataById.shareParamCode]:[]}
          onVisibleChange={(bool) => setDrawerVisible(bool)}
          renderListFunc={getDrawerTableList}
          config={{ tableSearch: false, rowKeys: 'shareParamCode' }}
          onFinishFunc={async (value, selectedRowKeys, selectedRows) => {
            // console.log({ '分摊': selectedRows })
            setSelectedShareparams(selectedRows[0]);
            const { shareParamName } = selectedRows[0];
            if(edit){
              updateFormRef?.current?.setFieldsValue({
                shareParamName: shareParamName,
              });
            }else{
              ref?.current?.setFieldsValue({
                shareParamName: shareParamName,
              });
            }
            
            setDrawerVisible(false);

          }}
        /> : <DrawerContent
          columns={drawerTableReportColumns}
          visible={drawerVisible}
          currentRow={currentRow}
          title={ifcostCorresponding ? '选择对应成本字段' : '选择对应收入字段'}
          type='radio'
          tabList={[
            {
              tab: '损益表',
              key: 0,
            },
            {
              tab: '完全成本法表',
              key: 1,
            },
            {
              tab: '变动成本表',
              key: 2,
            },
            {
              tab: '全院损益表',
              key: 3,
            },
            {
              tab: '全成本报表',
              key: 4,
            },
          ]}
          // tabActiveKey='3'
          renderCell={(checked, record, index, originNode) => {
            const { children } = record;
            if (!children || children.length == 0) {
              return originNode
            } else {
              return null
            }
          }}
          onTabChange={(key, ref) => {
            setActiveKey(key);
            if (ref.current) ref.current.reload()
          }}
          expandable={{
            expandedRowKeys:expandedRowKeys
          }}
          defaultSelected={defaultReportTableSelected}
          onVisibleChange={(bool) => setDrawerVisible(bool)}
          renderListFunc={getDrawerTableList}
          config={{ tableSearch: false,rowKeys:'num'}}

          tabActiveKey={activeKey}

          onFinishFunc={async (value, selectedRowKeys, selectedRows) => {
            // console.log({ '报表': selectedRows,'ifcostCorresponding':ifcostCorresponding,value });

            if(selectedRows.length>0){
              const { reportName,reportType } = selectedRows[0];
              if (!ifcostCorresponding) {
                setSelectedIncome(selectedRows[0]);
                if(edit){
                  updateFormRef?.current?.setFieldsValue({
                    incomeFileName: reportName,
                  });
                }else{
                  ref?.current?.setFieldsValue({
                    incomeFileName: reportName,
                  });
                }
              }
              if (ifcostCorresponding) {
                setSelectedCost(selectedRows[0]);
                if(edit){
                  updateFormRef?.current?.setFieldsValue({
                    costCorrespondingName: reportName,
                  });
                }else{
                  ref?.current?.setFieldsValue({
                    costCorrespondingName: reportName,
                  });
                }
                
              }
            }
            
            setDrawerVisible(false);
            setActiveKey('0');
          }}
        />
      }


      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          // console.log({ '编辑': value });
            const {id} = currentRow;
            const { allocation, incomeType } = value;
            let data = {id,allocation,incomeType};
            if(selectedShareparams){
              const { shareParamCode, shareParamName } = selectedShareparams;
              data = {...data,shareParamCode, shareParamName}
            }else{
              const { shareParamCode, shareParamName } = dataById;
              data = {...data,shareParamCode, shareParamName}
            }

            if(selectedIncome){
              const { num: incomeFieldNum, reportName: incomeFileName,reportType:incomeFileType } = selectedIncome;
              data = {...data,incomeFieldNum,incomeFileName,incomeFileType}
            }else{
              const { incomeFieldNum, incomeFileName,incomeFileType } = dataById;
              data = {...data,incomeFieldNum,incomeFileName,incomeFileType}
            }
            
            if(selectedCost){
              const { num: costCorresponding, reportName: costCorrespondingName,reportType:costFileType } = selectedCost;
              data = {...data,costCorresponding,costCorrespondingName,costFileType}
            }else{
              const { costCorresponding, costCorrespondingName,costFileType } = dataById;
              data = {...data,costCorresponding,costCorrespondingName,costFileType}
            }
            
            

            const success = await editVisitsAndBedDayCostSettingList(data);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }

           //清空
           setSelectedCost(null);
           setSelectedShareparams(null);
           setSelectedIncome(null);
           setDataById(null);
           setDefaultReportTableSelected([]);
           
        }}
        
        openDrawerHandle={openDrawerHandle}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        getFormRef={ref=>setUpdateFormRef(ref)}
        updateModalVisible={updateModalVisible}
        updateModalVisibleChange={updateModalVisibleChange}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default DistrictMana;
