/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-08-19 15:57:26
 * @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,Form} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProForm,{ ModalForm, ProFormText, ProFormSelect,ProFormDatePicker} from '@ant-design/pro-form';
import DrawerContent from './components/DrawerContent';
import CAUpload from '@/components/CAUpload/index';
import { getIncomeCostDataImport,addIncomeCostDataImport,cancelIncomeCostDataImport,getIncomeCostDataImportErrList } from './service';

import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';


const IncomeCostDataImport = () => {
  const [currentTime, setCurrentTime] = useState(moment().format('YYYY-MM'));
  const columns = [

    {
      title: '所属年份',
      key: 'dateTime',
      hideInTable: true,
      dataIndex: 'dateTime',
      renderFormItem: (item, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {

        if (type === 'form') {
          return null;
        }
        return (
          <Form.Item  name='dateTime'>
            <ProFormDatePicker  fieldProps={{ picker: 'month', format: (value) => { return value.format('YYYY-MM') }, locale: locale,onChange:(moment)=>{setCurrentTime(moment.format('YYYY-MM'))} }} name="dateTime" />
          </Form.Item>
        )
      },
    },

    {
      title: '文件编号',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
    },
    {
      title: '导入类型',
      dataIndex: 'fileType',
      key: 'fileType',
      hideInSearch: true,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      key: 'fileName',
    },
    {
      title: '所属年月',
      dataIndex: 'dateTime',
      key: 'dateTime',
      hideInSearch: true,
      render:(_,record)=>{
          return `${record.dateYear}-${record.dateMonth}`
      }
    },
    {
      title: '导入时间',
      dataIndex: 'dateTime',
      key: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '总数',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      hideInSearch: true,
    },
    {
      title: '导入数',
      dataIndex: 'successAmount',
      key: 'successAmount',
      hideInSearch: true,
    },
    {
      title: '导入人员',
      dataIndex: 'userName',
      key: 'userName',
      hideInSearch: true,
    },
    {
      title: '下载',
      dataIndex: 'fileUrl',
      key: 'fileUrl',
      hideInSearch: true,
      render: url =>{
          const userData = localStorage.getItem('userData');
          const {token} = JSON.parse(userData);
           return <a href={`${url}?token=${token}`} target="_blank">下载</a>
      } 
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) =>{
          const {errStatus,rollbackStatus} = record;
          return [
            <Button
              key="config"
              disabled={rollbackStatus==1?true:false}
              danger={errStatus==1?true:false}
              onClick={() => {
                optionBtnGrouphandle(errStatus,record)
              }}
            >
              {errStatus==1?'错误详情':'撤销导入'}
            </Button>
          ]
      }
    },
  ];


  const drawerTableColumns = [
     {
      title: '行数',
      dataIndex: 'total',
      key: 'total',
      width:'10%',
      hideInSearch: true,
     },
     {
      title: '错误信息',
      dataIndex: 'errMessage',
      key: 'errMessage',
      hideInSearch: true,
     }
  ]



  const [createModalVisible, handleModalVisible] = useState(false);
  const actionRef = useRef();
  const ref = useRef();   //新增表单
  const importFormRef = useRef();   //导入表单
  const [currentRow, setCurrentRow] = useState(null);
  const [drawerVisible,setDrawerVisible] = useState(false);
  const [formData,setFormData] = useState(null);


  
  /**
   * 
   * @param {Number} errStatus  
   */
  const optionBtnGrouphandle = async (errStatus,record)=>{
        console.log({errStatus,record});
        setCurrentRow(record);
        if(errStatus != 1){
             const {id} = record;
             const resp = await cancelIncomeCostDataImport({id});
             const {status} = resp;
             if(status==200){
              if (actionRef.current) {
                actionRef.current.reload();
              }
             }
        }else{
          setDrawerVisible(true);
        }
  }
 



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



  //自定义上传回调
  const customRequestCallback = (file)=>{
    // console.log({file});
    const formData = new FormData();
    formData.set('file',file);
    setFormData(formData);
    if(importFormRef.current){
      importFormRef.current.setFieldsValue({
          'formData':formData
      });
      importFormRef?.current?.submit();
    }
    

  }

  const ModalContent = ()=>{

    return (
      <ProForm
        formRef={importFormRef}
        layout={{
          labelCol: { span: 4 },
          wrapperCol: { span: 14 },
        }}
        onFinish={async (values)=>{
              const formData = importFormRef.current.getFieldValue('formData');
              const {fileType,dateTime} = values;
              formData.set('fileType',fileType);
              formData.set('dateTime',dateTime);
         
              const resp = await addIncomeCostDataImport({formData},{
                'content-type':'multipart/form-data',
              })
              const {status} = resp;
  
              if(status==200){
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
        }}
        submitter={{
          render:false
        }}
      >
        <ProFormDatePicker
          rules={[
            {
              required: true,
              message:'请选择数据年月',
            },
          ]}
          width="sm"
          name="dateTime"
          fieldProps={{
            format: 'YYYY-MM',
            picker:'month',
            locale:locale
          }}
          label="数据所属年月"
        />
        <ProFormSelect
            rules={[
              {
                required: true,
                message:'请选择数据类型',
              },
            ]}
            options={[
              {
                value: 1,
                label: '成本分摊参数值',
              },
              {
                value: 2,
                label: '收入数据',
              },
              {
                value: 3,
                label: '成本数据',
              },
            ]}
            width="sm"
            name="fileType"
            label="选择数据类型"
          />
      </ProForm>
    )
  }
  

  const getDrawerTableList = async ()=>{
        // console.log({currentRow});
        const {id} = currentRow;
        const resp = await getIncomeCostDataImportErrList({id});
        const {status,data} = resp;
        if(status==200){
          return {
            data: data,
            success:true,
          };  
        }
  }

  

  // useEffect(()=>{
  //   CARequest('/api/costAccount/hosptail/list');
  // },[]);

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <CAUpload
            key='CAUpload'
            templateHrefs={[
                {
                  label:'成本分摊参数模板',
                  value:'/costAccount/excel/getShareParamTemplate'
                },
                {
                  label:'收入数据模板',
                  value:'/costAccount/excel/getImportIncomeProductAccountTemplate'
                },
                {
                  label:'成本数据模板',
                  value:'/costAccount/excel/getImportCostProductAccountTemplate'
                }
            ]}
            url='/costAccount/excel/importDataByFileType'
            importSuccessCallback={() => { }}
            type='dialog'
            content={<ModalContent />}
          // token={'123'}
            customRequestCallback={customRequestCallback}
          />
        ]}

        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 { name, isHospital, id, sign } = value;
          const success = await addDistrict(isHospital == 0 ? {
            name, isHospital, sign
          } : {
            name, isHospital, parentId: id
          });
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择收支类型',
            },
          ]}
          options={[
            {
              value: 1,
              label: '收入',
            },
            {
              value: 2,
              label: '支出',
            },
          ]}
          width="sm"
          name="paymentsType"
          label="选择收支类型"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '请填写收支名称',
            },
          ]}
          width="sm"
          name="paymentsName"
          label="收支名称"
        />
      </ModalForm>


      <DrawerContent
          columns={drawerTableColumns}
          visible={drawerVisible}
          title="错误详情"
          currentRow={currentRow}
          onVisibleChange={(bool) =>{setDrawerVisible(bool);} }
          renderListFunc={getDrawerTableList}
          onFinishFunc={async (value, selectedRowKeys, selectedRows) => {
                
          }}
      />
    </PageContainer>
  );
};

export default IncomeCostDataImport;
