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

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

import {
  addData,
  copyParamsList,
  delData,
  editData,
  getProfitReportType,
  getProjectCostShareTableData,
  getResponsibilityCenterSelecterList,
  saveParamsList,
} from './service';

import './style.less';

import { getChilds } from '@/utils/tooljs';
import EditTableModal from './editTableModal';
import TableSelecter from './tableSelector';
import { getDicDataBySysId } from '@/services/getDic';
import { getReportProjectSettingList } from '@/pages/baseSetting/otherItemSet/reportItemSet/service';
import { KcimCenterSysId } from '@/constant';

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

export default function AllocationParamsMap() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >(undefined);
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<any | undefined>(undefined);

  const [editTableVisible, set_editTableVisible] = useState(false);
  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);

  const columns: ProColumns[] = [
    {
      title: '项目分类',
      ellipsis: true,
      width: 100,
      dataIndex: 'itemTypeName',
    },
    {
      title: '成本列代码',
      ellipsis: true,
      width: 100,
      dataIndex: 'columnCode',
    },
    {
      title: '成本列名称',
      ellipsis: true,
      width: 150,
      dataIndex: 'columnName',
    },
    {
      title: '成本列类型',
      ellipsis: true,
      width: 100,
      dataIndex: 'columnTypeName',
    },
    {
      title: '损益表类型',
      ellipsis: true,
      dataIndex: 'reportTypeName',
    },
    {
      title: '损益表项目',
      ellipsis: true,
      dataIndex: 'profitPathName',
    },
    {
      title: '分摊参数',
      ellipsis: true,
      width: 200,
      dataIndex: 'shareParamCostDetails',
      renderText(arr, record) {
        if (arr) {
          return arr.reduce(
            (prev: string, cur: any) =>
              `${prev.length > 0 ? prev + '|' : prev}${cur.shareParamName}`,
            '',
          );
        }
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 160,
      fixed: 'right',
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <a
            key="share"
            onClick={() => {
              set_editTableVisible(true);
              setCurrentRow(record);
            }}
          >
            分摊参数
          </a>,
          <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 getProjectCostShareTableData({ ...params });
    if (resp) {
      return {
        data: resp,
        success: true,
      };
    }
    return [];
  };

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

  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') => {
    try {
      const result = {
        columnCode: formVal.columnCode,
        columnName: formVal.columnName,
        columnType: formVal.columnType,
        columnTypeName: formVal.columnTypeName,
        profitId: formVal.profitId[formVal.profitId.length - 1],
        profitNum: formVal.profitNum,
        profitName: formVal.profitName,
        profitPath: formVal.profitPath,
        profitPathName: formVal.profitPathName,
        itemType: formVal.itemType,
        reportType: formVal.reportType,
      };

      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('操作成功！');
        }
      }
    } catch (error) {
      console.log({ error });
    }

    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}项目分摊参数对应`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                profitId: record.profitPath
                  ? record.profitPath.split(',').map((a: string) => Number(a))
                  : [],
              }
            : {}
        }
        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="columnTypeName" hidden />
        <ProFormText name="profitNum" hidden />
        <ProFormText name="profitName" hidden />
        <ProFormText name="profitPath" hidden />
        <ProFormText name="profitPathName" hidden />
        <ProFormSelect
          name="itemType"
          label="项目分类："
          placeholder="请输入"
          request={async () => {
            const resp = await getDicDataBySysId(
              KcimCenterSysId,
              'MED_SERVICE_ITEM_TYPE',
            );
            if (resp) {
              const { dataVoList = [] } = resp;
              return dataVoList.map((a: any) => ({
                label: a.name,
                value: a.code,
              }));
            }
            return [];
          }}
          rules={[{ required: true, message: '项目分类不能为空!' }]}
        />
        <ProFormText
          name="columnCode"
          label="成本列代码："
          placeholder="请输入"
          rules={[{ required: true, message: '成本列代码不能为空!' }]}
        />
        <ProFormText
          name="columnName"
          label="成本列名称："
          placeholder="请输入"
          rules={[{ required: true, message: '成本列名称不能为空!' }]}
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择',
            },
          ]}
          request={async () => {
            const currentSys = localStorage.getItem('currentSelectedTab');
            const { systemId } = JSON.parse(currentSys as string);
            const resp = await getDicDataBySysId(
              systemId,
              'ITEM_COST_COLUNM_TYPE',
            );
            if (resp) {
              const { dataVoList = [] } = resp;
              return dataVoList.map((a: any) => ({
                label: a.name,
                value: a.code,
              }));
            }
            return [];
          }}
          fieldProps={{
            onChange(value, option: any) {
              const { label = '' } = option;
              formRef.current?.setFieldValue('columnTypeName', label);
            },
          }}
          name="columnType"
          label="成本列类型："
        />
        <ProFormSelect
          name="reportType"
          label="损益表类型："
          placeholder="请输入"
          request={async () => {
            const { systemId } = JSON.parse(
              localStorage.getItem('currentSelectedTab') as string,
            );
            const resp = await getDicDataBySysId(
              systemId,
              'PROFIT_REPORT_TYPE',
            );
            if (resp) {
              const { dataVoList = [] } = resp;
              return dataVoList.map((a: any) => ({
                label: a.name,
                value: a.code,
              }));
            }
            return [];
          }}
          rules={[{ required: true, message: '损益表类型不能为空!' }]}
        />
        <ProFormDependency name={['reportType']}>
          {({ reportType }) => {
            return reportType ? (
              <ProFormCascader
                rules={[
                  {
                    required: true,
                    message: '请选择',
                  },
                ]}
                params={{ reportType }}
                request={async (params) => {
                  console.log({ params });
                  const { reportType } = params;
                  const resp = await getReportProjectSettingList({
                    reportType,
                  });
                  if (resp) {
                    return resp.list;
                  }
                  return [];
                }}
                fieldProps={{
                  fieldNames: {
                    label: 'reportName',
                    value: 'id',
                  },
                  onChange: (value: any, selectedOptions: any) => {
                    //  console.log({value,selectedOptions});
                    const { num = 0, reportName = '' } =
                      selectedOptions[selectedOptions.length - 1];
                    formRef.current?.setFieldValue('profitNum', num);
                    formRef.current?.setFieldValue('profitName', reportName);
                    formRef.current?.setFieldValue(
                      'profitPath',
                      value.join(','),
                    );
                    formRef.current?.setFieldValue(
                      'profitPathName',
                      selectedOptions.map((a: any) => a.reportName).join('/'),
                    );
                  },
                }}
                name="profitId"
                label="损益表项目："
              />
            ) : (
              <></>
            );
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

  const shareParamsSetCommit = async (rows: any[]) => {
    // console.log({currentRow,rows});
    const result = rows.map((a) => ({
      shareParamColumnCode: currentRow.columnCode,
      shareParamCode: a.shareParamCode,
      shareParamName: a.shareParamName,
      percent: a.percent,
    }));
    const resp = await saveParamsList(result);
    if (resp) {
      set_editTableVisible(false);
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  const tableSelecterCommit = async (keys: Key[], rows: any) => {
    const { id } = currentRow;
    const resp = await copyParamsList({ id, responsibilityIds: keys });
    if (resp) {
      set_tableSelecterVisible(false);
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  return (
    <KCIMPagecontainer className="AllocationParamsMap" title={false}>
      <EditTableModal
        onVisibleChange={(bool) => {
          set_editTableVisible(bool);
          if (!bool) setCurrentRow(undefined);
        }}
        title="分摊参数设置"
        rowKey={'id'}
        record={currentRow}
        open={editTableVisible}
        onFinish={(rows) => shareParamsSetCommit(rows)}
      />
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="选择复制目标"
        rowKey={'id'}
        defaultSelectedKeys={[]}
        record={currentRow}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />
      <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>
        <KCIMTable
          scroll={{ y: `calc(100vh - 233px)` }}
          columns={columns as ProColumns[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
