/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:37:11
 * @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,
  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 { useEffect, useRef, useState } from 'react';

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

import './style.less';

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';

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

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

const resultTypeList = [
  {
    label: '无需操作',
    value: 1,
  },
  {
    label: '需改善回复',
    value: 2,
  },
  {
    label: '需使用改善工具',
    value: 3,
  },
];

export default function DicClassfication() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const modalFormRef = useRef<ProFormInstance>();
  const [pagination, set_pagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
  });

  const columns: ProColumns[] = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '定性选项',
      dataIndex: 'name',
    },
    {
      title: '选项编码',
      dataIndex: 'code',
    },
    {
      title: '类型',
      dataIndex: 'resultTypeName',
    },
    {
      title: '是否默认',
      dataIndex: 'defaultFlag',
      renderText(num, record, index, action) {
        return num == 1 ? '是' : '否';
      },
    },
    {
      title: '排序序号',
      dataIndex: 'sort',
    },
    {
      title: '默认颜色',
      dataIndex: 'color',
      renderText(text, record, index, action) {
        return (
          <span
            style={{
              display: 'inline-block',
              backgroundColor: `#${text}`,
              padding: 2,
              borderRadius: 4,
              color: '#fff',
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      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,
  ): Promise<TableDataResponse | any[]> => {
    const resp = await getData({ ...params });
    if (resp) {
      if (resp.totalCount == 0 && resp.currPage != 1) {
        return getTableData({ ...params, current: resp.currPage - 1 });
      } else {
        return {
          data: resp.list,
          success: true,
          total: resp.totalCount,
          pageSize: resp.pageSize,
          totalPage: resp.totalPage,
        };
      }
    }
    return [];
  };

  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 currentHosp = localStorage.getItem('currentSelectedSubHop');
      const currentUser = localStorage.getItem('userData');
      if (currentHosp && currentUser) {
        const { id } = JSON.parse(currentHosp);
        const { userId } = JSON.parse(currentUser);
        const result = {
          hiId: id,
          code: formVal.code,
          name: formVal.name,
          resultType: formVal.resultType,
          defaultFlag: formVal.defaultFlag,
          sort: formVal.sort,
          delFlag: '',
          createUser: userId,
          createTime: new Date().getTime(),
          color: formVal.color,
        };
        const resp = await addData({ ...formVal });
        if (resp) {
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      }
    }
    if (type == 'EDIT') {
      const resp = await editData({ ...formVal });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }

    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}定性选项`}
        width={352}
        initialValues={type == 'EDIT' ? { ...record } : {}}
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        formRef={modalFormRef}
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText
          name="name"
          label="定性选项："
          placeholder="请输入"
          rules={[{ required: true, message: '定性不能为空!' }]}
        />
        <ProFormText
          name="code"
          label="选项编码："
          placeholder="请输入"
          rules={[{ required: true, message: '编码不能为空!' }]}
        />
        <ProFormSelect
          label="类型："
          name="resultType"
          request={async () => {
            return resultTypeList;
          }}
          rules={[{ required: true, message: '类型不能为空!' }]}
        />

        <ProFormSelect
          label="是否默认："
          name="defaultFlag"
          request={async () => {
            return [
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ];
          }}
        />
        <ProFormDigit name="sort" label="排序序号：" placeholder="请输入" />
        <ProFormSelect
          label="默认颜色："
          name="color"
          request={async () => {
            const currentSys = localStorage.getItem('currentSelectedTab');
            if (currentSys) {
              const { systemId } = JSON.parse(currentSys);
              const resp = await getColorFromDic({
                dictType: 'COLOR_TYPE',
                systemId: systemId,
              });

              if (resp && resp.length > 0) {
                const list = resp[0].dataVoList.map((a: any) => {
                  if (type == 'ADD' && a.defaultValue) {
                    modalFormRef.current?.setFieldValue('color', a.value);
                  }
                  return {
                    label: (
                      <span
                        style={{
                          background: `#${a.value}`,
                          color: '#fff',
                          width: 20,
                          height: 15,
                          display: 'inline-block',
                          position: 'relative',
                          top: 1,
                        }}
                      >
                        {}
                      </span>
                    ),
                    value: a.value,
                  };
                });
                return list;
              }
            }

            return [];
          }}
        />
      </ModalForm>
    );
  };

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

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

  return (
    <KCIMPagecontainer className="QualitativeOptMana" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem" style={{ marginRight: 16, width: 205 }}>
            <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 className="filterItem">
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              类型：
            </span>
            <ProFormSelect
              noStyle
              allowClear
              placeholder="请选择"
              style={{ width: 160, marginRight: 16 }}
              request={async () => {
                return resultTypeList;
              }}
              fieldProps={{
                onChange(value, option) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    resultType: 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>
  );
}
