import { PlusOutlined } from '@ant-design/icons';
import { Checkbox, Modal, Space, Tag, Button, message, Popconfirm, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import IntegralRecord from './components/IntegralRecord';
import moment from 'moment';
import {
  GetMemberPageQuery,
  UpdateMemberStatus,
  UpdateMemberInfo,
  GetMemberTagAndInfo,
  UpdateMemberTag,
  SyncMember,
  GetPlatformMemberList,
  post,
  CreateMemberInfo,
} from './service';
import { get, set } from 'lodash-es';
import { encode, decode } from 'js-base64';

const CheckboxGroup = Checkbox.Group;

const plainOptions = ['Apple', 'Pear', 'Orange'];
const defaultCheckedList = ['Apple', 'Orange'];

const key = 'message';

/**
 * 判断会员名称是否被小程序加密
 * @param {*} str
 * @returns
 */
const isBase64 = (str) => {
  const result = decode(str);
  if (result.includes('BPA_BASE64')) {
    return true;
  } else {
    false;
  }
};

/**
 * 对小程序加密的昵称进行解密
 * @param {*} str
 * @returns
 */
const decodeBPABase64 = (str) => {
  return decode(str).replace('BPA_BASE64', '');
};

const MemberManage = () => {
  const actionRef = useRef();
  const actionRef2 = useRef();
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, SetCreateModalVisible] = useState(false);
  const [integralRecordVisible, SetIntegralRecordVisible] = useState(false);
  const [dataRow, setdataRow] = useState([]);
  const [dataRowKey, setDataRowKey] = useState([]);
  const [currentRow, setCurrentRow] = useState();
  //会员标签弹窗
  const [isTagModalVisible, setIsTagModalVisible] = useState(false);
  //会员标签和绑定详情
  const [memberTagAndInfo, SetMemberTagAndInfo] = useState([]);
  //选中的标签
  const [checkedTagList, setCheckedTagList] = React.useState();
  const [isLook, setIsLook] = useState(false);

  const PlatformMemberList = async (memberId) => {
    await GetPlatformMemberList(memberId).then((r) => {
      setdataRow(r.data);
    });
  };

  //添加会员信息
  const AddMemberInfo = async (fields) => {
    message.loading('正在添加...', key);
    try {
      fields.status = 0;
      await CreateMemberInfo(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('添加成功');
        } else {
          message.error('添加失败');
        }
      });
      //刷新数据
      actionRef.current.reloadAndRest();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('添加失败请重试！');
      return false;
    }
  };

  //修改会员信息
  const updateMemberInfo = async (fields) => {
    message.loading('正在修改...', key);
    try {
      await UpdateMemberInfo(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('修改成功');
        } else {
          message.error('修改失败' + r.errors == null ? '' : r.errors);
        }
      });
      //刷新数据
      actionRef.current.reloadAndRest();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('修改失败请重试！');
      return false;
    }
  };

  //修改会员状态
  const updateMemberStatus = async (fields) => {
    message.loading('正在修改...', key);
    try {
      await UpdateMemberStatus(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          PlatformMemberList(fields.Id);
          message.success('修改成功');
        } else {
          message.error('修改失败' + r.errors == null ? '' : r.errors);
        }
      });
      //刷新数据
      actionRef.current.reloadAndRest();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('修改失败请重试！');
      return false;
    }
  };
  //修改会员标签
  const updateMemberTag = async (platformType, memberInfo_Id) => {
    message.loading('正在修改...', key);
    try {
      await UpdateMemberTag(
        JSON.stringify({
          platformType: platformType,
          memberInfo_Id: memberInfo_Id,
          tags: checkedTagList,
        }),
      ).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('修改成功');
        } else {
          message.error('修改失败' + r.errors == null ? '' : r.errors);
        }
      });
      //刷新数据
      actionRef.current.reloadAndRest();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('修改失败请重试！');
      return false;
    }
  };

  //获取会员标签和会员的绑定标签
  const getMemberTagAndInfo = async (memberinfoid, platformtype) => {
    await GetMemberTagAndInfo(memberinfoid, platformtype).then((r) => {
      if (r.data) {
        var list = [];
        var list2 = [];
        r.data.forEach((element) => {
          if (element.memberTagInfoId != null) {
            list2.push(element.id);
          }
          list.push({ label: element.name, value: element.id });
        });
        SetMemberTagAndInfo(list);
        setCheckedTagList(list2);
      }
    });
  };

  /** 国际化配置 */
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '头像',
      dataIndex: 'headImgUrl',
      search: false,
      hideInForm: true,
      render: (_, record) => (
        <img src={record.headImgUrl} style={{ width: '45px', height: '45px' }}></img>
      ),
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      valueType: 'textarea',
      ellipsis: {
        showTitle: true,
      },
      hideInForm: true,
      render: (_, record) => (
        <a>{isBase64(record.nickName) ? decodeBPABase64(record.nickName) : record.nickName}</a>
      ),
    },
    {
      title: '电话',
      dataIndex: 'phone',
      valueType: 'textarea',
      hideInForm: true,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      search: false,
      valueEnum: {
        0: { text: '未知' },
        1: { text: '男' },
        2: { text: '女' },
      },
    },
    {
      title: '等级',
      dataIndex: 'level',
      search: false,
      valueType: 'textarea',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '正常', status: 'Success' },
        1: { text: '禁用', status: 'error' },
      },
    },
    {
      title: '标签',
      dataIndex: 'memberTag',
      search: false,
      width: 300,
      render: (_, record) => (
        <Space>
          {record.memberTag.map(({ id, name }) => (
            <Tag color="#87d068" key={id}>
              {name}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      search: false,
      width: 150,
      valueType: 'textarea',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 300,
      render: (_, record) => {
        let template = [
          <a
            key="primary"
            type="primary"
            onClick={() => {
              SetCreateModalVisible(true);
              setCurrentRow(() => {
                record.birthday = moment(record.birthday);
                setIsLook(true);
                return record;
              });
            }}
          >
            详情
          </a>,
          <a
            key="primary"
            type="primary"
            onClick={() => {
              SetCreateModalVisible(true);
              setCurrentRow(() => {
                record.birthday = moment(record.birthday);
                setIsLook(false);
                return record;
              });
            }}
          >
            更新
          </a>,
          // <Popconfirm
          //   key="delete"
          //   title={`确定要${record.status == 0 ? '禁用' : '启用'}吗？`}
          //   onConfirm={async () => {
          //     var data = { Id: record.id, platformType: 0, status: record.status == 0 ? 1 : 0 };
          //     updateMemberStatus(data);
          //   }}
          //   okText="确定"
          //   cancelText="取消"
          // >
          //   <a
          //     key="primary"
          //     type="primary"
          //   >
          //     {record.status == 0 ? '禁用 ' : '启用'}
          //   </a>
          // </Popconfirm>,


          <a
            key="primary"
            type="primary"
            onClick={() => {
              getMemberTagAndInfo(record.id, 0);
              setIsTagModalVisible(true);
              setCurrentRow(() => {
                return record;
              });
            }}
          >
            标签管理
          </a>,
          // <a
          //   key="primary"
          //   type="primary"
          //   onClick={() => {
          //     setCurrentRow(record);
          //     SetIntegralRecordVisible(true);
          //   }}
          // >
          //   积分记录
          // </a>,
        ];
        return template;
      },
    },
  ];
  const onExpand = (expanded, record) => {
    if (expanded) {
      setdataRow(record.platformMemberInfos);
      setDataRowKey([record.id]);
    } else {
      setDataRowKey([]);
    }
  };
  const expandedRowRender = (data) => {
    return (
      <ProTable
        rowKey="id"
        actionRef={actionRef2}

        pagination={{
          pageSize: 10
        }}
        scroll={{
          x: 1300,
        }}
        columns={[
          {
            title: '平台',
            dataIndex: 'platformType',
            key: 'platformType',
            valueEnum: {
              1: { text: '微信' },
              2: { text: '支付宝' },
              3: { text: 'POS' },
              4: { text: '储值卡' },
            },
          },
          {
            title: '头像',
            dataIndex: 'headImgUrl',
            valueType: 'textarea',
            search: false,
            hideInForm: true,
            render: (_, record) => (
              <img src={record.headImgUrl} style={{ width: '45px', height: '45px' }}></img>
            ),
          },
          {
            title: '昵称',
            dataIndex: 'nickName',
            valueType: 'textarea',
            hideInForm: true,
            render: (_, record) => (
              <a>
                {isBase64(record.nickName) ? decodeBPABase64(record.nickName) : record.nickName}
              </a>
            ),
          },
          {
            title: '性别',
            dataIndex: 'sex',
            search: false,
            valueEnum: {
              0: { text: '未知' },
              1: { text: '男' },
              2: { text: '女' },
            },
          },
          {
            title: '状态',
            dataIndex: 'status',
            valueEnum: {
              0: { text: '正常', status: 'Success' },
              1: { text: '禁用', status: 'error' },
            },
          },
          {
            title: '标签',
            dataIndex: 'memberTag',
            key: 'memberTag',
            width: 450,
            render: (_, record) => (
              <>
                <Space>
                  {record.memberTag.map(({ id, name }) => (
                    <Tag color="#87d068" key={id}>
                      {name}
                    </Tag>
                  ))}
                </Space>
              </>
            ),
          },
          {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => {
              let template = [
                // <a
                //   key="primary"
                //   type="primary"
                //   onClick={() => {
                //     SetCreateModalVisible(true);
                //     setCurrentRow(() => {
                //       record.birthday = moment(record.birthday);
                //       return record;
                //     });
                //   }}
                // >
                //   更新
                // </a>,
                // <a
                //   key="primary"
                //   type="primary"
                //   onClick={() => {
                //     var data = {
                //       Id: record.memberInfo_Id,
                //       platformType: record.platformType,
                //       status: record.status == 0 ? 1 : 0,
                //     };
                //     updateMemberStatus(data);
                //   }}
                // >
                //   {record.status == 0 ? '禁用 ' : '启用'}
                // </a>,
                <a
                  key="primary"
                  type="primary"
                  onClick={() => {
                    getMemberTagAndInfo(record.memberInfo_Id, record.platformType);
                    setIsTagModalVisible(true);
                    setCurrentRow(() => {
                      return record;
                    });
                    PlatformMemberList(record.memberInfo_Id);
                  }}
                >
                  标签管理
                </a>,
              ];
              return template;
            },
          },
        ]}
        headerTitle={false}
        search={false}
        options={false}
        dataSource={dataRow}
      />
    );
  };
  return (
    <PageContainer
      header={{
        title: '',
        breadcrumb: {},
      }}
    >
      <ProTable
        headerTitle="会员信息"
        pagination={{
          pageSize: 10,
        }}
        scroll={{
          x: 1300,
        }}
        actionRef={actionRef}
        onExpand={onExpand}
        expandedRowKeys={dataRowKey}
        rowKey="id"
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              // SyncMember(1).then((r) => {
              //   message.success('启动同步,稍后请刷新页面');
              // });
              setIsLook(false);
              setCurrentRow({});
              SetCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 添加会员
          </Button>,
        ]}
        expandable={{ expandedRowRender }}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetMemberPageQuery(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
      />

      {/* 修改会员 */}
      <CreateForm
        isLook={isLook}
        onFinish={async (value) => {
          // value.birthday = value.birthday._i;
          var success = false;
          value.MemberInfo_Id = value.id;
          if (value.id) {
            success = updateMemberInfo(value);
          } else {
            success = AddMemberInfo(value);
          }
          if (success) {
            SetCreateModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reloadAndRest();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          SetCreateModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />

      {/* 会员标签 */}
      <Modal
        title="会员标签"
        visible={isTagModalVisible}
        onOk={() => {
          if (
            updateMemberTag(
              currentRow.platformType,
              currentRow.platformType == 0 ? currentRow.id : currentRow.memberInfo_Id,
            )
          ) {
            setIsTagModalVisible(false);
            setDataRowKey([]);
          }
        }}
        onCancel={() => {
          setCurrentRow([]);
          setIsTagModalVisible(false);
        }}
      >
        <>
          <CheckboxGroup
            options={memberTagAndInfo}
            value={checkedTagList}
            onChange={(list) => {
              setCheckedTagList(list);
            }}
          />
        </>
      </Modal>
      {/* 积分记录 */}
      {/* <IntegralRecord
        onClose={() => {
          SetIntegralRecordVisible(false);
        }}
        memberId={currentRow?.id}
        integralRecordVisible={integralRecordVisible}
      /> */}
    </PageContainer>
  );
};

export default MemberManage;
