/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:42:35
 * @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,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormCascader,
  ProFormDependency,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Modal } from 'antd';
import { useEffect, useRef, useState } from 'react';

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

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

import './style.less';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq } from '@/utils/tooljs';
import { getStandItemList } from '../standardProjectMana/service';
import { getDicDataBySysId } from '@/services/getDic';
import { CostAccountingSysId, KcimCenterSysId } from '@/constant';

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

export default function ProjectShareParamsSet() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [stopStat, set_stopStat] = useState(0);
  const columns: ProColumns[] = [
    {
      title: '分摊参数代码',
      dataIndex: 'shareParamCode',
    },
    {
      title: '分摊参数名称',
      dataIndex: 'shareParamName',
    },
    {
      title: '来源类型',
      dataIndex: 'sourceTypeName',
    },
    {
      title: '来源项目',
      dataIndex: 'sourceName',
    },
    {
      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 getProjectShareParamsSetTableData({ ...params });
    if (resp) {
      return {
        data: resp,
        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 updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    const result = {
      shareParamCode: formVal.shareParamCode,
      shareParamName: formVal.shareParamName,
      sourceType: formVal.sourceType,
      sourceCode: formVal.sourceCode,
      sourceName: formVal.sourceName,
    };

    if (type == 'ADD') {
      const resp = await addData(result);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      const resp = await editData({ ...result, id: formVal.id });
      if (resp) {
        tableRef.current?.reload();
        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,
                source: record.sourceCode ? record.sourceCode.split('|') : [],
              }
            : {}
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText
          name="shareParamCode"
          label="分摊参数代码："
          placeholder="请输入"
          rules={[{ required: true, message: '分摊参数代码不能为空!' }]}
        />
        <ProFormText
          name="shareParamName"
          label="分摊参数名称："
          placeholder="请输入"
          rules={[{ required: true, message: '分摊参数名称不能为空!' }]}
        />
        <ProFormSelect
          name="sourceType"
          label="来源类型："
          placeholder="请输入"
          request={async () => {
            const resp = await getDicDataBySysId(
              CostAccountingSysId,
              'ITEM_ALLOCATE_PARAM_SOURCE_TYPE',
            );
            if (resp) {
              const { dataVoList = [] } = resp;
              return dataVoList.map((a: any) => ({
                label: a.name,
                value: a.code,
              }));
            }
            return [];
          }}
          rules={[{ required: true, message: '来源类型不能为空!' }]}
        />
        <ProFormText name={'sourceCode'} hidden />
        <ProFormText name={'sourceName'} hidden />
        <ProFormDependency name={['sourceType']}>
          {({ sourceType }) => {
            return sourceType ? (
              <ProFormSelect
                allowClear
                label="来源项目："
                name="source"
                params={{ sourceType }}
                placeholder="请选择"
                rules={[{ required: true, message: '来源项目不能为空!' }]}
                request={async ({ sourceType }) => {
                  const resp = await getSourceItems(sourceType);
                  if (resp) {
                    const arr = resp.sort((a: any, b: any) => {
                      // Convert code values to integers
                      const codeA = parseInt(a.code);
                      const codeB = parseInt(b.code);
                      if (codeA === 0) return -1;
                      if (codeB === 0) return 1;

                      return codeA - codeB;
                    });

                    return arr.map((a: any) => ({
                      label: a.name,
                      value: a.code,
                    }));
                  }
                  return [];
                }}
                fieldProps={{
                  mode: 'multiple',
                  maxTagCount: 4,
                  maxTagPlaceholder: '...',
                  // labelInValue:true,
                  onChange(value: any, option: any) {
                    if (value.findIndex((a: any) => a == '0') != -1) {
                      formRef.current?.setFieldValue('sourceCode', '0');
                      formRef.current?.setFieldValue('sourceName', '全部');
                      formRef.current?.setFieldValue('source', ['0']);
                    } else {
                      formRef.current?.setFieldValue(
                        'sourceCode',
                        option.map((a: any) => a.value).join('|'),
                      );
                      formRef.current?.setFieldValue(
                        'sourceName',
                        option.map((a: any) => a.label).join('|'),
                      );
                    }
                  },
                }}
              />
            ) : null;
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

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

  useEffect(() => {}, []);

  return (
    <KCIMPagecontainer className="ProjectShareParamsSet" 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('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">
          <UpDataActBtn record type="ADD" />
        </div>
      </div>

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