/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-08-23 10:22:59
 * @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,
  getVisitsAndBedDayCostSettingList,
} from './service';

import './style.less';

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

export default function VisitsAndBedDayCostSetting() {
  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: 'allocation',
      render: (num) => (
        <>{num == 1 ? '按照收入比例分配' : '按照固定比例分配'}</>
      ),
    },
    {
      title: '收入类型',
      dataIndex: 'incomeType',
      render: (num) => <>{num == 1 ? '门诊收入' : '住院收入'}</>,
    },
    {
      title: '对应值',
      dataIndex: 'incomeFileName',
    },
    {
      title: '分摊参数编码',
      dataIndex: 'shareParamCode',
    },
    {
      title: '分摊参数名称',
      dataIndex: 'shareParamName',
    },
    {
      title: '成本对应',
      dataIndex: 'costCorrespondingName',
    },
    {
      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 getVisitsAndBedDayCostSettingList({ ...params });
    if (resp) {
      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') => {
    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).join(','),
        });
        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,
              }
            : {}
        }
        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
      >
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择分配方式',
            },
          ]}
          options={[
            {
              value: 1,
              label: '按收入比例分配',
            },
            // {
            //   value: 2,
            //   label: '按照固定比例分配',
            // },
          ]}
          name="allocation"
          label="分配方式"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择收入类型',
            },
          ]}
          options={[
            {
              value: 1,
              label: '住院收入',
            },
            {
              value: 2,
              label: '门诊收入',
            },
          ]}
          name="incomeType"
          label="收入类型"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '请选择分摊参数',
            },
          ]}
          name="shareParamName"
          label="选择分摊参数"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '请选择对应收入字段',
            },
          ]}
          name="incomeFileName"
          label="对应收入字段"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '请选择对应成本字段',
            },
          ]}
          name="costCorrespondingName"
          label="对应成本字段"
        />
      </ModalForm>
    );
  };

  return (
    <KCIMPagecontainer className="VisitsAndBedDayCostSetting" 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 - 191px)` }}
          columns={columns as ProColumns[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
