/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-10-16 13:30:45
 * @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 { 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: '总工时',
      align: 'center',
      dataIndex: 'hour',
    },
    {
      title: '固定薪资(元)',
      dataIndex: 'salary',
      align: 'center',
      renderText(number, record, index, action) {
        return (
          <div style={{ textAlign: 'right', paddingRight: '30%' }}>
            {formatMoneyNumber(number)}
          </div>
        );
      },
    },
    {
      title: '变动薪资(元)',
      align: 'center',
      dataIndex: 'variableCompensation',
      renderText(number, record, index, action) {
        return (
          <div style={{ textAlign: 'right', paddingRight: '30%' }}>
            {formatMoneyNumber(number)}
          </div>
        );
      },
    },
    {
      title: '总成本(元)',
      dataIndex: 'cost',
      align: 'center',
      renderText(number, record, index, action) {
        return (
          <div style={{ color: '#FF8C19' }}>{formatMoneyNumber(number)}</div>
        );
      },
    },
  ];

  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" style={{ width: 205 }}>
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              检索：
            </span>
            <Input
              placeholder={'输入工号,姓名'}
              allowClear
              autoComplete="off"
              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>
  );
}
