import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Modal, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import DictData from '../dictdata';
import api from './service';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  try {
    await api.addDictType(fields).then((r) => {
      if (r.succeeded) {
        message.success('添加成功');
      } else {
        message.error(r.errors);
      }
    });
    return true;
  } catch (error) {
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  try {
    await api.updateDictType(fields).then((r) => {
      if (r.succeeded) {
        message.success('修改成功');
      } else {
        message.error(r.errors);
      }
    });
    return true;
  } catch (error) {
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  if (!selectedRows) return true;
  const hide = message.loading('正在删除数据字典类型');
  try {
    await api.removeDictType(selectedRows.map((row) => row.id)).then((r) => {
      if (r.succeeded) {
        hide();
        message.success('删除成功，即将刷新');
        return true;
      } else {
        hide();
        message.error(r.errors);
      }
    });
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }

};
const DictTypeManage = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  /**详情 */
  const [showDetail, setShowDetail] = useState();
  /*绑定数据 */
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();

  /** 国际化配置 */
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: 'key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '类型编码',
      dataIndex: 'code',
    },
    {
      title: '类型名称',
      dataIndex: 'name',
      ellipsis:true
    },

    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
      ellipsis: true,
      
    },
    
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 350,
      render: (_, record) => [
        <a
          onClick={() => {
            handleModalVisible(true);
            setStepFormValues(record);
          }}
        >
          {' '}
          更新
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            api.removeDictType([record.id]).then((r) => {
              if (r.data) {
                message.success('删除成功，即将刷新');
                actionRef.current.reloadAndRest();
              } else {
                message.error('删除失败，请重试');
              }
            });
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
            <a
            onClick={() => {
              setShowDetail(true);
              setStepFormValues(record);
            }}
          >
            {' '}
            字典详情
          </a>,
      ],
    },
  ];
  const handleOk = () => {
    setShowDetail(false);
  };
  return (
    <PageContainer ghost header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
      style={{marginTop: '20px'}}
        headerTitle="字典类型列表"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var dictTypeData = [];
          var total = 0;
          await api.getDictType(params).then((r) => {
            dictTypeData = r.data.data;
            total = r.data.total;
          });
          return {
            data: dictTypeData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            type="primary"
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reloadAndRest();
            }
          }
          actionRef.current.reloadAndRest();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        createModalVisible={createModalVisible}
        values={stepFormValues || {}}
      />
      <Modal title="字典详情" 
      open={showDetail} 
      destroyOnClose
      footer={null}
        width={1300}
        onCancel={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
      >
        {stepFormValues?.name && (
         <DictData  currentRow={stepFormValues}/>
        )}
      </Modal>
    </PageContainer>
  );
};

export default DictTypeManage;
