/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-08-02 00:53: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 { Button, Popconfirm, Table, Space } 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 { ModalForm, ProFormText, ProFormSelect, ProFormDependency } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
// import CAUpload from '@/components/CAUpload';
import { getResponsibilityCenterList, editResponsibilityCenterList, delResponsibilityCenter, addResponsibilityCenter } from './service';
import { getApportionmentLevelListNoPage } from '../apportionmentLevel/service';

const responsibilityCenter = () => {
  const columns = [
    {
      title: '责任中心名称',
      dataIndex: 'responsibilityName',
      key: 'responsibilityName',
      hideInSearch: false,
      width: '15%'
    },
    {
      title: '责任中心编码',
      dataIndex: 'responsibilityCode',
      key: 'responsibilityCode',
      hideInSearch: true,
    },
    // {
    //   title: '责任中心级别',
    //   dataIndex: 'responsibilityLevel',
    //   key: 'responsibilityLevel',
    //   hideInSearch: true,
    //   width: '10%'
    // },
    {
      title: '是否汇总中心',
      dataIndex: 'isGatherCenter',
      key: 'isGatherCenter',
      hideInSearch: true,
      render: (text) => <>{text == 1 ? '是' : '否'}</>,
      width: '15%'
    },
    {
      title: '责任类型',
      dataIndex: 'responsibilityType',
      key: 'responsibilityType',
      hideInSearch: true,
      width: '15%',
      render: (text) => <>{text == 1 ? '收益中心' : '成本(费用)中心'}</>,
    },
    {
      title: '分摊级别',
      dataIndex: 'shareLevel',
      key: 'shareLevel',
      hideInSearch: true,
      width: '10%'
    },
    {
      title: '分摊级别名称',
      dataIndex: 'shareName',
      key: 'shareName',
      hideInSearch: true,
      width: '15%'
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      width: '15%',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="subscribeAlert"
          title="是否确定删除?"
          onConfirm={() => {
            setCurrentRow(record);
            delListHandler(record);
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const actionRef = useRef();  //表格
  const ref = useRef();   //新增表单
  const [currentRow, setCurrentRow] = useState({});
  const [selectedLevelList,setSelectedLevelList] = useState(null); //可选的分摊层级列表
  const [selectedLevel,setSelectedLevel] = useState(null);

  /**
   *
   * @param {Boolean} bool 弹窗展示状态
   */
  const updateModalVisibleChange = (bool) => {
    handleUpdateModalVisible(bool);
    if (!bool) setCurrentRow(undefined);
  };


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

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

  //展开table
  const expandedRowRender = (record, index, indent, expanded) => {
    // console.log({ record, index, indent, expanded });
    const _columns = columns.filter(item => !(['id'].includes(item.key)));
    return (
      <ProTable
        columns={[..._columns]}
        headerTitle={false}
        showHeader={false}
        search={false}
        options={false}
        rowKey="id"
        dataSource={record.child}
        pagination={false}
      />
    );
  };

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

        pagination={{
          pageSize: 10,
        }}

        search={false}

      />

      <ModalForm
        title="新增责任中心"
        width="800px"
        labelCol={{ span: 5, offset: 3 }}
        layout={'horizontal'}
        visible={createModalVisible}
        onVisibleChange={(bool)=>{
          if (ref.current) {
            ref.current.resetFields();
          }
          handleModalVisible(bool);
        }}
        formRef={ref}
        onFinish={async (value) => {
          console.log({'新增':value,selectedLevel})
          const {shareLevel} = value;
          const body = {...value,shareName:selectedLevel.shareName,shareId:selectedLevel.id}
          // console.log({body});
          // return;
          const success = await addResponsibilityCenter(body);
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);

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

        <ProFormSelect
          name="id"
          label="责任管理中心"
          showSearch
          request={async ({ keyWords }) => {
            const res = await getResponsibilityCenterList();
            if(res.status == 200){
              // console.log({res});
                 const filter_arr = res.data.list.filter(item=>{
                  //  console.log({item});
                   if(keyWords){
                    return item.responsibilityName.indexOf(keyWords) != -1
                   }else {
                    return item
                   }
                   
                 });
                 const arr = filter_arr.map(item=>({label:item.responsibilityName, value:item.id}));
                 return arr;
            }else {
                 return [];
            }

          }}
          width='md'
          placeholder="选择需要新增在哪个责任中心下，默认新增最外层"
          rules={[{ required: false, message: '' }]}
        />

        <ProFormText
          label="责任中心名"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.responsibilityName" defaultMessage="医院名是必填项" />
              ),
            },
          ]}
          width="sm"
          name="responsibilityName"
        />
        <ProFormText
          label="责任中心编码"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.responsibilityCode" defaultMessage="责任中心编码是必填项" />
              ),
            },
          ]}
          width="sm"
          name="responsibilityCode"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.isGatherCenter" defaultMessage="请选择是否为汇总中心" />
              ),
            },
          ]}
          options={[
            {
              value: 1,
              label: '是',
            },
            {
              value: 2,
              label: '否',
            },
          ]}
          width="sm"
          name="isGatherCenter"
          label="是否汇总中心"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.responsibilityType" defaultMessage="请选择责任类型" />
              ),
            },
          ]}
          options={[
            {
              value: 1,
              label: '收益中心',
            },
            {
              value: 2,
              label: '成本(费用)中心',
            },
          ]}
          width="sm"
          name="responsibilityType"
          label="选择责任类型"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.shareLevel" defaultMessage="请选择分摊级别" />
              ),
            },
          ]}
          fieldProps={{
            onChange: async (val) => {
              const resp = await getApportionmentLevelListNoPage();
              const {status,data} = resp;
              if(status==200){
                const needItem = data.list.filter(item=>item.leverSort == val);
                setSelectedLevel(needItem[0]);
              }
            },
          }}
          request={ async ()=>{
                const resp = await getApportionmentLevelListNoPage();
                const {status,data} = resp;
                if(status==200){
                    setSelectedLevelList(data.list);
                    return data.list.map(item=>({label:`级别${item.leverSort}-${item.shareName}`,value:item.leverSort}))
                }else{
                   return []
                }
          }}
          width="sm"
          name={['shareLevel']}
          label="选择分摊级别"
        />
      </ModalForm>

      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          console.log({ '编辑': value });
         
          const {responsibilityLevel,selectedLevel} = value;
          const body = selectedLevel.length==0?{
            //没有修改分摊层级
            ...value,shareLevelId:responsibilityLevel
          }:{
                  //修改了分摊层级
                  ...value,shareLevelId:selectedLevel[0].id
          }
          // console.log({'editBody':body});
          // return;
          const success = await editResponsibilityCenterList(body);

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

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        updateModalVisibleChange={updateModalVisibleChange}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default responsibilityCenter;
