/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-25 15:00:46
 * @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 KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { formatMoneyNumber } from '@/utils/format';
import { createFromIconfontCN } from '@ant-design/icons';
import FormItem from 'antd/es/form/FormItem';

import {
  ActionType,
  ProFormDatePicker,
  ProFormDateTimePicker,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDependency,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormSwitch,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { message, Popconfirm, Form } from 'antd';
import { Fragment, useEffect, useRef, useState } from 'react';

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

import { addData, delData, editData, getWholeHospCostList } from './service';

import './style.less';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq } from '@/utils/tooljs';
import moment from 'moment';
import { getWholeHospCostList as getWholeHospCostSetList } from '@/pages/baseSetting/otherItemSet/wholeHospCostAndIncomeSet/service';

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

export default function WholeHospIncomeAndCost({
  date,
  btnPerm,
  cancelHandle,
  getHandle,
}: {
  date: string;
  btnPerm: string;
  cancelHandle: () => Promise<boolean>;
  getHandle: () => Promise<boolean>;
}) {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const [ifShowGetBtn, set_ifShowGetBtn] = useState(false);
  const [ifShowCancelBtn, set_ifShowCancelBtn] = useState(false);
  const [currentType, set_currentType] = useState(0);
  const [cardData, set_cardData] = useState<any[]>([]);
  const [showCardData, set_showCardData] = useState<any[]>([]);

  const columns: ProColumns[] = [
    {
      title: '收支类型',
      dataIndex: 'paymentsType',
      renderText(num) {
        return <>{num == 1 ? '收入' : '支出'}</>;
      },
    },
    {
      title: '收支名称',
      dataIndex: 'paymentsName',
    },
    {
      title: '金额',
      dataIndex: 'totalAmount',
      renderText(num) {
        return formatMoneyNumber(num);
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 90,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getWholeHospCostList({
      ...params,
      pageSize: 500,
      current: 1,
    });
    if (resp) {
      set_cardData([...resp.list]);
      set_showCardData([...resp.list]);
    }
  };

  const delTableData = async (record: any) => {
    const resp = await delData([record.id]);
    if (resp) {
      message.success('操作成功！');
      getTableData({ ...tableDataFilterParams });
      // message.success('操作成功!');
    }
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    const result = {
      dateTime: date,
      paymentsName: formVal.paymentData.label,
      paymentsType: formVal.paymentData.value,
      totalAmount: formVal.totalAmount,
    };

    if (type == 'ADD') {
      const resp = await addData(result);
      if (resp) {
        getTableData({ ...tableDataFilterParams });
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      const resp = await editData({ ...result, id: formVal.id });
      if (resp) {
        getTableData({ ...tableDataFilterParams });
        message.success('操作成功！');
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                dateTime: `${record.dateYear}-${
                  record.dateMonth > 9
                    ? record.dateMonth
                    : '0' + record.dateMonth
                }`,
                paymentData: {
                  label: record.paymentsName,
                  value: record.paymentsType,
                },
              }
            : { status: 0, dateTime: date }
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <div className="list">
              <IconFont type="iconzhankai" style={{ color: '#17181A' }} />
              <span>新增收支</span>
            </div>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        {/* <ProFormDatePicker
                    rules={[
                        {
                            required: true,
                            message: '年月是必填项！',
                        },
                    ]}
                    fieldProps={{
                        picker: 'month',
                        format: (value) => {
                            return value.format('YYYY-MM');
                        },
                        locale: locale,
                    }}
                    disabled
                    width={318}
                    label="选择年月"
                    name="dateTime"
                /> */}
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择收支名称',
            },
          ]}
          fieldProps={{
            labelInValue: true,
          }}
          request={async () => {
            const resp = await getWholeHospCostSetList({
              pageSize: 200,
              current: 1,
            });
            if (resp) {
              return resp.list.map((item: any) => ({
                label: item.paymentsName,
                value: item.paymentsType,
              }));
            }
          }}
          name="paymentData"
          label="选择收支名称"
        />
        <ProFormDigit
          rules={[
            {
              required: true,
              message: '金额是必填项',
            },
          ]}
          min={0}
          name="totalAmount"
          label="金额"
        />
      </ModalForm>
    );
  };

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

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

  useEffect(() => {
    if (currentType == 0) {
      set_showCardData([...cardData]);
    }
    if (currentType == 1) {
      set_showCardData([...cardData.filter((a) => a.paymentsType == 1)]);
    }
    if (currentType == 2) {
      set_showCardData([...cardData.filter((a) => a.paymentsType == 2)]);
    }
  }, [cardData]);

  useEffect(() => {
    if (tableDataFilterParams) {
      getTableData({ ...tableDataFilterParams });
    }
  }, [tableDataFilterParams]);

  useEffect(() => {
    if (currentType == 0) {
      set_showCardData([...cardData]);
    }
    if (currentType == 1) {
      set_showCardData([...cardData.filter((a) => a.paymentsType == 1)]);
    }
    if (currentType == 2) {
      set_showCardData([...cardData.filter((a) => a.paymentsType == 2)]);
    }
  }, [currentType]);

  return (
    <KCIMPagecontainer className="WholeHospIncomeAndCost" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div
            className={currentType == 0 ? 'tab on' : 'tab'}
            onClick={() => set_currentType(0)}
          >
            全部
          </div>
          <div
            className={currentType == 1 ? 'tab on' : 'tab'}
            onClick={() => set_currentType(1)}
          >
            收入
          </div>
          <div
            className={currentType == 2 ? 'tab on' : 'tab'}
            onClick={() => set_currentType(2)}
          >
            支出
          </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>
          )}
          {/* <UpDataActBtn record type='ADD' /> */}
        </div>
      </div>

      <div className="content" style={{ marginTop: 16 }}>
        <UpDataActBtn key={'act'} record={undefined} type="ADD" />
        {showCardData.map((item, index) => (
          <div className="list" key={index}>
            <div className="rowOne">
              <span
                className={item.paymentsType == 1 ? 'tag income' : 'tag cost'}
              >
                {item.paymentsType == 1 ? '收入' : '支出'}
              </span>
              <span className="date">{date}</span>
            </div>
            <div className="rowTwo">{formatMoneyNumber(item.totalAmount)}</div>
            <div className="rowThree">
              <span className="name">{item.paymentsName}</span>
              <span className="btns">
                <UpDataActBtn key={'act'} record={item} type="EDIT" />
                <Popconfirm
                  title="是否确认删除？"
                  key="del"
                  onConfirm={() => delTableData(item)}
                >
                  <a style={{ fontSize: 14, marginLeft: 12 }}>删除</a>
                </Popconfirm>
              </span>
            </div>
          </div>
        ))}
      </div>
    </KCIMPagecontainer>
  );
}
