/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:54:49
 * @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,
  ProFormDigit,
} from '@ant-design/pro-components';
import { ModalForm } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Form, Select } 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,
  delData,
  editData,
  getApportionmentLevelList,
} from './service';

import './style.less';

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

export default function AllocationLevelSet() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >({ accountType: 1 });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<any | undefined>(undefined);
  const [selectableLevelList, setSelectableLevelList] = useState<any[]>([]); //可选的分摊层级列表

  const columns: ProColumns[] = [
    {
      title: '分摊层级名',
      dataIndex: 'shareName',
    },
    {
      title: '分摊层级序号',
      dataIndex: 'leverSort',
    },
    {
      title: '目标层级',
      dataIndex: 'targetLevel',
    },
    {
      title: '计算方式',
      dataIndex: 'calcType',
      renderText(text, record) {
        return <>{text == 0 ? '合并计算' : '分开计算'}</>;
      },
    },
    {
      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 getApportionmentLevelList({ ...params });
    if (resp) {
      const tempArr =
        resp.list &&
        resp.list.map((item: any) => ({
          label: item.shareName,
          value: item.leverSort,
        }));
      setSelectableLevelList(tempArr);
      return {
        data: resp.list,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    }
    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') => {
    console.log({ formVal });

    if (type == 'ADD') {
      const { targetLevel } = formVal;
      const result = {
        ...formVal,
        targetLevel: targetLevel.map((a: any) => a.value).join(','),
      };

      const resp = await addData(result);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        const { targetLevel } = formVal;
        const resp = await editData({
          ...formVal,
          targetLevel: targetLevel
            .map((a: any) => (a.value ? a.value : a))
            .join(','),
        });
        if (resp) {
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      } catch (error) {
        console.log({ error });
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    setCurrentRow(record);
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}分摊层级`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                targetLevel: record.targetLevel
                  ? record.targetLevel.split(',').map((a: string) => Number(a))
                  : [],
              }
            : { targetLevel: [] }
        }
        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
      >
        <ProFormDigit
          label="分摊层级序号"
          rules={[
            {
              required: true,
              message: '分摊层级序号是必填项',
            },
          ]}
          name="leverSort"
          min={1}
          max={100}
        />

        <ProFormText
          label="分摊层级名"
          rules={[
            {
              required: true,
              message: '分摊层级名是必填项',
            },
          ]}
          name="shareName"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择计算方式',
            },
          ]}
          options={[
            {
              value: 0,
              label: '合并计算',
            },
            {
              value: 1,
              label: '分开计算',
            },
          ]}
          name="calcType"
          label="计算方式"
        />
        <ProFormDependency name={['leverSort']}>
          {({ leverSort }) => {
            try {
              const filteredArr = selectableLevelList.filter(
                (item) => item.value >= leverSort,
              );
              if (filteredArr.length == 0) {
                //当大于最大可选分摊层级
                //formRef?.current?.setFieldsValue({ targetLevel: [{ value: `${leverSort}` }] });
                formRef?.current?.setFieldValue('targetLevel', [
                  { value: `${leverSort}` },
                ]);
                return <ProFormText name="targetLevel" hidden />;
              } else {
                if (type == 'ADD') {
                  formRef?.current?.setFieldValue('targetLevel', []);
                }
                if (type == 'EDIT') {
                  formRef?.current?.setFieldValue(
                    'targetLevel',
                    record.targetLevel
                      ? record.targetLevel
                          .split(',')
                          .map((a: string) => Number(a))
                      : [],
                  );
                }
              }
              return (
                filteredArr.length > 0 && (
                  <Form.Item
                    name="targetLevel"
                    label="目标层级"
                    shouldUpdate
                    style={{ width: 320 }}
                    required
                  >
                    <Select
                      mode="multiple"
                      labelInValue={true}
                      placeholder="请选择"
                      maxTagCount={2}
                    >
                      {filteredArr.map((item, index) => (
                        <Select.Option key={index} value={item.value}>
                          {`${item.label}层级${item.value}`}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                )
              );
            } catch (error) {
              console.log({ error });
            }
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

  return (
    <KCIMPagecontainer className="AllocationLevelSet" 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('name')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    name: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  name: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
        </div>
        <div className="btnGroup">
          <UpDataActBtn record type="ADD" />
        </div>
      </div>

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