/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-10-13 11:20:45
 * @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 { createFromIconfontCN } from '@ant-design/icons';

import {
  ActionType,
  DrawerForm,
  EditableFormInstance,
  EditableProTable,
  ProFormInstance,
  ProFormSelect,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDigit,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

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

import './style.less';

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import KCIMDrawerForm from '@/components/KCIMDrawerForm';
import TableSelecter from './tableSelector';

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

type TableDataResponse = {
  data: any[];
  success: boolean;
  total: number;
  pageSize: number;
  totalPage: number;
};

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

  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);
  const [tableSelecterType, set_tableSelecterType] = useState<
    'EMP' | 'CHECKGROUP'
  >('EMP'); //穿梭框类型

  const [currentEdit, set_currentEdit] = useState<any | undefined>(undefined);

  const columns: ProColumns[] = [
    {
      title: 'Code',
      dataIndex: 'code',
    },
    {
      title: '展示排序',
      dataIndex: 'sort',
    },
    {
      title: '单位名',
      dataIndex: 'name',
    },
    {
      title: '职能科室',
      dataIndex: 'createUserName',
    },
    {
      title: '单位负责人',
      dataIndex: 'manager',
      renderText(list, record, index, action) {
        if (list) {
          return list.reduce(
            (prev: string, cur: any) =>
              `${prev.length > 0 ? prev + ',' : ''}${cur.name}`,
            '',
          );
        }
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '是否作废',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      key: 'option',
      width: 140,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <a
            key={'emp'}
            onClick={() => {
              openTransformModal(record);
              set_tableSelecterType('EMP');
            }}
          >
            人员
          </a>,
          // <a key={'theme'}>主题</a>,
          // <a key={'checkPoint'}>查核要点</a>
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getData(params);
    if (resp) {
      return {
        data: resp,
        success: true,
      };
    }
    return [];
  };

  const openTransformModal = (record: any) => {
    set_currentEdit(record);
    set_tableSelecterVisible(true);
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    const content = formVal.table.map((a: any) => ({}));

    if (type == 'ADD') {
      const result = {
        name: formVal.name,
        content: JSON.stringify(formVal.table),
        remark: formVal.remark,
      };
      const resp = await addData({ ...result });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      const result = {
        id: formVal.id,
        name: formVal.name,
        content: JSON.stringify(formVal.table),
        remark: formVal.remark,
      };
      const resp = await editData({ ...result });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }

    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    const formRef = useRef<ProFormInstance<any>>();

    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}单位`}
        width={400}
        initialValues={
          type == 'EDIT'
            ? { ...record, filedType: 'Text' }
            : { filedType: 'Text' }
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val: any) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        formRef={formRef}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText
          name="name"
          label="单位名称："
          placeholder="请输入"
          rules={[{ required: true, message: '名称不能为空!' }]}
        />
        <ProFormDigit name="sort" label="展示排序" />
        <ProFormTextArea name="remark" label="备注：" placeholder="请输入" />
      </ModalForm>
    );
  };

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

  const tableSelecterCommit = async (keys: React.Key[], rows: any[]) => {};

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

  return (
    <KCIMPagecontainer className="unitMana" title={false}>
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="关联"
        rowKey="id"
        tableSelecterType={tableSelecterType}
        record={currentEdit}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />

      <div className="toolBar">
        <div className="filter">
          <div className="filterItem" style={{ marginRight: 16, width: 250 }}>
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              检索：
            </span>
            <Input
              placeholder={'请输入单位/负责人'}
              allowClear
              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[]}
          actionRef={tableRef}
          rowKey="id"
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
