/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-07-30 15:21:27
 * @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, ProFormDigit } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
// import CAUpload from '@/components/CAUpload';
import { getApportionmentLevelList, editApportionmentLevelList, delApportionmentLevel, addApportionmentLevel } from './service';

const ApportionmentLevel = () => {
  const columns = [

    {
      title: '分摊层级名',
      dataIndex: 'shareName',
      key: 'shareName',
      hideInSearch: false,
    },
    {
      title: '分摊层级序号',
      dataIndex: 'leverSort',
      key: 'leverSort',
      hideInSearch: true,
    },
    {
      title: '目标层级',
      dataIndex: 'targetLevel',
      key: 'targetLevel',
      hideInSearch: true,
    },
    {
      title: '计算方式',
      dataIndex: 'calcType',
      key: 'calcType',
      hideInSearch: true,
      render: (text) =><>{text == 0 ? '合并计算' : '分开计算'}</>,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      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 [currentRow, setCurrentRow] = useState({});

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

  //获取科室列表
  const getList = async (params = {}, sort, filter) => {

    const res = await getApportionmentLevelList(params);
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

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

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新增
          </Button>
        ]}
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
        }}
        pagination={{
          pageSize: 10,
        }}
        search={{
          defaultCollapsed: false,
          labelWidth: 'auto',
        }}
        tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
          // console.log({selectedRowKeys, selectedRows, onCleanSelected});
          return (
            <Space size={16}>
              <span>
                <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
              <Popconfirm
                title="是否确定批量删除选中列表?"
                onConfirm={() => {
                  delListHandler({ id: selectedRowKeys });
                }}
              >
                <a>批量删除</a>
              </Popconfirm>
            </Space>
          );
        }}
      />

      <ModalForm
        title="新增分摊层级"
        width="800px"
        labelCol={{ span: 5, offset: 3 }}
        layout={'horizontal'}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await addApportionmentLevel(value);
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormDigit
          label="分摊层级序号"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.leverSort" defaultMessage="分摊层级序号是必填项" />
              ),
            },
          ]}
          width="sm"
          name="leverSort"
          min={1} max={100}
        />
    
        <ProFormText
          label="分摊层级名"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.shareName" defaultMessage="分摊层级名是必填项" />
              ),
            },
          ]}
          width="sm"
          name="shareName"
        />
        <ProFormDigit
          label="目标层级"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.targetLevel" defaultMessage="目标层级是必填项" />
              ),
            },
          ]}
          min={1} max={100}
          width="sm"
          name="targetLevel"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.calcType" defaultMessage="请选择计算方式" />
              ),
            },
          ]}
          options={[
            {
              value: 0,
              label: '合并计算',
            },
            {
              value: 1,
              label: '分开计算',
            },
          ]}
          width="sm"
          name="calcType"
          label="计算方式"
        />

      </ModalForm>

      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          console.log({ '编辑': value });
          const success = await editApportionmentLevelList(value);

          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 ApportionmentLevel;
