import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, 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 api from './service';
import Make from '../deviceConfig/Make';

import StockLoc from '../deviceConfig/StockLoc';
/**
 * 添加节点
 *
 * @param fields
 */

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

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

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除数据字典');
  if (!selectedRows) return true;
  try {
    await api.removeDictData(selectedRows.map((row) => row.id)).then((r) => {
      if (r.data) {
        hide();
        message.success('删除成功，即将刷新');
        return true;
      } else {
        hide();
        message.error('删除失败，请重试');
      }
    });
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const ConfigDataManage = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  /**详情 */
  const [showDetail, setShowDetail] = useState();
  /*绑定数据 */
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();

  const [createStockLocModalVisible, handleStockLocModalVisible] = useState();
  const [createMakeModalVisible, handleMakeModalVisible] = 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: 'value',
    },
    {
      title: '设备系列编码',
      dataIndex: 'code',
    },
    {
      title: '备注',
      dataIndex: 'remark',

      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '停用',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          onClick={() => {
            handleStockLocModalVisible(true);
            setStepFormValues(record);
          }}
        >
          {' '}
          库存位置配置
        </a>,
        <a
          onClick={() => {

            handleMakeModalVisible(true);
            setStepFormValues(record);
          }}
        >
          {' '}
          设备做法
        </a>,
        <a
          onClick={() => {
            handleModalVisible(true);
            setStepFormValues(record);
          }}
        >
          {' '}
          更新
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            api.removeDictData([record.id]).then((r) => {
              if (r.data) {
                message.success('删除成功，即将刷新');
                actionRef.current.reload();
              } else {
                message.error('删除失败，请重试');
              }
            });
          }}
          onCancel={() => { }}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="设备系列配置列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var dictData = [];
          var total = 0;
          params.TypeCode = 'DeviceClientType';
          await api.GetDictData(params).then((r) => {
            dictData = r.data.data;
            total = r.data.total;
          });
          return {
            data: dictData,
            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;
          value.TypeCode = 'DeviceClientType';
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setStepFormValues({});
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          actionRef.current.reload();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        createModalVisible={createModalVisible}
        values={stepFormValues || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
      <StockLoc
        onCancel={() => {
          handleStockLocModalVisible(false);
        }}
        createModalVisible={createStockLocModalVisible}
        values={stepFormValues || {}}
      />
      <Make
        onCancel={() => {
          handleMakeModalVisible(false);
        }}
        createModalVisible={createMakeModalVisible}
        values={stepFormValues || {}}
      />
    </PageContainer>
  );
};

export default ConfigDataManage;
