/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-07-31 19:22:20
 * @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, Modal } 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 { getUserList, addUser, editUser, delUser,importExcel } from './service';

const UserMana = () => {
  const columns = [
    {
      title: 'Id',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
      render: (text) => <a>{text}</a>,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '用户名',
      dataIndex: 'account',
      key: 'account',
      hideInSearch: true,
    },
    {
      title: '在职状态',
      dataIndex: 'hospitalStatus',
      key: 'hospitalStatus',
      hideInSearch: true,
      render: (text) => <a>{text == 1 ? '在职' : '离职'}</a>,
    },
    {
      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);
            delUserHandler(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;
  // const [shareParamsSetting,setShareParamsSetting] = useState(false);  //是否分摊参数设置

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

  //获取用户列表
  const getUserlist = async (params = {}, sort, filter) => {
    const res = await getUserList(params);
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

  /**
   *
   * @param {Object} value 删除项数据
   */
  const delUserHandler = async (value) => {
    const resp = await delUser(value);
    if(resp.msg){
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };
  //自定义上传回调
  const customRequestCallback = async (formData)=>{
    const resp = await importExcel({formData},{
      // 'content-type': 'application/json'
      'content-type':'multipart/form-data',
    })
    console.log({resp});

    const {status} = resp;
    if(status==200){
      Modal.success({
         title:'导入成功！',
         onOk:()=>{
          if (actionRef.current) {
            actionRef.current.reload();
          }
         }
      })
    }
  }

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getUserlist}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新增
          </Button>,
          <CAUpload  
                templateHref={'/costAccount/excel/getImportUserTemplate'}
                url='/costAccount/excel/importUser'
                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 addUser(value);
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="姓名"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.ruleName" defaultMessage="人员名是必填项" />
              ),
            },
          ]}
          width="sm"
          name="name"
        />
        <ProFormText
          label="账户"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.ruleName" defaultMessage="账户名是必填项" />
              ),
            },
          ]}
          width="sm"
          name="account"
        />
        <ProFormText
          label="密码不修改留空"
          rules={[
            {
              required: false,
              message: (
                <FormattedMessage id="pages.searchTable.password" defaultMessage="" />
              ),
            },
          ]}
          width="sm"
          name="password"
        />
        <ProFormSelect
          options={[
            {
              value: 0,
              label: '离职',
            },
            {
              value: 1,
              label: '在职',
            },
          ]}
          width="sm"
          name="hospitalStatus"
          label="在职状态"
        />
      </ModalForm>

    
      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          // console.log({value});
          const success = await editUser(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 UserMana;
