/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-10-13 16:40:53
 * @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,
  ProFormCheckbox,
  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, Switch } from 'antd';
import { createRef, useEffect, useRef, useState } from 'react';

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

import './style.less';

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import KCIMDrawerForm from '@/components/KCIMDrawerForm';
import TableTransfer from './transform';
import TableSelecter from './tableSelector';
import { getCheckData } from '../checkGroupMana/service';
import { debounce } from 'lodash';

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<
    'UNIT' | 'CHECKGROUP'
  >('UNIT'); //穿梭框类型

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

  const columns: ProColumns[] = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    // {
    //     title: '工号',
    //     dataIndex: 'employeeId',
    // },
    {
      title: '用户名',
      dataIndex: 'account',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '查核组',
      dataIndex: 'groupList',
      ellipsis: true,
      renderText(groupList, record, index, action) {
        if (groupList) {
          return groupList.reduce(
            (prev: string, next: any) =>
              `${prev.length > 0 ? prev + ',' : prev}${next.name}`,
            '',
          );
        }
      },
    },
    {
      title: '单位名',
      dataIndex: 'departList',
      ellipsis: true,
      renderText(departList, record, index, action) {
        if (departList) {
          return departList.reduce(
            (prev: string, next: any) =>
              `${prev.length > 0 ? prev + ',' : prev}${next.name}`,
            '',
          );
        }
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 160,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <a
            key="unit"
            onClick={() => {
              openTransformModal(record);
              set_tableSelecterType('UNIT');
            }}
          >
            单位
          </a>,
          <a
            key="checkGroup"
            onClick={() => {
              openTransformModal(record);
              set_tableSelecterType('CHECKGROUP');
            }}
          >
            查核组
          </a>,
        ];
      },
    },
  ];

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

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    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,
        employeeId: formVal.employeeId,
        account: formVal.account,
        permission: formVal.permission.join(','),
      };
      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={600}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                permission: record.roleList ? record.roleList.split(',') : [],
              }
            : {}
        }
        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
      >
        <ProFormCheckbox.Group
          name="permission"
          layout="horizontal"
          label="行业分布"
          options={[
            { label: '管理员', value: '1' },
            { label: '查核组长', value: '2' },
            { label: '查核组员', value: '3' },
            { label: '单位负责人', value: '4' },
            { label: '改善人', value: '5' },
            { label: '职能科室负责人', value: '6' },
            { label: '职能科室普通人员', value: '7' },
            { label: '自查人', value: '8' },
          ]}
        />
      </ModalForm>
    );
  };

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

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

  const tableSelecterCommit = async (keys: React.Key[], rows: any[]) => {
    if (tableSelecterType == 'CHECKGROUP') {
      const result = {
        employeeId: currentEdit.employeeId,
        employeeName: currentEdit.name,
        groupList: rows.map((a: any) => ({
          code: a.code,
          name: a.name,
          isManager: a.flag ? 1 : 0,
        })),
      };
      const resp = await bindCheckGroupReq(result);
      if (resp) {
        set_tableSelecterVisible(false);
        tableRef.current?.reload();
      }
    }
    if (tableSelecterType == 'UNIT') {
      const result = {
        employeeId: currentEdit.employeeId,
        employeeName: currentEdit.name,
        departmentList: rows.map((a: any) => ({
          code: a.code,
          name: a.name,
          isManager: a.flag ? 1 : 0,
          isFunction: 0,
        })),
      };
      const resp = await bindUnitReq(result);
      if (resp) {
        set_tableSelecterVisible(false);
        tableRef.current?.reload();
      }
    }
  };

  const debouncedFetch = debounce(async (keyWords, callback) => {
    const resp = await getCheckData({
      pageSize: 20,
      current: 1,
      filter: keyWords,
    });
    if (resp) {
      callback(
        resp.list.map((a: any) => ({
          label: a.name,
          value: a.code,
        })),
      );
    } else {
      callback([]);
    }
  }, 300);

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

  return (
    <KCIMPagecontainer className="empMana" title={false}>
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="关联"
        rowKey={tableSelecterType == 'UNIT' ? 'code' : '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: 220 }}>
            <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>
  );
}
