/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-10-16 11:26:19
 * @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 { createFromIconfontCN } from '@ant-design/icons';

import {
  ActionType,
  ProFormInstance,
  ProFormText,
  ProFormSelect,
  ProFormCascader,
  ProFormDigit,
  ProFormDatePicker,
} from '@ant-design/pro-components';
import { ModalForm } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Dropdown } from 'antd';
import type { MenuProps } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

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

import {
  addData,
  calculateMonthCostShareData,
  copyMonthCostShareData,
  delData,
  editData,
  getMonthCostShareDataList,
} from './service';

import './style.less';
import moment from 'moment';
import { getCostshareparamList } from '../costAllocationParamsSet/service';
import { getResponsibilityCenterList } from '../../responsibilityCenterSet/responsibilityCenter/service';
import { renameChildListToChildren } from '@/utils/tooljs';
import { tableColumnsWidObj } from '@/constant';

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

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

export default function CostAllocationParamsDeal({
  date,
  ifShowGetBtn,
  ifShowCancelBtn,
  responsibilityCode,
  cancelHandle,
  getHandle,
}: {
  date: string;
  ifShowGetBtn: boolean;
  ifShowCancelBtn: boolean;
  responsibilityCode: string;
  cancelHandle: () => Promise<boolean>;
  getHandle: () => Promise<boolean>;
}) {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >({ computeDate: currentData });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [computeDate, set_computeDate] = useState(currentData);
  const [currentEditRow, set_currentEditRow] = useState<undefined | any>(
    undefined,
  );

  const columns: ProColumns[] = [
    {
      title: '分摊参数',
      dataIndex: 'shareParamName',
      renderText(text, record, index, action) {
        const { shareParamCode, shareParamName } = record;
        return `[${shareParamCode}]${shareParamName}`;
      },
    },
    {
      title: '数值',
      align: 'center',
      dataIndex: 'valueNum',
      renderText(num, record, index, action) {
        return (
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'flex-end',
              paddingRight: '30%',
            }}
          >
            {currentEditRow && currentEditRow.id == record.id && (
              <>
                <ProFormDigit
                  width={80}
                  noStyle
                  fieldProps={{
                    value: num,
                    onChange(value) {
                      set_currentEditRow({
                        ...record,
                        valueNum: value ? value : 0,
                      });
                    },
                  }}
                />
                <img
                  onClick={() =>
                    updateTable({ ...record, ...currentEditRow }, 'EDIT')
                  }
                  style={{
                    width: 16,
                    height: 16,
                    display: 'inline-block',
                    marginLeft: 8,
                    cursor: 'pointer',
                  }}
                  src={require('../../../../../static/confirmIcon.png')}
                />
              </>
            )}

            {(!currentEditRow ||
              (currentEditRow && currentEditRow.id != record.id)) && (
              <>
                <div>{num.toFixed(2)}</div>
                <img
                  onClick={() => set_currentEditRow(record)}
                  style={{
                    width: 16,
                    height: 16,
                    display: 'inline-block',
                    marginLeft: 8,
                    cursor: 'pointer',
                  }}
                  src={require('../../../../../static/editIcon.png')}
                />
              </>
            )}
          </div>
        );
      },
    },
    {
      title: '责任中心',
      dataIndex: 'responsibilityName',
      renderText(text, record, index, action) {
        const { responsibilityCode, responsibilityName } = record;
        return `[${responsibilityCode}]${responsibilityName}`;
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 90,
      fixed: 'right',
      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 items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <a
          onClick={() =>
            cancelHandle().then((isok) => {
              if (isok) tableRef.current?.reload();
            })
          }
          style={{ display: ifShowCancelBtn ? 'inline-block' : 'none' }}
        >
          撤销
        </a>
      ),
    },
    {
      key: '2',
      label: (
        <a
          onClick={() =>
            getHandle().then((isok) => {
              if (isok) {
                tableRef.current?.reload();
              }
            })
          }
          style={{ display: ifShowGetBtn ? 'inline-block' : 'none' }}
        >
          获取
        </a>
      ),
    },
  ];

  const getTableData = async (params: any) => {
    const { computeDate, responsibilityCode } = params;
    if (computeDate && responsibilityCode) {
      const resp = await getMonthCostShareDataList({ ...params });
      if (resp) {
        return {
          data: resp.list,
          success: true,
          total: resp.totalCount,
          pageSize: resp.pageSize,
          totalPage: resp.totalPage,
        };
      }
    }
    return [];
  };

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

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords,
    });
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD' | 'COPY') => {
    const result = {
      date: computeDate.replace('-', ''),
      shareParamCode: formVal.shareParamCode,
      valueNum: formVal.valueNum,
    };

    if (type == 'ADD') {
      const resp = await addData({
        ...result,
        responsibilityCode:
          formVal.responsibilityCode[formVal.responsibilityCode.length - 1],
      });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        const resp = await editData({
          ...result,
          id: formVal.id,
          responsibilityCode:
            typeof formVal.responsibilityCode == 'string'
              ? formVal.responsibilityCode
              : formVal.responsibilityCode[
                  formVal.responsibilityCode.length - 1
                ],
        });
        if (resp) {
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      } catch (error) {
        console.log({ error });
      }
    }

    if (type == 'COPY') {
      const { dataSourceType, toDate, date: fromDate } = formVal;
      const resp = await copyMonthCostShareData({
        dataSourceType,
        toDate: moment(toDate).format('yyyyMM'),
        fromDate: moment(fromDate).format('yyyyMM'),
      });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    return true;
  };

  const calculateHandle = async () => {
    const resp = await calculateMonthCostShareData({
      date: computeDate.replace('-', ''),
    });
    if (resp) {
      message.success('计算成功！');
      tableRef?.current?.reload();
    }
  };

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

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD' | 'COPY';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}成本分摊参数处理`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
              }
            : {}
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : type == 'COPY' ? (
            <span>复制</span>
          ) : (
            <span>新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        {type == 'COPY' && (
          <>
            <ProFormDatePicker
              name="date"
              width={318}
              rules={[
                {
                  required: true,
                  message: '复制时间是必填项！',
                },
              ]}
              label="复制数据年月"
              fieldProps={{
                picker: 'month',
                locale: locale,
                format: 'YYYY-MM',
                autoComplete: 'off',
              }}
            />
            <ProFormDatePicker
              name="toDate"
              width={318}
              label="目标年月"
              rules={[
                {
                  required: true,
                  message: '目标时间是必填项！',
                },
              ]}
              fieldProps={{
                picker: 'month',
                locale: locale,
                format: 'YYYY-MM',
                autoComplete: 'off',
              }}
            />
            <ProFormSelect
              options={[
                {
                  value: 1,
                  label: '手动输入',
                },
                {
                  value: 2,
                  label: '文件导入',
                },
                {
                  value: 3,
                  label: '全部',
                },
              ]}
              rules={[
                {
                  required: true,
                  message: '数据类型是必填项！',
                },
              ]}
              name="dataSourceType"
              label="数据类型"
            />
          </>
        )}
        {type != 'COPY' && (
          <>
            <ProFormSelect
              name="shareParamCode"
              label="选择分摊参数"
              request={async (params) => {
                const resp = await getCostshareparamList({
                  ...params,
                  pageSize: 500,
                });
                if (resp) {
                  return resp.list.map((item: any) => ({
                    label: item.shareParamName,
                    value: item.shareParamCode,
                  }));
                }
              }}
              placeholder="请选择"
              rules={[{ required: true, message: '分摊参数是必选项！' }]}
            />
            <ProFormCascader
              label="责任中心"
              name="responsibilityCode"
              allowClear
              placeholder="请选择"
              request={async () => {
                const resp = await getResponsibilityCenterList({
                  pageSize: 500,
                });
                if (resp) {
                  return resp.list;
                }
                return [];
              }}
              fieldProps={{
                fieldNames: {
                  label: 'responsibilityName',
                  value: 'responsibilityCode',
                  children: 'child',
                },
              }}
            />
            <ProFormDigit
              label="数值"
              name="valueNum"
              rules={[
                {
                  required: true,
                  message: '必选项！',
                },
              ]}
            />
          </>
        )}
      </ModalForm>
    );
  };

  return (
    <KCIMPagecontainer className="CostAllocationParamsDeal" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem">
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              检索：
            </span>
            <Input
              placeholder={'分摊参数代码/名称'}
              allowClear
              autoComplete="off"
              suffix={
                <IconFont
                  type="iconsousuo"
                  style={{ color: '#99A6BF' }}
                  onClick={() => tableDataSearchHandle('shareParamCode')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    shareParamCode: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  shareParamCode: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
        </div>
        <div className="btnGroup">
          <UpDataActBtn record type="COPY" />
          <span onClick={() => calculateHandle()}>计算</span>
          <UpDataActBtn record type="ADD" />
          {ifShowCancelBtn && ifShowGetBtn && (
            <Dropdown menu={{ items }} placement="bottomRight">
              <IconFont type="icongengduochuizhi" />
            </Dropdown>
          )}
        </div>
      </div>

      <div>
        <KCIMTable
          scroll={{ y: `calc(100vh - 343px)` }}
          columns={columns as ProColumns[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
