/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:52: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 { createFromIconfontCN } from '@ant-design/icons';
import FormItem from 'antd/es/form/FormItem';

import {
  ActionType,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import { ModalForm, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Modal, Tag } 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 {
  getResponsibilityCenterConnectList,
  saveResponsibilityCenterConnected,
} from './service';

import './style.less';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq, renameChildListToChildren } from '@/utils/tooljs';
import React from 'react';
import TableTransfer from './transform';
import { searchTree } from '../responsibilityCenter';

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

const transferTableColumn: ProColumns[] = [
  {
    title: 'Id',
    width: 60,
    dataIndex: 'id',
  },
  {
    title: '科室名称',
    ellipsis: true,
    dataIndex: 'departmentName',
    renderText(text, record) {
      return record.departmentCode ? `${text}(${record.departmentCode})` : text;
    },
  },
];

let currentRow: any = undefined;

export default function ResponsibilityCenterConnect() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const columns: ProColumns[] = [
    {
      title: '责任中心名称',
      dataIndex: 'responsibilityName',
      ellipsis: true,
      width: 200,
      renderText(_, record) {
        const { isDefault, responsibilityName } = record;
        return isDefault == 1 ? (
          <Tag>{`${responsibilityName}(是)`}</Tag>
        ) : (
          responsibilityName
        );
      },
    },
    {
      title: '责任中心Id',
      ellipsis: true,
      width: 120,
      dataIndex: 'responsibilityId',
    },
    {
      title: '部门列表',
      ellipsis: true,

      dataIndex: 'departments',
      renderText(_, record) {
        if (Array.isArray(_)) {
          return _.map((item, index) => {
            return <Tag key={index}>{item.departmentName}</Tag>;
          });
        } else {
          return '';
        }
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 100,
      valueType: 'option',
      render: (_: any, record: any) => {
        const { isGatherCenter } = record;
        return isGatherCenter == 2
          ? [
              <a
                key="1"
                onClick={() => {
                  addConnectDepartments(record);
                  currentRow = record;
                }}
              >
                绑定科室
              </a>,
            ]
          : [];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const { filter } = params;
    const resp = await getResponsibilityCenterConnectList({ ...params });
    if (resp) {
      let data = [];
      if (filter) {
        const result = searchTree(
          renameChildListToChildren(resp.list, 'child'),
          filter,
        );
        data = result;
      } else {
        data = renameChildListToChildren(resp.list, 'child');
      }
      return {
        data: data,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    }
    return [];
  };

  const onSaveHandle = async (keys: Key[], rows: any[]) => {
    const { responsibilityId } = currentRow;
    const resp = await saveResponsibilityCenterConnected({
      responsibilityId,
      departmentIds: keys,
    });
    if (resp) {
      currentRow = undefined;
      tableRef.current?.reload();
    }
  };

  const addConnectDepartments = (record: any) => {
    const ref = React.createRef<{ save: any }>();

    Modal.confirm({
      title: `选择科室`,
      icon: <></>,
      width: 750,
      centered: true,
      okText: '确定',
      cancelText: '取消',
      content: (
        <TableTransfer
          ref={ref}
          record={record}
          onSave={onSaveHandle}
          leftColumns={transferTableColumn}
          rightColumns={transferTableColumn}
          dataSource={[]}
        ></TableTransfer>
      ),
      onOk: () => {
        return ref.current && ref.current.save();
      },
    });
  };

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

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

  return (
    <KCIMPagecontainer className="ResponsibilityCenterConnect" title={false}>
      <div className="toolBar" style={{ marginBottom: 16 }}>
        <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"></div>
      </div>

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