/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-06-11 11:26:11
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { createFromIconfontCN } from '@ant-design/icons';

import { ModalForm } from '@ant-design/pro-form';
import FormItem from 'antd/es/form/FormItem';
import { DatePicker, Input } from 'antd';
import { useEffect, useRef, useState } from 'react';

import { getData, downloadTemplateReq, importEmpCostDataPost } from './service';

import './style.less';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import KCIMUpload from '@/components/KCIMUpload';
import { TableDataResponse } from 'typings';
import { ActionType, ProColumns } from '@ant-design/pro-components';
import { formatMoneyNumber } from '@/utils/format';


const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

const currentData = `${new Date().getFullYear()}-${(new Date().getMonth() + 1).toString().padStart(2, '0')}`

export default function EmpCostDataImport(
  { date, btnPerm, cancelHandle, getHandle }:
    {
      date: string, btnPerm: string, cancelHandle: () => Promise<boolean>,
      getHandle: () => Promise<boolean>,
    }) {
  const [computeDate, set_computeDate] = useState(currentData);
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<any>({ computeDate: currentData });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
  const tableRef = useRef<ActionType>();

  const [ifShowGetBtn, set_ifShowGetBtn] = useState(false);
  const [ifShowCancelBtn, set_ifShowCancelBtn] = useState(false);

  const columns: ProColumns[] = [
    {
      title: '工号',
      dataIndex: 'empCode',
    },
    {
      title: '姓名',
      dataIndex: 'empName',
    },
    {
      title: '总工时',
      dataIndex: 'hour',
    },
    {
      title: '固定薪资(元)',
      dataIndex: 'salary',
      renderText(number, record, index, action) {
        return formatMoneyNumber(number)
      },
    },
    {
      title: '变动薪资(元)',
      dataIndex: 'variableCompensation',
      renderText(number, record, index, action) {
        return formatMoneyNumber(number)
      },
    },
    {
      title: '总成本(元)',
      dataIndex: 'cost',
      renderText(number, record, index, action) {
        return <span style={{color:'#FF8C19'}}>{formatMoneyNumber(number)}</span>
      },

    },
  ];

  const getTableData = async (params: any): Promise<TableDataResponse | any[]> => {
    const resp = await getData({ ...params, ...tableDataFilterParams });
    if (resp) {
      const { list, totalCount, pageSize, current, totalPage } = resp;
      if (totalCount == 0 && current != 1) {
        return getTableData({ ...params, current: current - 1 });
      } else {
        return {
          data: list,
          success: true,
          total: totalCount,
          pageSize: pageSize,
          totalPage: totalPage,
        };
      }
    }
    return [];
  };

  const tableDataSearchHandle = (paramName: string) => {


    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords
    })
  }

  const downloadTemplate = async () => {
    await downloadTemplateReq();
  };

  const importData = () => {
    return (
      <ModalForm
        width={360}
        title={`导入数据`}
        trigger={
          <a className="import" key="3">
            导入
          </a>
        }
        submitter={{
          render: (props, defaultDoms) => {
            const needBtn = defaultDoms.filter((b) => {
              return b.key != 'rest';
            });
            return [
              // <Button
              //     key="ok"
              //     onClick={auditType == '0' ? () => downloadTemplate(index) : () => { }}
              // >
              //     下载模板
              // </Button>,
              ...needBtn,
            ];
          },
        }}
        onFinish={async (values) => {
          const {
            importFile: { fileList },
          } = values;

          let formData = new FormData();
          formData.append('file', fileList[0].originFileObj);
          formData.append('computeDate', computeDate);

          const resp = await importEmpCostDataPost(formData);

          if (resp) {
            tableRef.current?.reload();
            return true;
          }
        }}
      >
        <FormItem name={'importFile'}>
          <KCIMUpload downloadTemplateFile={() => downloadTemplate()} />
        </FormItem>
      </ModalForm>
    );
  };

  useEffect(() => {
    if (date) {
      set_computeDate(date);
      set_tableDataFilterParams({
        ...tableDataFilterParams,
        computeDate: date,
      });
    }
  }, [date]);

  useEffect(() => {
    if (btnPerm) {
      const [a, b] = btnPerm.split('|');
      set_ifShowCancelBtn(b == '1');
      set_ifShowGetBtn(a == '1')
    }
  }, [btnPerm])

  return (
    <KCIMPagecontainer className="empCostDataImport" title={false}>
      <div className="toolBar">
        <div className="filter">
          {/* <div className="filterItem">
            {
              <div className="search">
                <span>核算年月：</span>
                <DatePicker
                  onChange={(data, dateString) => {
                    set_computeDate(dateString);
                    set_tableDataFilterParams({
                      ...tableDataFilterParams,
                      computeDate: dateString,
                    });
                  }}
                  picker="month"
                  locale={locale}
                  defaultValue={moment(`${new Date().getFullYear()}-${(new Date().getMonth()+1).toString().padStart(2, '0')}`, 'YYYY-MM')}
                  format="YYYY-MM"
                  placeholder="选择年月"
                />
              </div>
            }
          </div> */}
          <div className='filterItem' style={{ width: 205 }}>
            <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
            <Input placeholder={'输入工号,姓名'} allowClear
              suffix={
                <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle('filter')} />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    filter: ''
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  filter: ((e.target) as HTMLInputElement).value
                });
              }}

            />
          </div>
        </div>
        <div className="btnGroup">
          {ifShowCancelBtn && <span onClick={() => cancelHandle().then((isok) => {
            if (isok) tableRef.current?.reload();
          })}>撤销</span>}
          {ifShowGetBtn && <span onClick={() => getHandle().then((isok) => {
            if (isok) tableRef.current?.reload();
          })}>获取</span>}
          {/* {importData()} */}
        </div>
      </div>
      <div style={{ marginTop: 16 }}>
        <KCIMTable
          columns={columns}
          actionRef={tableRef}
          rowKey="id"
          scroll={{y:`calc(100vh - 345px)`}}
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
