/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-08-02 18:55:53
 * @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, message, Input, Drawer } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage,useModel } from 'umi';
import { PageContainer, FooterToolbar } 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 CAUpload from '@/components/CAUpload';
import { getDepartmentList ,editDepartmentList,delDepartment,addDepartment,importExcel} from './service';

const DepartmentMana = () => {
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'name',
      hideInSearch: true,
      render: (text) => <a>{text}</a>,
    },
    {
      title: '科室名',
      dataIndex: 'departmentName',
      key: 'departmentName',
      hideInSearch: false,
    },
    {
      title: '科室编号',
      dataIndex: 'departmentCode',
      key: 'departmentCode',
      hideInSearch: false,
    },
    // {
    //   title: '医院Id',
    //   dataIndex: 'hospId',
    //   key: 'hospId',
    //   hideInSearch: true,
    // },
    {
      title: '创建时间',
      dataIndex: 'createDateTime',
      key: 'createTime',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            console.log({ record });
            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({});
  const { initialState, setInitialState } = useModel('@@initialState');
  const {currentUser:{token}} = initialState;

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

  //获取科室列表
  const getList = async (params = {}, sort, filter) => {
    const res = await getDepartmentList(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 delDepartment(value);
    if(resp.status==200){
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };

  //自定义上传回调
  const customRequestCallback = async (formData)=>{
    const resp = await importExcel({formData},{
      // 'content-type': 'application/json'
      'content-type':'multipart/form-data',
    })
    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>,
          <CAUpload  
          templateHref={'/costAccount/excel/getDepartmentTemplate'}
          url='/costAccount/excel/importDepartment'
          importSuccessCallback={() =>{}}
          token={token}
          customRequestCallback={customRequestCallback}
    />
        ]}
        pagination={{
          pageSize: 10,
        }}
        search={{
          defaultCollapsed: false,
          labelWidth: 'auto',
        }}
      />

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

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="科室名"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.departmentName" defaultMessage="科室名是必填项" />
              ),
            },
          ]}
          width="sm"
          name="departmentName"
        />
        <ProFormText
          label="科室编号"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.departmentCode" defaultMessage="科室编号是必填项" />
              ),
            },
          ]}
          width="sm"
          name="departmentCode"
        />
      </ModalForm>

      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          console.log({'编辑':value});
          const success = await editDepartmentList(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 DepartmentMana;
