import { DropboxOutlined, 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 MemberInfoTable from './components/memberInfoList';
import api from './services';

//页面 相当于 class
const MemberTagManage = () => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [showDetail, setShowDetail] = useState(false);
  //绑定
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  //选中的行
  const [selectedRowsState, setSelectedRows] = useState([]);

  //分配会员
  const [memberInfoModalVisible, setMemberInfoModalVisible] = useState(false);
  /**
   * 添加节点
   *
   * @param fields
   */
  function handleAdd(fields) {
    try {
      api.addMemberTag(JSON.stringify(fields)).then((r) => {
        if (r.data) {
          message.success('添加成功');
          //刷新数据
          actionRef.current.reload();
        } else {
          message.success('添加失败请重试！');
        }
      });
      return true;
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  }

  /**
   * 更新节点
   *
   * @param fields
   */

  function handleUpdate(fields) {
    try {
      api.updateMemberTag(fields).then((r) => {
        if (r.data) {
          message.success('更新成功');
        } else {
          message.error('更新失败请重试！');
        }
      });
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.error('更新失败请重试！');
      return false;
    }
  }

  /**
   * 删除节点
   *
   * @param selectedRows
   */
  function handleRemove() {
    try {
      api.removeMemberTag(selectedRowsState.map((item, index) => item.id)).then((r) => {
        if (r.data) {
          message.success('删除成功，即将刷新');
        } else {
          message.error('删除失败，请重试');
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
    }
  }

  /** 国际化配置 */

  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: 'name',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: '平台',
      dataIndex: 'platformType',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '默认平台',
          defaultPlatformType: 'Processing',
        },
        1: {
          text: '微信',
          defaultPlatformType: 'Success',
        },
        2: {
          text: '支付宝',
          defaultPlatformType: 'Default',
        },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '停用',
          status: 'Success',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
        <Popconfirm
          key="primary"
          type="primary"
          title="确认删除吗"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            //handleRemoveSingle(record.id);
            api.removeMemberTag([record.id]).then((r) => {
              if (r.data) {
                message.success('删除成功，即将刷新');
                actionRef.current.reload();
              } else {
                message.error('删除失败，请重试');
              }
            });
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
        <a
          key="primary"
          onClick={() => {
            setCurrentRow(record);
            setMemberInfoModalVisible(true);
          }}
        >
          {' '}
          分配会员平台
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="会员标签管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        //数据绑定
        request={async (params) => {
          var memberTagData = [];
          var total = 0;
          await api.memberTagList(params).then((r) => {
            memberTagData = r.data.data;
            memberTagData.forEach((x) => {
              x.status = x.status.toString();
              x.platformType = x.platformType.toString();
            });
            total = r.data.total;
          });
          return {
            data: memberTagData,

            success: true,
            total: total,
          };
        }}
        // 每行选择点击事件
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      ></ProTable>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={() => {
              handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            type="primary"
            key="primary"
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      {/* 会员标签管理(新增，修改) */}
      <CreateForm
        isAdd="true"
        onFinish={async (value) => {

          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
      <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>
      {/* 分配会员 */}
      <MemberInfoTable
        onCancel={() => {
          setMemberInfoModalVisible(false);
          setCurrentRow({});
        }}
        memberInfoModalVisible={memberInfoModalVisible}
        values={currentRow}
      />
    </PageContainer>
  );
};

export default MemberTagManage;
