/*
 Navicat Premium Dump SQL

 Source Server         : game_grade
 Source Server Type    : MySQL
 Source Server Version : 80036 (8.0.36)
 Source Host           : rm-bp1749tfxu2rpq670lo.mysql.rds.aliyuncs.com:3306
 Source Schema         : game_db

 Target Server Type    : MySQL
 Target Server Version : 80036 (8.0.36)
 File Encoding         : 65001

 Date: 15/03/2026 19:27:51
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for agent
-- ----------------------------
DROP TABLE IF EXISTS `agent`;
CREATE TABLE `agent`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `agen_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `agen_name` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商名称',
  `agen_logo` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '代理商logo，80*50',
  `agen_parentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '上级代理商ID',
  `agen_idxcode` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT '' COMMENT '代理商树状结构编码 3位一级',
  `agen_state` tinyint(1) NULL DEFAULT 0 COMMENT '状态 0-启用 1-禁用',
  `agen_sharingmode` tinyint(1) NULL DEFAULT 0 COMMENT '分成模式 0-普通模式 1-阶梯模式',
  `agen_sharingrate` tinyint NULL DEFAULT 100 COMMENT '普通模式分成比例  正整数[0, 99]，表示100元分成多少',
  `agen_selftotal` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '自己的总流水',
  `agen_selfsharing` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '自己的总分成',
  `agen_childsharing` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '子代理的总分成',
  `agen_maxplayerid` int NULL DEFAULT 100000 COMMENT '当前最大的玩家id',
  `agen_maxsalesid` int NULL DEFAULT 200000 COMMENT '当前最大的个人代理id',
  `agen_scrollmsg` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '滚动公告内容',
  `agen_noticemsg` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '通知公告内容',
  `agen_server` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '代理商服务器地址，不需要\"http\"前缀',
  `agen_server_visitor` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `agen_port_tcp` int NULL DEFAULT NULL COMMENT '代理商服务器tcp端口',
  `agen_port_http` int NULL DEFAULT NULL COMMENT '代理商服务器http端口',
  `agen_downloadhtml` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT 'app下载页面',
  `agen_freeroom` int NULL DEFAULT 300 COMMENT '默认同意解散房间的倒计时，秒',
  `agen_salespower` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT '22',
  `agen_managecode` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '管理码，关闭、开启服务器、发送系统消息时验证使用',
  `agen_user` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '登录运营后台的用户名',
  `agen_pwd` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '登录运营后台的密码',
  `agen_initroomacard` int NULL DEFAULT 8,
  `agen_initbean` int NULL DEFAULT 0,
  `agen_rebatemode1` tinyint(1) NULL DEFAULT 0,
  `agen_rebateset1` int NULL DEFAULT 0,
  `agen_rebatemode2` tinyint(1) NULL DEFAULT 0,
  `agen_rebateset2` int NULL DEFAULT 0,
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `agent_index`(`agen_agentid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 133 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '代理商表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_channel
-- ----------------------------
DROP TABLE IF EXISTS `agent_channel`;
CREATE TABLE `agent_channel`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `agch_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `agch_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商id',
  `agch_channelname` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商名称',
  `agch_WechatPublicNo` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商微信公众号',
  `agch_wechat_ewm` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '' COMMENT '渠道商微信公众号二维码图片链接地址',
  `agch_service_wechat` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商客服微信号',
  `agch_service_qq` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商客服QQ号',
  `agch_service_tel` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商客服电话',
  `agch_sales_tel` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '' COMMENT '渠道商售卡电话',
  `agch_sales_wechat` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '' COMMENT '渠道商售卡微信',
  `agch_youle_appid` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '友乐开发平台appid',
  `agch_youle_devkey` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '友乐开发平台devkey',
  `agch_youle_busiid` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '友乐开发平台businessid',
  `agch_youle_signkey` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '友乐开发平台signkey微信支付签名',
  `agch_invitecode` int NULL DEFAULT NULL,
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `agent_channel_index`(`agch_agentid` ASC, `agch_channelid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 88 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '代理商的渠道表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_channel_city
-- ----------------------------
DROP TABLE IF EXISTS `agent_channel_city`;
CREATE TABLE `agent_channel_city`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `agcc_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `agcc_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商id',
  `agcc_citycode` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '城市编码',
  `agcc_city` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市名称',
  `agcc_WechatPublicNo` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市微信公众号',
  `agcc_wechat_ewm` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市微信公众号二维码图片链接地址',
  `agcc_service_wechat` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市客服微信号',
  `agcc_service_qq` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市客服QQ号',
  `agcc_service_tel` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市客服电话',
  `agcc_invitecode` int NULL DEFAULT NULL COMMENT '默认的邀请码',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `agent_channel_city_index`(`agcc_agentid` ASC, `agcc_channelid` ASC, `agcc_citycode` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '城市配置表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_game
-- ----------------------------
DROP TABLE IF EXISTS `agent_game`;
CREATE TABLE `agent_game`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `agga_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理id',
  `agga_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `agga_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道id',
  `agga_aliasname` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商的游戏别名',
  `agga_image` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商的游戏图标',
  `agga_state` tinyint(1) NULL DEFAULT 0 COMMENT '状态 0:发布中 1:测试中 2: 研发中',
  `agga_gamememo` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '游戏简介',
  `agga_gameversion` int NOT NULL COMMENT '游戏版本号',
  `agga_android_ver` int NOT NULL COMMENT '安卓app实际版本号',
  `agga_android_vername` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '安卓app版本号，显示用',
  `agga_android_down` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '安卓app下载地址',
  `agga_android_size` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '安卓app大小',
  `agga_android_time` datetime NULL DEFAULT NULL COMMENT '安卓app发布时间',
  `agga_ios_ver` int NOT NULL COMMENT '苹果app实际版本号',
  `agga_ios_vername` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '苹果app版本号，显示用',
  `agga_ios_down` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '苹果app下载地址',
  `agga_ios_size` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '苹果app大小',
  `agga_ios_time` datetime NULL DEFAULT NULL COMMENT '苹果app发布时间',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `agent_game_index`(`agga_agentid` ASC, `agga_gameid` ASC, `agga_channelid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '代理商游戏表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_game_online
-- ----------------------------
DROP TABLE IF EXISTS `agent_game_online`;
CREATE TABLE `agent_game_online`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `aggo_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理id',
  `aggo_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `aggo_datetime` datetime NOT NULL COMMENT '统计时间',
  `aggo_onlineplayer` int NULL DEFAULT NULL COMMENT '在线玩家数量',
  `aggo_onlineroom` int NULL DEFAULT NULL COMMENT '开房房间数量',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `agent_game_online`(`aggo_agentid` ASC, `aggo_gameid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16479965 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '在线玩家数量统计表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_game_player
-- ----------------------------
DROP TABLE IF EXISTS `agent_game_player`;
CREATE TABLE `agent_game_player`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `agpl_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `agpl_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `agpl_playerid` int NOT NULL COMMENT '玩家id',
  `agpl_openid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信openid',
  `agpl_lasttime` datetime NOT NULL COMMENT '最后登录时间',
  `agpl_logindate` int NULL DEFAULT 1 COMMENT '累积登录天数',
  `agpl_usecard` int NULL DEFAULT 0 COMMENT '累积使用房卡数量',
  `agpl_firsttime` datetime NULL DEFAULT NULL,
  `agpl_playset` int NULL DEFAULT 0,
  `agpl_winlose` int NULL DEFAULT 0,
  `agpl_playset_xx` int NULL DEFAULT 0,
  `agpl_winlose_xx` int NULL DEFAULT 0,
  `agpl_winlose_x2` int NULL DEFAULT 0,
  `agpl_playset_b` int NULL DEFAULT 0,
  `agpl_winlose_b` int NULL DEFAULT 0,
  `agpl_playset_xx_b` int NULL DEFAULT 0,
  `agpl_winlose_xx_b` int NULL DEFAULT 0,
  `[REDACTED]` int NULL DEFAULT 0,
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `agent_game_player_index1`(`agpl_agentid` ASC, `agpl_gameid` ASC, `agpl_playerid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 255273 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '游戏的玩家表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_game_player_short
-- ----------------------------
DROP TABLE IF EXISTS `agent_game_player_short`;
CREATE TABLE `agent_game_player_short`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `agps_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `agps_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `agps_playerid` int NOT NULL COMMENT '玩家id',
  `agps_shortcode` int NOT NULL COMMENT '房间短号',
  `agps_playset` int NULL DEFAULT 0 COMMENT '累积游戏局数（大局）',
  `agps_winlose` int NULL DEFAULT 0 COMMENT '累积输赢',
  `agps_playset_xx` int NULL DEFAULT 0 COMMENT '累积游戏局数（大局）',
  `agps_winlose_xx` int NULL DEFAULT 0 COMMENT '累积输赢',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `agent_game_player_short_index1`(`agps_agentid` ASC, `agps_gameid` ASC, `agps_playerid` ASC, `agps_shortcode` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '玩家短号输赢表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_game_pond
-- ----------------------------
DROP TABLE IF EXISTS `agent_game_pond`;
CREATE TABLE `agent_game_pond`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `aggp_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理id',
  `aggp_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `aggp_pondid` int NOT NULL COMMENT '池子id',
  `aggp_value` int NULL DEFAULT 0 COMMENT '累计输赢',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `agent_game_pond_index`(`aggp_agentid` ASC, `aggp_gameid` ASC, `aggp_pondid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 66 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '系统累计输赢池子表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_game_room
-- ----------------------------
DROP TABLE IF EXISTS `agent_game_room`;
CREATE TABLE `agent_game_room`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `aggr_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理id',
  `aggr_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `aggr_minroomcode` int NOT NULL COMMENT '最小房间号 >=',
  `aggr_maxroomcode` int NOT NULL COMMENT '最大房间号 <=',
  `aggr_server` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '房间服务器地址，不需要\"http\"前缀',
  `aggr_port_tcp` int NULL DEFAULT NULL COMMENT '房间服务器tcp端口',
  `aggr_port_http` int NULL DEFAULT NULL COMMENT '房间服务器http端口',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `agent_game_room`(`aggr_agentid` ASC, `aggr_gameid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '房间服务器表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for agent_game_version
-- ----------------------------
DROP TABLE IF EXISTS `agent_game_version`;
CREATE TABLE `agent_game_version`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `aggv_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理id',
  `aggv_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `aggv_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道id',
  `aggv_version` int NOT NULL COMMENT 'app实际版本号',
  `aggv_type` int NOT NULL COMMENT '升级类型 0-整包升级(zip格式) 1-单个文件升级',
  `aggv_download` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '文件下载地址',
  `aggv_file` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '带文件名的存放路径，升级类型为0时此字段无意义',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `agent_game_version`(`aggv_agentid` ASC, `aggv_gameid` ASC, `aggv_channelid` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '游戏版本表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for ct_user_process_log
-- ----------------------------
DROP TABLE IF EXISTS `ct_user_process_log`;
CREATE TABLE `ct_user_process_log`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `uspl_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `uspl_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商id',
  `uspl_playerid` int NOT NULL COMMENT '玩家id',
  `uspl_unionid` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '玩家unionid',
  `uspl_opt` tinyint NOT NULL COMMENT '操作类型 1:新增玩家 2:绑定邀请码',
  `uspl_optdata` varchar(4000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '操作数据 1:玩家微信信息json 2:邀请码',
  `uspl_opttime` datetime NULL DEFAULT NULL COMMENT '生成的时间',
  `uspl_state` tinyint(1) NULL DEFAULT 0 COMMENT '代理后台处理状态 0:未处理 1:已处理',
  `uspl_statetime` datetime NULL DEFAULT NULL COMMENT '代理后台处理时间',
  PRIMARY KEY (`idx`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 168473 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '游戏的操作日志表-代理后台2.0接口表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for error
-- ----------------------------
DROP TABLE IF EXISTS `error`;
CREATE TABLE `error`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `erro_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `erro_playerid` int NOT NULL COMMENT '玩家id',
  `erro_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `erro_msg` varchar(10000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '错误信息',
  `erro_packet` varchar(10000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '收到的包',
  `erro_time` datetime NULL DEFAULT NULL COMMENT '时间',
  PRIMARY KEY (`idx`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 38845 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '错误日志表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for game
-- ----------------------------
DROP TABLE IF EXISTS `game`;
CREATE TABLE `game`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `game_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `game_name` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏名称',
  `game_minroomcode` int NULL DEFAULT 100000 COMMENT '最小房号',
  `game_maxroomcode` int NULL DEFAULT 999999 COMMENT '最大房号',
  `game_seatcount` int NOT NULL COMMENT '房间内的座位数量',
  `game_makewar` int NULL DEFAULT NULL COMMENT '达成开战条件的人数',
  `game_modename` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '游戏服务器模块名称',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `game_index`(`game_gameid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 52 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '游戏表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for game_buybill
-- ----------------------------
DROP TABLE IF EXISTS `game_buybill`;
CREATE TABLE `game_buybill`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `gabu_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `gabu_playerid` int NOT NULL COMMENT '玩家id',
  `gabu_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '渠道商id',
  `gabu_billcode` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '订单号',
  `gabu_productid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '产品id',
  `gabu_payid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '支付id',
  `gabu_amount` int NOT NULL COMMENT '产品中的房卡数量',
  `gabu_money` decimal(10, 2) NOT NULL COMMENT '产品中的所需金额',
  `gabu_createtime` datetime NOT NULL COMMENT '下单时间',
  `gabu_paystate` tinyint(1) NULL DEFAULT 0 COMMENT '支付状态 0-未支付 1-已支付',
  `gabu_paymoney` decimal(10, 2) NULL DEFAULT NULL COMMENT '实际支付金额',
  `gabu_paytime` datetime NULL DEFAULT NULL COMMENT '支付时间',
  `gabu_paytype` tinyint(1) NOT NULL COMMENT '支付方式 1-苹果 2-微信 3-支付宝',
  `gabu_transid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '支付流水号',
  `gabu_outtradeNo` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '商家订单号',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `game_buybill_index`(`gabu_agentid` ASC, `gabu_channelid` ASC, `gabu_billcode` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '玩家购卡记录表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for game_product
-- ----------------------------
DROP TABLE IF EXISTS `game_product`;
CREATE TABLE `game_product`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `gapr_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `gapr_productid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '产品id',
  `gapr_payid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '支付id',
  `gapr_name` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '产品名称',
  `gapr_amount` int NOT NULL COMMENT '房卡数量',
  `gapr_money` decimal(10, 2) NOT NULL COMMENT '所需金额',
  `gapr_memo` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '描述',
  `gapr_state` tinyint(1) NULL DEFAULT 0 COMMENT '状态 0-启用 1-禁用',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `game_product_index`(`gapr_agentid` ASC, `gapr_productid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 353 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '房卡产品表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for player
-- ----------------------------
DROP TABLE IF EXISTS `player`;
CREATE TABLE `player`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `play_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `play_playerid` int NOT NULL COMMENT '玩家id',
  `play_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_openid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信openid',
  `play_unionid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信unionid',
  `play_nickname` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '玩家昵称',
  `play_avatar` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '头像',
  `play_sex` tinyint(1) NULL DEFAULT NULL COMMENT '性别',
  `play_province` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '省',
  `play_city` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市',
  `play_roomcard` int NULL DEFAULT 8 COMMENT '房卡数量',
  `play_bean` int NULL DEFAULT 0 COMMENT '金币',
  `play_regtime` datetime NOT NULL COMMENT '注册时间',
  `play_lasttime` datetime NOT NULL COMMENT '最后登录时间',
  `play_logindate` int NULL DEFAULT 1 COMMENT '累积登录天数',
  `play_usecard` int NULL DEFAULT 0 COMMENT '累积使用房卡数量',
  `play_taskaward` int NULL DEFAULT 0 COMMENT '累积任务奖励房卡数量',
  `play_type` tinyint(1) NULL DEFAULT 0 COMMENT '用户类型 0:普通用户 1:vip开房不扣房卡',
  `play_score` int NULL DEFAULT 0,
  `play_a_country` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_province` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_city` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_citycode` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_district` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_street` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_address` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_longitude` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_latitude` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_invitecode` int NULL DEFAULT NULL,
  `play_inviteid` int NULL DEFAULT NULL,
  `play_state` tinyint(1) NULL DEFAULT 0,
  `play_advanced` tinyint NULL DEFAULT 0,
  `play_shortcode` int NULL DEFAULT NULL,
  `play_roomcodes` varchar(4000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_desone` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_destwo` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_whitelist` varchar(6000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_limit` int NULL DEFAULT NULL,
  `play_notice` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_bankpower` tinyint(1) NULL DEFAULT 1,
  `play_bank` int NULL DEFAULT 0,
  `play_bankpwd` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_tel` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_wechat` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_marketid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_phoneinfo` varchar(8000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_sign` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `player_index2`(`play_agentid` ASC, `play_unionid` ASC) USING BTREE,
  UNIQUE INDEX `player_index1`(`play_agentid` ASC, `play_playerid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 137785 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '玩家表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for player_copy1
-- ----------------------------
DROP TABLE IF EXISTS `player_copy1`;
CREATE TABLE `player_copy1`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `play_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `play_playerid` int NOT NULL COMMENT '玩家id',
  `play_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_openid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信openid',
  `play_unionid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信unionid',
  `play_nickname` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '玩家昵称',
  `play_avatar` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '头像',
  `play_sex` tinyint(1) NULL DEFAULT NULL COMMENT '性别',
  `play_province` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '省',
  `play_city` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市',
  `play_roomcard` int NULL DEFAULT 8 COMMENT '房卡数量',
  `play_bean` int NULL DEFAULT 0 COMMENT '金币',
  `play_regtime` datetime NOT NULL COMMENT '注册时间',
  `play_lasttime` datetime NOT NULL COMMENT '最后登录时间',
  `play_logindate` int NULL DEFAULT 1 COMMENT '累积登录天数',
  `play_usecard` int NULL DEFAULT 0 COMMENT '累积使用房卡数量',
  `play_taskaward` int NULL DEFAULT 0 COMMENT '累积任务奖励房卡数量',
  `play_type` tinyint(1) NULL DEFAULT 0 COMMENT '用户类型 0:普通用户 1:vip开房不扣房卡',
  `play_score` int NULL DEFAULT 0,
  `play_a_country` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_province` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_city` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_citycode` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_district` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_street` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_a_address` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_longitude` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_latitude` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_invitecode` int NULL DEFAULT NULL,
  `play_inviteid` int NULL DEFAULT NULL,
  `play_state` tinyint(1) NULL DEFAULT 0,
  `play_advanced` tinyint NULL DEFAULT 0,
  `play_shortcode` int NULL DEFAULT NULL,
  `play_roomcodes` varchar(4000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_desone` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_destwo` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_whitelist` varchar(6000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_limit` int NULL DEFAULT NULL,
  `play_notice` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_bankpower` tinyint(1) NULL DEFAULT 1,
  `play_bank` int NULL DEFAULT 0,
  `play_bankpwd` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_tel` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_wechat` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_marketid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_phoneinfo` varchar(8000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `play_sign` varchar(400) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `player_index2`(`play_agentid` ASC, `play_unionid` ASC) USING BTREE,
  UNIQUE INDEX `player_index1`(`play_agentid` ASC, `play_playerid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 137552 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '玩家表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for player_grade
-- ----------------------------
DROP TABLE IF EXISTS `player_grade`;
CREATE TABLE `player_grade`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `plgr_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `plgr_playerid` int NOT NULL COMMENT '玩家id',
  `plgr_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `plgr_roomcode` int NOT NULL COMMENT '房号',
  `plgr_ownerid` int NULL DEFAULT NULL COMMENT '房主id',
  `plgr_roomtype` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '房间类型',
  `plgr_createtime` datetime NOT NULL COMMENT '开房时间',
  `plgr_makewartime` datetime NOT NULL COMMENT '开战时间',
  `plgr_overtime` datetime NOT NULL COMMENT '结束时间',
  `plgr_roomcard` int NULL DEFAULT NULL COMMENT '这局结束时自己剩余房卡',
  `plgr_gameinfo1` varchar(10000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '一局游戏的完整数据 json格式',
  `plgr_gameinfo2` mediumtext CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '一局游戏的完整数据 json格式',
  `plgr_type` tinyint(1) NULL DEFAULT 0 COMMENT '类型 1-房主读取标识',
  `plgr_memo1` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '备用1',
  `plgr_memo2` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '备用2',
  `plgr_memo3` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '备用3',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `player_grade_index`(`plgr_agentid` ASC, `plgr_playerid` ASC, `plgr_gameid` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '玩家战绩表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for player_opinion
-- ----------------------------
DROP TABLE IF EXISTS `player_opinion`;
CREATE TABLE `player_opinion`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `plop_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `plop_playerid` int NOT NULL COMMENT '玩家id',
  `plop_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `plop_content` varchar(2000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '反馈意见',
  `plop_time` datetime NULL DEFAULT NULL COMMENT '反馈时间',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `player_opinion_index`(`plop_agentid` ASC, `plop_playerid` ASC, `plop_gameid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9560 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '玩家反馈意见表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for report_agent_day
-- ----------------------------
DROP TABLE IF EXISTS `report_agent_day`;
CREATE TABLE `report_agent_day`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `read_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `read_day` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '日期',
  `read_newplayer` int NULL DEFAULT 0 COMMENT '新增玩家数量',
  `read_newsalesman` int NULL DEFAULT 0 COMMENT '新增个人代理数量',
  `read_playeraward` int NULL DEFAULT 0 COMMENT '玩家得到的奖励房卡数量',
  `read_salesmoney` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '房卡销售金额',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `report_agent_day_index`(`read_agentid` ASC, `read_day` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9061 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '代理商的日报表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for report_game_day
-- ----------------------------
DROP TABLE IF EXISTS `report_game_day`;
CREATE TABLE `report_game_day`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `regd_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `regd_gameid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '游戏id',
  `regd_day` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '日期',
  `regd_newplayer` int NULL DEFAULT 0 COMMENT '新增玩家数量',
  `regd_useroomcard` int NULL DEFAULT 0 COMMENT '消耗房卡数量',
  `regd_asetcount` int NULL DEFAULT 0 COMMENT '玩家一共玩了多少游戏局（每人一大局算1）',
  `regd_maxplayer` int NULL DEFAULT 0 COMMENT '最大在线玩家数量',
  `regd_maxplayertime` datetime NULL DEFAULT NULL COMMENT '最大在线玩家数量出现的时间',
  `regd_maxroom` int NULL DEFAULT 0 COMMENT '最大开房数量',
  `regd_maxroomtime` datetime NULL DEFAULT NULL COMMENT '最大开房数量出现的时间',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `report_game_day_index`(`regd_agentid` ASC, `regd_gameid` ASC, `regd_day` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 43210 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '游戏的日报表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_ask_bill
-- ----------------------------
DROP TABLE IF EXISTS `sales_ask_bill`;
CREATE TABLE `sales_ask_bill`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `saab_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `saab_type` tinyint(1) NOT NULL COMMENT '索取类型 0-玩家索取房卡 1-个人代理索取房卡',
  `saab_askid` int NOT NULL COMMENT '发起者id（玩家id或个人代理id）',
  `saab_asknickname` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '发起者昵称',
  `saab_askavatar` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '发起者头像',
  `saab_salesid` int NOT NULL COMMENT '受理者id（个人代理id）',
  `saab_amount` int NOT NULL COMMENT '索要房卡数量',
  `saab_state` tinyint(1) NOT NULL COMMENT '状态 0-等待发卡 1-已确认发卡 2-发起者已取消 3-受理者已驳回',
  `saab_asktime` datetime NOT NULL COMMENT '发起索取的时间',
  `saab_dealtime` datetime NULL DEFAULT NULL COMMENT '确认发卡或取消或驳回的时间',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `sales_ask_bill_index`(`saab_agentid` ASC, `saab_type` ASC, `saab_askid` ASC, `saab_salesid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10659 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '索要房卡记录表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_award
-- ----------------------------
DROP TABLE IF EXISTS `sales_award`;
CREATE TABLE `sales_award`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `saaw_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `saaw_salesid` int NOT NULL COMMENT '个人代理id',
  `saaw_childid` int NOT NULL COMMENT '子个人代理id',
  `saaw_type` tinyint(1) NOT NULL COMMENT '奖励类型 0-发展子代理 1-子代理充值',
  `saaw_buybill` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '子个人代理购卡订单号',
  `saaw_award` int NOT NULL COMMENT '个人代理的奖励房卡数量',
  `saaw_state` tinyint(1) NULL DEFAULT 0 COMMENT '奖励领取状态 0-未领取 1-已领取',
  `saaw_createtime` datetime NULL DEFAULT NULL COMMENT '奖励的生成时间',
  `saaw_gettime` datetime NULL DEFAULT NULL COMMENT '奖励的领取时间',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `sales_award_index`(`saaw_agentid` ASC, `saaw_salesid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 343 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '子代理充值奖励表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_buybill
-- ----------------------------
DROP TABLE IF EXISTS `sales_buybill`;
CREATE TABLE `sales_buybill`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `sabu_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `sabu_openid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信openid',
  `sabu_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `sabu_billcode` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '订单号',
  `sabu_productid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '产品id',
  `sabu_amount` int NOT NULL COMMENT '产品中的房卡数量',
  `sabu_money` decimal(10, 2) NOT NULL COMMENT '产品中的所需金额',
  `sabu_createtime` datetime NOT NULL COMMENT '下单时间',
  `sabu_paystate` tinyint(1) NULL DEFAULT 0 COMMENT '支付状态 0-未支付 1-已支付',
  `sabu_paymoney` decimal(10, 2) NULL DEFAULT NULL COMMENT '实际支付金额',
  `sabu_paytime` datetime NULL DEFAULT NULL COMMENT '支付时间',
  `sabu_billtype` tinyint(1) NOT NULL COMMENT '订单类型 0-个人玩家购卡 1-个人代理购卡',
  `sabu_playerid` int NULL DEFAULT NULL COMMENT '充值者id',
  `sabu_playername` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '充值者昵称',
  `sabu_transid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '微信支付流水号',
  `sabu_outtradeNo` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '微信支付商家订单号',
  `sabu_appid` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `sabu_devkey` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `sabu_business_id` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `sabu_signkey` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '微信支付签名',
  `sabu_pushrate1` int NULL DEFAULT NULL,
  `sabu_pushmoney1` decimal(10, 2) NULL DEFAULT NULL,
  `sabu_pushrate2` int NULL DEFAULT NULL,
  `sabu_pushmoney2` decimal(10, 2) NULL DEFAULT NULL,
  `sabu_pushstate` tinyint(1) NULL DEFAULT 0,
  `sabu_pushsalesid1` int NULL DEFAULT NULL,
  `sabu_pushsalesid2` int NULL DEFAULT NULL,
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `sales_buybill_index2`(`sabu_agentid` ASC, `sabu_billcode` ASC) USING BTREE,
  INDEX `sales_buybill_index1`(`sabu_agentid` ASC, `sabu_openid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4511 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '用户购卡记录表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_notice
-- ----------------------------
DROP TABLE IF EXISTS `sales_notice`;
CREATE TABLE `sales_notice`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `sano_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `sano_noticeid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '公告id',
  `sano_title` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '标题',
  `sano_time` datetime NOT NULL COMMENT '发布时间',
  `sano_begintime` datetime NULL DEFAULT NULL COMMENT '开始显示时间',
  `sano_endtime` datetime NULL DEFAULT NULL COMMENT '结束显示时间',
  `sano_content` varchar(4000) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '内容',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `sales_notice_index`(`sano_agentid` ASC, `sano_noticeid` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '个人代理公告' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_product
-- ----------------------------
DROP TABLE IF EXISTS `sales_product`;
CREATE TABLE `sales_product`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `sapr_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `sapr_productid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '产品id',
  `sapr_type` tinyint(1) NOT NULL COMMENT '产品类型 0-针对个人玩家的产品 1-针对个人代理的产品',
  `sapr_name` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '产品名称',
  `sapr_amount` int NOT NULL COMMENT '房卡数量',
  `sapr_money` decimal(10, 2) NOT NULL COMMENT '所需金额',
  `sapr_memo` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '描述',
  `sapr_state` tinyint(1) NULL DEFAULT 0 COMMENT '状态 0-启用 1-禁用',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `sales_product_index`(`sapr_agentid` ASC, `sapr_productid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 323 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '房卡产品表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_sellbill
-- ----------------------------
DROP TABLE IF EXISTS `sales_sellbill`;
CREATE TABLE `sales_sellbill`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `sase_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `sase_openid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信openid',
  `sase_playerid` int NOT NULL COMMENT '玩家id',
  `sase_amount` int NOT NULL COMMENT '售卡数量',
  `sase_selltime` datetime NOT NULL COMMENT '售卡时间',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `sales_sellbill_index`(`sase_agentid` ASC, `sase_openid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 59239 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '个人代理售卡记录表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_sellbill_bean
-- ----------------------------
DROP TABLE IF EXISTS `sales_sellbill_bean`;
CREATE TABLE `sales_sellbill_bean`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `ssbe_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `ssbe_openid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信openid',
  `ssbe_playerid` int NOT NULL COMMENT '玩家id',
  `ssbe_amount` int NOT NULL COMMENT '充值数量',
  `ssbe_selltime` datetime NOT NULL COMMENT '充值时间',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `sales_sellbill_bean_index`(`ssbe_agentid` ASC, `ssbe_openid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '个人代理充星星记录表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_transferbill
-- ----------------------------
DROP TABLE IF EXISTS `sales_transferbill`;
CREATE TABLE `sales_transferbill`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `satr_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `satr_openid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信openid',
  `satr_salesid` int NOT NULL COMMENT '个人代理id',
  `satr_amount` int NOT NULL COMMENT '转卡数量',
  `satr_transfertime` datetime NOT NULL COMMENT '转卡时间',
  PRIMARY KEY (`idx`) USING BTREE,
  INDEX `sales_transferbill_index`(`satr_agentid` ASC, `satr_openid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3986 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '个人代理转卡记录表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for sales_user
-- ----------------------------
DROP TABLE IF EXISTS `sales_user`;
CREATE TABLE `sales_user`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `saus_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `saus_channelid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `saus_openid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '微信openid',
  `saus_unionid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '微信unionid',
  `saus_nickname` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '昵称',
  `saus_avatar` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '头像',
  `saus_sex` tinyint(1) NULL DEFAULT NULL COMMENT '性别',
  `saus_province` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '省',
  `saus_city` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '城市',
  `saus_firsttime` datetime NOT NULL COMMENT '第一次登登录时间',
  `saus_lasttime` datetime NOT NULL COMMENT '最后一次登录时间',
  `saus_salesman` tinyint(1) NULL DEFAULT 0 COMMENT '0:普通用户 1:个人代理',
  `saus_salesid` int NULL DEFAULT NULL COMMENT '个人代理id',
  `saus_level` int NULL DEFAULT 0,
  `saus_parentid` int NULL DEFAULT NULL COMMENT '上级个人代理id',
  `saus_salestype` tinyint(1) NULL DEFAULT 1,
  `saus_roomcard` int NULL DEFAULT 0 COMMENT '房卡数量',
  `saus_bean` int NULL DEFAULT 0,
  `saus_saletime` datetime NULL DEFAULT NULL COMMENT '成为个人代理时间',
  `saus_tel` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `saus_wechat` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `saus_invitecode` int NULL DEFAULT NULL,
  `saus_power` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `saus_pushrate1` int NULL DEFAULT 33,
  `saus_pushrate2` int NULL DEFAULT 8,
  `saus_pushmoney1` decimal(10, 2) NULL DEFAULT 0.00,
  `saus_pushmoney2` decimal(10, 2) NULL DEFAULT 0.00,
  `saus_status` int NULL DEFAULT 0 COMMENT '0、正常，1、封禁',
  `password` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '用户密码',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `salesman_index1`(`saus_agentid` ASC, `saus_openid` ASC) USING BTREE,
  UNIQUE INDEX `salesman_index2`(`saus_agentid` ASC, `saus_unionid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 55084 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '公众号用户表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for task
-- ----------------------------
DROP TABLE IF EXISTS `task`;
CREATE TABLE `task`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `task_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `task_taskid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '任务id',
  `task_type` tinyint(1) NOT NULL COMMENT '类型 0-针对玩家的每日任务 1-针对玩家的限时任务 2-针对玩家的不限时不限量任务(奖励=tapl_finish*task_award) 3-针对玩家的不限时不限量任务(奖励=tapl_finish)',
  `task_title` varchar(40) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '标题',
  `task_memo` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '描述',
  `task_total` int NOT NULL COMMENT '任务量',
  `task_award` int NOT NULL COMMENT '完成任务的奖励房卡数量',
  `task_begintime` datetime NULL DEFAULT NULL COMMENT '限时任务的开始时间',
  `task_endtime` datetime NULL DEFAULT NULL COMMENT '限时任务的截止时间',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `task_index`(`task_agentid` ASC, `task_taskid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 294 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '任务表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for task_player
-- ----------------------------
DROP TABLE IF EXISTS `task_player`;
CREATE TABLE `task_player`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `tapl_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '代理商id',
  `tapl_playerid` int NOT NULL COMMENT '玩家id',
  `tapl_taskid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '任务id',
  `tapl_finish` int NULL DEFAULT 0 COMMENT '任务完成量',
  `tapl_state` tinyint(1) NULL DEFAULT 0 COMMENT '任务状态 0-待完成 1-已完成 2-奖励已领取',
  `tapl_createtime` datetime NOT NULL COMMENT '任务领取时间',
  `tapl_finishtime` datetime NULL DEFAULT NULL COMMENT '任务完成时间',
  `tapl_awardtime` datetime NULL DEFAULT NULL COMMENT '奖励领取时间',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `task_player_index`(`tapl_agentid` ASC, `tapl_playerid` ASC, `tapl_taskid` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2218964 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '玩家任务完成表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Table structure for test
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test`  (
  `player_id` int NULL DEFAULT NULL
) ENGINE = InnoDB AUTO_INCREMENT = 1464 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for test2
-- ----------------------------
DROP TABLE IF EXISTS `test2`;
CREATE TABLE `test2`  (
  `player_id` int NULL DEFAULT NULL
) ENGINE = InnoDB AUTO_INCREMENT = 5556 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for topup_card
-- ----------------------------
DROP TABLE IF EXISTS `topup_card`;
CREATE TABLE `topup_card`  (
  `idx` int NOT NULL AUTO_INCREMENT,
  `toca_cardno` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '卡号 32位随机字符 + 1位卡类型 + 充值数量',
  `toca_state` tinyint(1) NULL DEFAULT 0 COMMENT '0-未使用 1-已使用',
  `toca_usetime` datetime NULL DEFAULT NULL COMMENT '使用时间',
  `toca_agentid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '使用的代理id',
  `toca_playerid` int NULL DEFAULT NULL COMMENT '使用的玩家id',
  PRIMARY KEY (`idx`) USING BTREE,
  UNIQUE INDEX `topup_card_index`(`toca_cardno` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 184 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '充值卡表' ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Procedure structure for cp_agent_login
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_agent_login`;
delimiter ;;
CREATE PROCEDURE `cp_agent_login`(IN `user` varchar(100) charset utf8 collate utf8_general_ci ,IN `pwd` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '运营商登录'
label_cp: begin
  declare result       tinyint(1);    -- 0:成功  >0:失败
  declare error        varchar(100);  -- 失败描述
  declare agentid      varchar(32);   -- 代理商id
  declare agentname    varchar(100);  -- 代理商名称   
  declare paymenttotal decimal(10,2); -- 收益总流水
  declare sharingrate  int(11);       -- 分成比例
  declare profittotal  decimal(10,2); -- 收益总金额
  declare playercount  int(11);       -- 玩家总数
  declare newplayer    int(11);       -- 当月新增玩家数量
  declare salecount	   int(11);       -- 个人代理总数
  declare newsale	     int(11);       -- 当月新增个人代理数量

  set result = 0;
  
  -- 总流水、分成比例、总收益
  select agen_agentid, agen_name, agen_selftotal, agen_sharingrate, cast(agen_selftotal * agen_sharingrate / 100 as decimal(10,2))
  into agentid, agentname, paymenttotal, sharingrate, profittotal 
  from agent
  where agen_user = user and agen_pwd = [REDACTED]

  if isnull(agentid) then
    set result = 1;
    set error = '账号或密码错误';
    select result, error;
    leave label_cp;
  end if;
  
  -- 玩家总人数统计
  select count(1) into playercount 
  from player 
  where play_agentid = agentid;

  -- 当月新增玩家人数
  select count(1) into newplayer 
  from player 
  where play_agentid = agentid 
    and play_regtime >= date_add(curdate(), interval - day(curdate()) + 1 day);  
    
  -- 统计个人代理总数
  select count(1) into salecount 
  from sales_user 
  where saus_agentid = agentid
    and saus_salesman = 1; 

  -- 统计当月新增个人代理数量
  select count(1) into newsale
  from sales_user 
  where saus_agentid = agentid 
    and saus_salesman = 1
    and saus_saletime >= date_add(curdate(), interval - day(curdate()) + 1 day);
    
  select result, error, agentid, agentname, paymenttotal, sharingrate, profittotal, playercount, newplayer, salecount, newsale;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_agent_player_game
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_agent_player_game`;
delimiter ;;
CREATE PROCEDURE `cp_agent_player_game`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '按游戏统计玩家数量和房卡消耗数量'
begin
  select agpl_gameid as gameid, game_name as gamename, count(1) as playercount, sum(agpl_usecard) as useroomcard
  from agent_game_player
  inner join game on game_gameid = agpl_gameid
  where agpl_agentid = agentid
  group by gameid, gamename;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_agent_player_max
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_agent_player_max`;
delimiter ;;
CREATE PROCEDURE `cp_agent_player_max`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '按月度统计同时在线玩家数量峰值和房间峰值'
begin
  -- 最近12个月按月度统计同时在线玩家数量峰值和房间峰值
  select date_format(aggo_datetime, "%Y-%m") as month, max(aggo_onlineplayer) as maxplayer, max(aggo_onlineroom) as maxroom  
  from agent_game_online
  where aggo_agentid = agentid
  group by month
  order by month desc limit 12;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_agent_player_month
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_agent_player_month`;
delimiter ;;
CREATE PROCEDURE `cp_agent_player_month`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '按月度统计新增玩家数量'
begin
  -- 最近12个月按月度统计新增玩家数量
  select date_format(play_regtime, "%Y-%m") as month, count(1) as newplayer 
  from player 
  where play_agentid = agentid 
  group by month
  order by month desc limit 12;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_agent_profit_month
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_agent_profit_month`;
delimiter ;;
CREATE PROCEDURE `cp_agent_profit_month`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '按月度统计流水'
begin
  -- 最近12个月按月度统计收益
  select date_format(sabu_paytime, "%Y-%m" ) as month, sum(sabu_paymoney) as money 
  from sales_buybill
  where sabu_agentid = agentid
    and sabu_paystate = 1
  group by month
  order by month desc limit 12;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_agent_profit_product
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_agent_profit_product`;
delimiter ;;
CREATE PROCEDURE `cp_agent_profit_product`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '按产品统计流水'
begin
  select sales_product.idx as idx, sabu_productid as productid,
         concat(sapr_money, '元', sapr_amount, '张') as productname,
         sum(sabu_paymoney) as money, count(1) as times
  from sales_buybill
  inner join sales_product on sapr_agentid = sabu_agentid
                        and sapr_productid = sabu_productid 
  where sabu_agentid = agentid
    and sabu_paystate = 1
  group by idx, productid, productname
  order by idx;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_agent_sale_month
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_agent_sale_month`;
delimiter ;;
CREATE PROCEDURE `cp_agent_sale_month`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '按月度统计新增个人代理数量'
begin
  -- 最近12个月按月度统计新增个人代理数量
  select date_format(saus_saletime, "%Y-%m") as month, count(1) as newsale 
  from sales_user 
  where saus_agentid = agentid 
    and saus_salesman = 1
    and saus_saletime is not null
  group by month
  order by month desc limit 12;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_agent_updatepwd
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_agent_updatepwd`;
delimiter ;;
CREATE PROCEDURE `cp_agent_updatepwd`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `oldpwd` varchar(100) charset utf8 collate utf8_general_ci ,IN `newpwd` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '修改运营商登录密码'
label_cp: begin
  declare result       tinyint(1);    -- 0:成功  >0:失败
  declare error        varchar(100);  -- 失败描述

  set result = 0;

  if not exists(select 1 from agent where agen_agentid = agentid and agen_pwd = [REDACTED] then
    set result = 1;
    set error = '原密码不正确';
    select result, error;
    leave label_cp;
  end if;
  
  update agent set agen_pwd = [REDACTED] where agen_agentid = agentid;
  
  select result, error; 
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_bind_player_wechat
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_bind_player_wechat`;
delimiter ;;
CREATE PROCEDURE `cp_bind_player_wechat`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,
IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,
IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,
IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,
IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,
IN `nickname` varchar(100) charset utf8 collate utf8_general_ci ,
IN `avatar` varchar(200) charset utf8 collate utf8_general_ci ,
IN `sex` int(11) ,
IN `province` varchar(100) charset utf8 collate utf8_general_ci ,
IN `city` varchar(100) charset utf8 collate utf8_general_ci ,
IN `marketid` varchar(100) charset utf8 collate utf8_general_ci ,
IN `telphone` varchar(20) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '绑定手机号'
begin
    declare playerid int(8);
    
    select play_playerid into playerid from player where play_agentid = agentid and play_unionid = unionid limit 1;
    
    if not isnull(playerid) then
        update player set play_tel = '' where play_agentid = agentid and play_tel = telphone and play_playerid <> playerid;
        update player set play_nickname = nickname, play_avatar = avatar, play_tel = telphone
        where play_agentid = agentid and play_playerid = playerid;
        select 1 as result, '更新成功' as msg;
    else
        if exists(select 1 from player where play_agentid = agentid and play_tel = telphone) then
            select -1 as result, '手机号已存在' as msg;
        else
            call cp_game_player_login_1121(agentid, channelid, gameid, openid, unionid, nickname, avatar, sex, province, city, marketid, telphone);
        end if;
    end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_1_agent
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_1_agent`;
delimiter ;;
CREATE PROCEDURE `cp_check_1_agent`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `agentname` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '检验代理商是否存在'
begin
  set result = 0;
  set error  = '';
  set agentname = null;                       
  
  select agen_name into agentname from agent where agen_agentid = agentid limit 1;
  if isnull(agentname) then    
    set result = 1;                            
    set error  = '运营商不存在';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_2_player
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_2_player`;
delimiter ;;
CREATE PROCEDURE `cp_check_2_player`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `playername` varchar(100) charset utf8 collate utf8_general_ci ,OUT `roomcard` int(11))
  SQL SECURITY INVOKER
  COMMENT '检验代理商是否存在'
begin
  set result = 0;
  set error  = '';
  set playername = null;
  set roomcard = 0;
  
  select play_nickname, play_roomcard into playername, roomcard 
  from player where play_agentid = agentid and play_playerid = playerid limit 1;

  if isnull(playername) then
    set result = 2;
    set error  = '玩家不存在';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_3_game
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_3_game`;
delimiter ;;
CREATE PROCEDURE `cp_check_3_game`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `gamename` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '检验代理商是否存在'
begin
  set result = 0;
  set error  = '';
  set gamename = null;
  
  select game_name into gamename from game where game_agentid = agentid and game_gameid = gameid limit 1;
  if isnull(gamename) then
    set result = 3;
    set error  = '游戏不存在';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_4_salesuser
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_4_salesuser`;
delimiter ;;
CREATE PROCEDURE `cp_check_4_salesuser`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `username` varchar(100) charset utf8 collate utf8_general_ci ,OUT `salesman` tinyint(1))
  SQL SECURITY INVOKER
  COMMENT '微信公众号用户是否存在'
begin
  set result = 0;
  set error  = '';
  set username = null;
  set salesman = null;
  
  select saus_nickname, saus_salesman into username, salesman 
  from sales_user where saus_agentid = agentid and saus_openid = openid limit 1;
  
  if isnull(username) then
    set result = 4;
    set error  = '用户不存在';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_5_product
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_5_product`;
delimiter ;;
CREATE PROCEDURE `cp_check_5_product`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `productid` varchar(32) charset utf8 collate utf8_general_ci ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `productname` varchar(100) charset utf8 collate utf8_general_ci ,OUT `productamount` int(11) ,OUT `productmoney` decimal(10,2))
  SQL SECURITY INVOKER
  COMMENT '检验代理商是否存在'
begin
  set result = 0;
  set error  = '';
  set productname   = null;
  set productamount = 0;
  set productmoney  = 0;
  
  select sapr_name, sapr_amount, sapr_money into productname, productamount, productmoney
  from sales_product where sapr_agentid = agentid and sapr_productid = productid limit 1;
  
  if isnull(productname) then
    set result = 5;
    set error  = '房卡产品不存在';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_6_buybill
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_6_buybill`;
delimiter ;;
CREATE PROCEDURE `cp_check_6_buybill`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `billcode` varchar(50) charset utf8 collate utf8_general_ci ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `billtype` tinyint(1) ,OUT `playerid` int(8) ,OUT `playername` varchar(100) charset utf8 collate utf8_general_ci ,OUT `amount` int(11) ,OUT `money` decimal(10,2) ,OUT `paystate` tinyint(1))
  SQL SECURITY INVOKER
  COMMENT '检验购卡订单是否存在'
begin
  set result = 0;
  set error  = '';
  set billtype = null;
  set playerid = null;
  set playername = null;
  set money = null;
  set amount = null;
  
  select sabu_billtype, sabu_playerid, sabu_playername, sabu_amount, sabu_money, sabu_paystate 
  into billtype, playerid, playername, amount, money, paystate
  from sales_buybill where sabu_agentid = agentid and sabu_billcode = billcode limit 1;
  
  if isnull(billtype) then
    set result = 6;
    set error  = '订单不存在';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_7_salesman
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_7_salesman`;
delimiter ;;
CREATE PROCEDURE `cp_check_7_salesman`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `roomcard` int(11))
  SQL SECURITY INVOKER
  COMMENT '微信公众号用户是否存在'
begin
  set result = 0;
  set error  = '';
  set roomcard = null;
  
  select saus_roomcard into roomcard 
  from sales_user 
  where saus_agentid = agentid and saus_openid = openid and saus_salesman = 1 limit 1;
  
  if isnull(roomcard) then
    set result = 7;
    set error  = '不是个人代理';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_8_task
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_8_task`;
delimiter ;;
CREATE PROCEDURE `cp_check_8_task`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `taskid` varchar(100) charset utf8 collate utf8_general_ci ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `tasktype` tinyint(1) ,OUT `total` int(8) ,OUT `award` int(8))
  SQL SECURITY INVOKER
  COMMENT '任务是否存在和有效'
begin
  set result = 0;
  set error  = '';
  set award = null;
  
  select task_type, task_total, task_award into tasktype, total, award 
  from task 
  where task_agentid = agentid 
     and task_taskid = taskid
     and ((task_type = 0)
       or ((task_type = 1) and
           (task_begintime is null or now() >= task_begintime) and
           (task_endtime   is null or now() <= task_endtime)
          )
       or (task_type = 2)
       or (task_type = 3)
         );
  
  if isnull(award) then
    set result = 8;
    set error  = '任务不存在或已过期';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_check_9_salesman
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_check_9_salesman`;
delimiter ;;
CREATE PROCEDURE `cp_check_9_salesman`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `salesid` int(8) ,OUT `result` tinyint(1) ,OUT `error` varchar(100) charset utf8 collate utf8_general_ci ,OUT `salesname` varchar(100) charset utf8 collate utf8_general_ci ,OUT `roomcard` int(11))
  SQL SECURITY INVOKER
  COMMENT '个人代理是否存在'
begin
  set result = 0;
  set error  = '';
  set salesname = null;
  set roomcard = null;
  
  select saus_nickname, saus_roomcard into salesname, roomcard 
  from sales_user 
  where saus_agentid = agentid and saus_salesid = salesid and saus_salesman = 1 limit 1;
  
  if isnull(roomcard) then
    set result = 9;
    set error  = '代理id不存在';  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_add_bean
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_add_bean`;
delimiter ;;
CREATE PROCEDURE `cp_game_add_bean`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `amount` int(8))
  SQL SECURITY INVOKER
  COMMENT '加豆豆(第三方接口)'
label_cp: begin
  declare result tinyint(1);   -- 0:成功  >0:失败 
  declare error  varchar(100); -- 失败描述 
  declare bean   int(8);

  set result = 0;
  if not exists(select 1 from agent where agen_agentid = agentid) then 
    set result = 1;
    set error  = 'agentid不存在';
    select result, error;
    leave label_cp;
  end if; 
  
  set bean = null;
  select play_bean into bean from player 
  where play_agentid = agentid and play_playerid = playerid limit 1;
  if isnull(bean) then 
    set result = 1;
    set error  = 'player不存在';
    select result, error;
    leave label_cp;  
  end if; 
     
  update player set play_bean = play_bean + amount
  where play_agentid = agentid 
    and play_playerid = playerid limit 1;   
      
  select result, agentid, playerid, amount, bean + amount as bean;      
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_binding_invitecode
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_binding_invitecode`;
delimiter ;;
CREATE PROCEDURE `cp_game_binding_invitecode`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `invitecode` int(8) ,IN `invitecodetype` tinyint(1))
  SQL SECURITY INVOKER
  COMMENT '玩家登录游戏记录地理位置'
label_cp: begin
  declare result          tinyint(1);   -- 0:成功  >0:失败 
  declare error           varchar(100); -- 失败描述 
  declare agentname       varchar(100); -- 代理商名称
  declare playerchannelid varchar(32);  -- 渠道商id
  declare playerunionid  varchar(50);  -- 玩家的unionid 
  declare playername     varchar(100); -- 玩家昵称
  declare playerroomcard int(11);      -- 玩家房卡数量
  declare salesid        int(8);       -- 邀请码对应的代理id
  declare _invitecode    int(8);       -- 已经绑定的邀请码  
  
  declare _len  int(8);     -- 要绑定的邀请码的长度
  declare _type tinyint(1); -- 要绑定的邀请码的类型
  declare _unionid varchar(50);
  declare _code int(8);     -- 要绑定的个人代理id
  declare _id   int(8);     -- 要绑定的玩家id
  
  set result = 0;
    
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
   
  -- 检验playerid
  call cp_check_2_player(agentid, playerid, result, error, playername, playerroomcard);
  if result > 0 then
    select result, error;
    leave label_cp;
  end if;
  
  -- 确定要绑定的邀请码是个人代理id还是玩家id
  set _len = length(invitecode);
  if _len < 8 then
    set _type = invitecodetype; 
  else 
    set _type = 0;
  end if;
  
  -- 检验邀请码
  if _type = 0 then
    -- 绑定的邀请码是个人代理id 
    select saus_unionid into _unionid 
    from sales_user
    where saus_agentid = agentid and saus_salesid = invitecode and saus_salesman = 1 limit 1;
    
    if isnull(_unionid) then
      set result = 10;
      set error = '邀请码不存在';
      select result, error;
      leave label_cp;
    end if; 
    
    set _code = invitecode;
    
    select play_playerid into _id
    from player
    where play_agentid = agentid
      and play_unionid = _unionid limit 1;
  else 
    -- 绑定的邀请码是玩家id 
    select play_unionid into _unionid 
    from player 
    where play_agentid = agentid and play_playerid = invitecode limit 1;
    
    if isnull(_unionid) then
      set result = 10;
      set error = '邀请码不存在';
      select result, error;
      leave label_cp;
    end if;  
    
    set _id = invitecode;
    
    select saus_salesid into _code
    from sales_user
    where saus_agentid = agentid
      and saus_unionid = _unionid limit 1;    
  end if; 
  
  -- 检查是否已经绑定了邀请码
  select play_invitecode into _invitecode 
  from player 
  where play_agentid = agentid
    and play_playerid = playerid limit 1;
    
  if isnull(_invitecode) then
    update player set play_invitecode = _code, play_inviteid = _id
    where play_agentid = agentid
      and play_playerid = playerid limit 1;    
     
    select play_channelid, play_unionid into playerchannelid, playerunionid
    from player
    where play_agentid = agentid
      and play_playerid = playerid limit 1; 

    insert into ct_user_process_log(uspl_agentid, uspl_channelid, uspl_playerid, uspl_unionid, uspl_opt, uspl_optdata, uspl_opttime)
    values(agentid, playerchannelid, playerid, playerunionid, 2, _code, now()); 
      
    -- 完成绑定邀请码任务
    call cp_game_task_finish(agentid, playerid, 'UEFsfbv29YnlacKLo0mjomK48Bv82hGv', 1, 0);   
   
    set result = 0;
    set error  = '绑定邀请码成功';  
  else
    set result = 21;
    set error  = '已经绑定过邀请码，不能再次绑定';
  end if;
  
  select result, error, _code, _id;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_change_bankstar
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_change_bankstar`;
delimiter ;;
CREATE PROCEDURE `cp_game_change_bankstar`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `bankpwd` varchar(10) charset utf8 collate utf8_general_ci ,IN `domode` tinyint(1) ,IN `amount` int(11))
  SQL SECURITY INVOKER
  COMMENT '存入或取出银行金币'
label_cp: begin
  declare result tinyint(1);   -- 0:成功  >0:失败 
  declare error  varchar(100); -- 失败描述
  declare _playerid   int(8);
  declare _playerbean int(11);
  declare _playerbank int(11);
  declare _playerpwd  varchar(10);  
  set result = 0;
  
  if amount < 0 then
    set result = 1;
    set error = '数量不能为负数';
    select result, error;
    leave label_cp;
  end if; 
    
  -- 检验agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error = '运营商id不存在';
    select result, error;
    leave label_cp;
  end if; 
  
  select play_playerid, play_bean, play_bank, play_bankpwd
  into _playerid, _playerbean, _playerbank, _playerpwd
  from player 
  where play_agentid = agentid 
    and play_playerid = playerid;
  
  if isnull(_playerid) then
    set result = 1;
    set error = '玩家id不存在';
    select result, error;
    leave label_cp;  
  end if;

  if bankpwd <> _playerpwd then
    set result = 1;
    set error = '密码不正确';
    select result, error;
    leave label_cp;  
  end if;

  if domode = 0 then
    if amount > _playerbean then
      set result = 1;
      set error = '数量不够';
      select result, error;
      leave label_cp;   
    else
      update player set play_bean = ifnull(play_bean, 0) - amount, 
                        play_bank = ifnull(play_bank, 0) + amount
      where play_agentid = agentid and play_playerid = playerid limit 1;      
    end if;   
  else 
    if amount > _playerbank then
      set result = 1;
      set error = '数量不够';
      select result, error;
      leave label_cp;
    else
      update player set play_bean = ifnull(play_bean, 0) + amount, 
                        play_bank = ifnull(play_bank, 0) - amount
      where play_agentid = agentid and play_playerid = playerid limit 1;         
    end if;     
  end if;  

  -- 返回执行结果 
  select result, error, play_bean, play_bank
  from player where play_agentid = agentid and play_playerid = playerid limit 1;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_deduct_roomcard
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_deduct_roomcard`;
delimiter ;;
CREATE PROCEDURE `cp_game_deduct_roomcard`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `deduct` int(8) ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '第一小局结算后扣除房主开房所需的房卡'
begin
  declare error int default 0;  
  
  -- 如果出现异常也继续执行  
  declare continue handler for sqlexception set error = 1;   
  
  -- 启动事务  
  start transaction; 
   
  if deduct > 0 then
    update player set play_roomcard = play_roomcard - deduct, 
                      play_usecard = play_usecard + deduct
    where play_agentid = agentid 
      and play_playerid = playerid limit 1;
      
    update agent_game_player set agpl_usecard = agpl_usecard + deduct
    where agpl_agentid = agentid
      and agpl_gameid = gameid
      and agpl_playerid = playerid limit 1;
      
    -- 按日期统计房卡消耗数量
    call cp_report_game_day(agentid, gameid, now(), 1, deduct, null);
  end if;  

  -- 运行没有异常，提交事务
  if error = 1 then  
    rollback;  
  else
    commit;
  end if;
  
  select playerid, play_roomcard as roomcard, deduct
  from player
  where play_agentid = agentid and play_playerid = playerid limit 1;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_del_timeout_task
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_del_timeout_task`;
delimiter ;;
CREATE PROCEDURE `cp_game_del_timeout_task`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '删除过期任务'
begin
  if isnull(agentid) then
    delete task_player 
    from task_player, task 
    where task_agentid = tapl_agentid 
      and task_taskid = tapl_taskid
      -- 每日任务
      and ((task_type = 0 and datediff(tapl_createtime, curdate()) <> 0)
      -- 限时任务
        or (task_type = 1 and ((task_begintime is not null and tapl_createtime < task_begintime) 
                            or (task_endtime   is not null and tapl_createtime > task_endtime)
                              )
           )
         );  
  else
    -- 删除所有人的过期任务
    delete task_player 
    from task_player, task 
    where tapl_agentid = agentid
      and task_agentid = agentid
      and task_taskid = tapl_taskid
      -- 每日任务
      and ((task_type = 0 and datediff(tapl_createtime, curdate()) <> 0)
      -- 限时任务
        or (task_type = 1 and ((task_begintime is not null and tapl_createtime < task_begintime) 
                            or (task_endtime   is not null and tapl_createtime > task_endtime)
                              )
           )
         );     
  end if; 
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_get_player_invitecode
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_get_player_invitecode`;
delimiter ;;
CREATE PROCEDURE `cp_game_get_player_invitecode`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取玩家绑定的邀请码'
begin  
  declare invitecode int(8);
  
  select play_invitecode into invitecode
  from player 
  where play_agentid = agentid 
    and play_playerid = playerid limit 1;
  
  if isnull(invitecode) then
    call cp_game_get_player_invitecode_insales(agentid, playerid, unionid, invitecode); 
  end if;
  
  select invitecode;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_get_player_invitecode_insales
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_get_player_invitecode_insales`;
delimiter ;;
CREATE PROCEDURE `cp_game_get_player_invitecode_insales`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,OUT `invitecode` int(8))
  SQL SECURITY INVOKER
  COMMENT '获取玩家绑定的邀请码'
begin   
  -- 看是否自动绑定过邀请码
  if isnull(invitecode) then
    select saus_invitecode into invitecode
    from sales_user
    where saus_agentid = agentid
      and saus_unionid = unionid;
      
    if not isnull(invitecode) then
       update player set play_invitecode = invitecode
       where play_agentid = agentid
         and play_playerid = playerid;
                  
       -- 完成绑定邀请码任务
      call cp_game_task_finish(agentid, playerid, 'UEFsfbv29YnlacKLo0mjomK48Bv82hGv', 1, 0);    
    end if; 
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_get_player_taskstate
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_get_player_taskstate`;
delimiter ;;
CREATE PROCEDURE `cp_game_get_player_taskstate`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,OUT `taskstate` tinyint(1))
  SQL SECURITY INVOKER
  COMMENT '删除过期任务，获取玩家当天的任务状态'
begin
  -- 获取玩家的任务状态
  set taskstate = 0; 
  
  if exists(select 1 from task_player
            where tapl_agentid = agentid 
              and tapl_playerid = playerid
              and tapl_state = 1
            ) then
    -- 有任务已完成可领取奖励
    set taskstate = 2;  
  elseif exists(select 1 from task
                where task_agentid = agentid
                  and ((task_type = 0) 
                    or (task_type = 1 and 
                        (task_begintime is null or now() >= task_begintime) and
                        (task_endtime   is null or now() <= task_endtime)
                       )
                      )
                  and not exists(select 1 from task_player
                                 where tapl_agentid = agentid 
                                   and tapl_playerid = playerid
                                   and tapl_taskid = task_taskid)
               ) then               
    -- 有任务未完成
    set taskstate = 1;
  elseif exists(select 1 from task_player, task
                where tapl_agentid = agentid 
                  and tapl_playerid = playerid
                  and tapl_state = 0
                  and task_agentid = agentid
                  and task_taskid = tapl_taskid
                  and task_type in (0, 1)
            ) then  
    -- 有任务未完成
    set taskstate = 1;
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_grade_robot
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_grade_robot`;
delimiter ;;
CREATE PROCEDURE `cp_game_grade_robot`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `grade` int(11) ,IN `beanmult` int(11))
  SQL SECURITY INVOKER
  COMMENT '累计机器人的星星输赢'
begin
  if exists(select 1 from agent_game_player 
            where agpl_agentid = agentid
              and agpl_gameid = gameid
              and agpl_playerid = 999999) then
    update agent_game_player 
    set agpl_playset_xx = agpl_playset_xx + 1,
        agpl_winlose_xx = agpl_winlose_xx + if(beanmult = 0, 0, grade div beanmult),
        agpl_winlose_x2 = agpl_winlose_x2 + grade,
        agpl_lasttime = now()
    where agpl_agentid = agentid
      and agpl_gameid = gameid
      and agpl_playerid = 999999 limit 1;
  else
    insert into agent_game_player(agpl_agentid, agpl_gameid, agpl_playerid, agpl_openid,  
     agpl_firsttime, agpl_lasttime, agpl_playset_xx, agpl_winlose_xx, agpl_winlose_x2)
    values(agentid, gameid, 999999, 'robot', now(), now(), 1, grade, if(beanmult = 0, 0, grade div beanmult));    
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_grade_save
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_grade_save`;
delimiter ;;
CREATE PROCEDURE `cp_game_grade_save`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerids` varchar(800) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `roomcode` int(8) ,IN `roomtype` varchar(200) charset utf8 collate utf8_general_ci ,IN `createtime` datetime ,IN `makewartime` datetime ,IN `overtime` datetime ,IN `gameinfo1` varchar(10000) charset utf8 collate utf8_general_ci ,IN `gameinfo2` mediumtext charset utf8 collate utf8_general_ci ,IN `ownerid` int(8) ,IN `grades` varchar(800) charset utf8 collate utf8_general_ci ,IN `roommode` tinyint(1) ,IN `beanmult` int(4) ,IN `shortcode` int(8) ,IN `isrobots` varchar(800) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '保存战绩'
begin
  declare ary_playerid varchar(800);
  declare ary_grade    varchar(800);
  declare ary_isrobot  varchar(800);
  declare pos_playerid int(10);
  declare pos_grade    int(10);
  declare pos_isrobot  int(10);   
  declare playerid     varchar(8);
  declare grade        varchar(8);
  declare isrobot      varchar(8);
  
  -- 如果出现异常，自动退出并rollback
  declare exit handler for sqlexception ROLLBACK;  
  
  -- 启动事务  
  start transaction;  
  
  set ary_playerid = playerids;
  set ary_grade    = grades;
  set ary_isrobot  = isrobots; 
   
  while ary_playerid <> '' do
    set pos_playerid = instr(ary_playerid, ',');
    set pos_grade    = instr(ary_grade, ',');
    set pos_isrobot  = instr(ary_isrobot, ',');
    if pos_playerid = 0 then
       set playerid = ary_playerid;
       set grade    = ary_grade;
       set isrobot  = ary_isrobot;
       set ary_playerid = '';
       set ary_grade    = '';
       set ary_isrobot  = '';
    else
      set playerid = left(ary_playerid, pos_playerid - 1);
      set grade    = left(ary_grade,    pos_grade    - 1); 
      set isrobot  = left(ary_isrobot,  pos_isrobot  - 1);     
      set ary_playerid = right(ary_playerid, length(ary_playerid) - pos_playerid);
      set ary_grade    = right(ary_grade,    length(ary_grade)    - pos_grade);
      set ary_isrobot  = right(ary_isrobot,  length(ary_isrobot)  - pos_isrobot);
    end if;
           
    -- 累计游戏局数（大局）
    if roommode = 0 then
      -- 非星星场
      if isrobot = '0' then
        update agent_game_player 
        set agpl_playset = agpl_playset + 1,
            agpl_winlose = agpl_winlose + grade
        where agpl_agentid = agentid
          and agpl_gameid = gameid
          and agpl_playerid = playerid limit 1;
      end if;
    else 
      -- 星星场
      if isrobot = '0' then
        update agent_game_player 
        set agpl_playset_xx = agpl_playset_xx + 1,
            agpl_winlose_xx = agpl_winlose_xx + (grade div beanmult),
            agpl_winlose_x2 = agpl_winlose_x2 + grade
        where agpl_agentid = agentid
          and agpl_gameid = gameid
          and agpl_playerid = playerid limit 1; 
      else
        call cp_game_grade_robot(agentid, gameid, grade, beanmult);
      end if; 
    end if;
         
    -- 统计房主的邀请新人奖励
    if ownerid <> playerid then
      if exists(select 1 from agent_game_player 
                where agpl_agentid = agentid
                  and agpl_gameid = gameid
                  and agpl_playerid = playerid
                  and agpl_playset = 1) then
        call cp_game_task_finish(agentid, ownerid, 'ZVlpZweovbeQ68g8xdjcxaXHfbfIvvu7', 1, 0); 
      end if;     
      
      -- 累加积分（玩一局积分加1）
      /*
      update player set play_score = play_score + 1 
      where play_agentid = agentid
        and play_playerid = playerid;    
    else
      -- 累加积分（开房积分加2）
      update player set play_score = play_score + 3 
      where play_agentid = agentid
        and play_playerid = playerid;
      */
    end if;
  end while;
  
  -- 按日期统计玩家一共玩了多少游戏局（大局）
  call cp_report_game_day(agentid, gameid, now(), 2, 1, null);
  
  -- 运行没有异常，提交事务  
  commit; 
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_login_location
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_login_location`;
delimiter ;;
CREATE PROCEDURE `cp_game_login_location`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `country` varchar(100) charset utf8 collate utf8_general_ci ,IN `province` varchar(100) charset utf8 collate utf8_general_ci ,IN `city` varchar(100) charset utf8 collate utf8_general_ci ,IN `citycode` varchar(20) charset utf8 collate utf8_general_ci ,IN `district` varchar(100) charset utf8 collate utf8_general_ci ,IN `street` varchar(100) charset utf8 collate utf8_general_ci ,IN `address` varchar(200) charset utf8 collate utf8_general_ci ,IN `latitude` varchar(20) charset utf8 collate utf8_general_ci ,IN `longitude` varchar(20) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '玩家登录游戏记录地理位置'
begin  
  declare _channelid     varchar(32);  -- 玩家所属的渠道id
  declare _citycode      varchar(20);  -- 已记录的城市编号
  declare _invitecode    int(8);       -- 已绑定的邀请码
  
  declare city_wechatgzh varchar(100); -- 城市公众号
  declare city_wechatewm varchar(100); -- 城市公众号二维码图片地址
  declare city_wechatkfh varchar(50);  -- 城市客服微信
  declare city_qq        varchar(50);  -- 城市客服QQ
  declare city_tel       varchar(50);  -- 城市客服电话    
    
  select play_channelid, play_a_citycode, play_invitecode 
  into _channelid, _citycode, _invitecode
  from player 
  where play_agentid = agentid 
    and play_playerid = playerid limit 1;
  
  if isnull(_citycode) then
     -- 记录第一次登录时的城市
     update player set play_a_country = country, play_a_province = province, 
                       play_a_city = city, play_a_citycode = citycode, 
                       play_a_district = district, play_a_street = street, 
                       play_a_address = address
     where play_agentid = agentid 
       and play_playerid = playerid limit 1;
       
    -- 获取城市的联系方式
    select agcc_WechatPublicNo, agcc_wechat_ewm, agcc_service_wechat, agcc_service_qq, agcc_service_tel
    into city_wechatgzh, city_wechatewm, city_wechatkfh, city_qq, city_tel      
    from agent_channel_city
    where agcc_agentid = agentid
      and agcc_channelid = _channelid
      and agcc_citycode = citycode;             
  end if;
  
  if isnull(_invitecode) then
     -- 自动绑定邀请码
     select ifnull(agcc_invitecode, agch_invitecode) 
     into _invitecode
     from agent_channel, agent_channel_city
     where agch_agentid = agentid
       and agch_channelid = _channelid
       and agcc_agentid = agentid
       and agcc_channelid = _channelid
       and agcc_citycode = citycode;
     
     if not isnull(_invitecode) then
       update player set play_invitecode = _invitecode
       where play_agentid = agentid 
         and play_playerid = playerid; 
         
       -- 完成绑定邀请码任务
      call cp_game_task_finish(agentid, playerid, 'UEFsfbv29YnlacKLo0mjomK48Bv82hGv', 1, 0);    
     end if;          
  end if; 
  
  update player set play_longitude = longitude, play_latitude = latitude
  where play_agentid = agentid 
    and play_playerid = playerid limit 1;
  
  select city_wechatgzh as wechatgzh, city_wechatewm as wechatewm, 
         city_wechatkfh as wechatkfh, city_qq as qq, city_tel as tel, 
         _invitecode as invitecode;  
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_login_phoneinfo
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_login_phoneinfo`;
delimiter ;;
CREATE PROCEDURE `cp_game_login_phoneinfo`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `info` varchar(8000) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '玩家登录游戏记录手机信息'
begin  
  update player set play_phoneinfo = info where play_agentid = agentid and play_playerid = playerid limit 1; 
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_pay_succ
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_pay_succ`;
delimiter ;;
CREATE PROCEDURE `cp_game_pay_succ`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `billcode` varchar(50) charset utf8 collate utf8_general_ci ,IN `productid` varchar(32) charset utf8 collate utf8_general_ci ,IN `payid` varchar(100) charset utf8 collate utf8_general_ci ,IN `amount` int(11) ,IN `money` decimal(10,2) ,IN `createtime` datetime ,IN `paymoney` decimal(10,2) ,IN `paytime` datetime ,IN `paytype` tinyint(1) ,IN `transid` varchar(100) charset utf8 collate utf8_general_ci ,IN `outtradeNo` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '游戏中支付成功'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述 
  declare agentname      varchar(100); -- 代理商名称 
  declare playername     varchar(100); -- 玩家昵称
  declare playerroomcard int(11);      -- 玩家房卡数量
  declare roomcard       int(11);      -- 购卡后房卡数量
    
  set result = 0;
     
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验playerid
  call cp_check_2_player(agentid, playerid, result, error, playername, playerroomcard);
  if result > 0 then
    select result, error;
    leave label_cp;
  end if;  
  
  -- 获取渠道商id
  if not exists (select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    select agch_channelid into channelid from agent_channel where agch_agentid = agentid order by idx limit 1;
  end if; 
  
  -- 保存订单
	insert into game_buybill(gabu_agentid, gabu_playerid, gabu_channelid,
                           gabu_billcode, gabu_productid, gabu_payid, 
                           gabu_amount, gabu_money, gabu_createtime, 
                           gabu_paystate, gabu_paymoney, gabu_paytime, 
                           gabu_paytype, gabu_transid, gabu_outtradeNo) 
  values(agentid, playerid, channelid, billcode, productid, payid, amount, money, 
         createtime, 1, paymoney, paytime, paytype, transid, outtradeNo);
  
  -- 统计总流水
  update agent set agen_selftotal = agen_selftotal + paymoney where agen_agentid = agentid;
  
  -- 按日期统计房卡销售金额
  call cp_report_agent_day(agentid, 3, paymoney); 

  -- 修改玩家房卡数量
  update player set play_roomcard = play_roomcard + amount
  where play_agentid = agentid and play_playerid = playerid;
  
  -- 返回玩家购卡后的房卡数量
  select play_roomcard into roomcard from player 
  where play_agentid = agentid and play_playerid = playerid;
  
  -- 返回执行结果 
  select result, error, playerid, playername, amount, roomcard;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_player_advanced
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_player_advanced`;
delimiter ;;
CREATE PROCEDURE `cp_game_player_advanced`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `advanced` tinyint(3) ,IN `shortcode` int(6) ,IN `desone` varchar(400) charset utf8 collate utf8_general_ci ,IN `destwo` varchar(400) charset utf8 collate utf8_general_ci ,IN `lowlimit` int(11) ,IN `notice` varchar(400) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '设置玩家的短号'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述    
  set result = 0;
     
  -- 检验agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error = '运营商id不存在';
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验playerid
  if not exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) then
    set result = 2;
    set error = '玩家id不存在';
    select result, error;
    leave label_cp;
  end if;

  update player 
  set play_shortcode = null, play_advanced = 0, play_roomcodes = null,
      play_desone = null, play_destwo = null, 
      play_limit = null, play_notice = null 
  where play_agentid = agentid
    and play_shortcode = shortcode;
  
  update player set play_advanced = advanced, play_shortcode = shortcode, 
         play_desone = desone, play_destwo = destwo,
         play_limit = lowlimit, play_notice = notice  
  where play_agentid = agentid and play_playerid = playerid limit 1;

  -- 返回执行结果 
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_player_login
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_player_login`;
delimiter ;;
CREATE PROCEDURE `cp_game_player_login`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `nickname` varchar(100) charset utf8 collate utf8_general_ci ,IN `avatar` varchar(200) charset utf8 collate utf8_general_ci ,IN `sex` int(11) ,IN `province` varchar(100) charset utf8 collate utf8_general_ci ,IN `city` varchar(100) charset utf8 collate utf8_general_ci ,IN `marketid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '玩家登录游戏'
begin  
  declare playerid      int(8);       -- 玩家id
  declare roomcard      int(11);      -- 玩家房卡数量 
  declare bean          int(11);      -- 玩家元宝数量
  declare playertype    int(1);       -- 玩家类型   
  declare score         int(11);      -- 积分
  declare invitecode    int(8);       -- 绑定的邀请码
  declare state         tinyint(1);   -- 封禁状态
  declare advanced      tinyint(3);   -- 创建固定房间的权限
  declare shortcode     int(6);       -- 房间短号
  declare roomcodes     varchar(4000);-- 固定房号
  declare desone        varchar(400); 
  declare destwo        varchar(400); 
  declare whitelist     varchar(8000);-- 短号白名单
  declare lowlimit      int(11);      -- 短号房魅力值下限
  declare notice        varchar(400); -- 短号房公告  
  declare optdata       varchar(2000);
  declare nn_winlose    int(11);     -- 牛牛游戏得分 
  declare nn_winlose_xx int(11);     -- 牛牛游戏得分（星星场）
  declare nn_winlose_x2 int(11);     
  declare bankpower     tinyint(1); -- 金币银行权限
  declare bank          int(11);    -- 金币银行中的金币数量
  declare bankpwd       varchar(10);-- 金币银行密码
  
  declare game_winlose    int(11);     -- 游戏得分 
  declare game_winlose_xx int(11);     -- 游戏得分（星星场）
  declare game_winlose_x2 int(11);     -- 游戏星星输赢
  declare psign varchar(400);
  
  -- 如果出现异常，自动退出并rollback
  declare exit handler for sqlexception ROLLBACK;  
  
  -- 启动事务  
  start transaction;  
  
  -- 检查是否是新玩家
  select play_playerid, play_roomcard, play_bean, play_type, play_score, 
         play_invitecode, play_state, play_advanced, play_shortcode, 
         play_roomcodes, play_whitelist, play_desone, play_destwo,
         play_bankpower, play_bank, play_bankpwd, play_limit, play_notice,play_sign 
  into playerid, roomcard, bean, playertype, score, invitecode, state, 
       advanced, shortcode, roomcodes, whitelist, desone, destwo,
       bankpower, bank, bankpwd, lowlimit, notice,psign
  from player 
  where play_agentid = agentid 
    and play_unionid = unionid limit 1;
  
  if isnull(playerid) then
     -- 新玩家
     update agent set agen_maxplayerid = agen_maxplayerid + 1 where agen_agentid = agentid limit 1;

     select agen_maxplayerid, agen_initroomacard, agen_initbean into playerid, roomcard, bean 
     from agent where agen_agentid = agentid limit 1;
     
     -- 随机取一个不存在的玩家id作为新的玩家id(200000-899999)
     set playerid = ceil(rand() * 700000) + 200000;
     while exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) do
       set playerid = ceil(rand() * 700000) + 200000;
     end while;

     insert into player(play_agentid, play_playerid, play_channelid, play_openid, 
                        play_unionid, play_nickname, play_avatar, play_sex,  
                        play_province, play_city, play_regtime, play_lasttime,
                        play_roomcard, play_bean, play_marketid)
     values(agentid, playerid, channelid, openid, unionid, nickname, avatar, sex,
            province, city, now(), now(), roomcard, bean, marketid);
     
     set optdata = CONCAT('{"openid":"', openid, '", "unionid":"', unionid, '", "nickname":"', ifnull(nickname, ''), '","avatar":"', ifnull(avatar, ''), '","sex":', ifnull(sex, 0), ',"province":"', ifnull(province, ''), '","city":"', ifnull(city, ''), '"}');
     insert into ct_user_process_log(uspl_agentid, uspl_channelid, uspl_playerid, uspl_unionid, uspl_opt, uspl_optdata, uspl_opttime)
     values(agentid, channelid, playerid, unionid, 1, optdata, now());
   
     select play_roomcard, play_bean, play_type, play_score, play_invitecode, play_state,
            play_advanced, play_shortcode, play_roomcodes, play_whitelist, play_desone, play_destwo,
            play_bankpower, play_bank, play_bankpwd, play_limit, play_notice,play_sign
     into roomcard, bean, playertype, score, invitecode, state, 
          advanced, shortcode, roomcodes, whitelist, desone, destwo,
          bankpower, bank, bankpwd, lowlimit, notice,psign
     from player 
     where play_agentid = agentid 
       and play_playerid = playerid limit 1;

     -- 按日期统计新增玩家数量
     call cp_report_agent_day(agentid, 0, 1);
  else
     -- 老玩家
     update player set play_nickname = nickname, play_avatar = avatar, play_openid = openid,
                       play_sex = sex, play_province = province, play_city = city, 
                       play_logindate = play_logindate + if(datediff(now(), play_lasttime) = 0, 0, 1),
                       play_lasttime = now()                     
     where play_agentid = agentid 
       and play_playerid = playerid limit 1; 
  end if;
   
  -- 统计玩家的最后登录时间和累积登录天数
  if not exists(select 1 from agent_game_player 
                where agpl_agentid = agentid 
                  and agpl_gameid = gameid 
                  and agpl_playerid = playerid) then
    insert into agent_game_player(agpl_agentid, agpl_gameid, agpl_playerid, agpl_openid, agpl_firsttime, agpl_lasttime)
    values(agentid, gameid, playerid, openid, now(), now());
    
    -- 按日期统计新增玩家数量
    call cp_report_game_day(agentid, gameid, now(), 0, 1, null);
  else
    update agent_game_player set agpl_logindate = agpl_logindate + if(datediff(now(), agpl_lasttime) = 0, 0, 1),
                                 agpl_lasttime = now()
    where agpl_agentid = agentid 
      and agpl_gameid = gameid 
      and agpl_playerid = playerid limit 1;
  end if;
  
  -- 看是否自动绑定过邀请码
  if isnull(invitecode) then
    call cp_game_get_player_invitecode_insales(agentid, playerid, unionid, invitecode); 
  end if;
  
  -- 运行没有异常，提交事务  
  commit;  
  
  -- 返回执行结果
  select ifnull(agpl_winlose, 0), ifnull(agpl_winlose_xx, 0), ifnull(agpl_winlose_x2, 0) 
    into nn_winlose, nn_winlose_xx, nn_winlose_x2
  from agent_game_player 
  where agpl_agentid = agentid
    and agpl_gameid = '8x4l0rGjf026f60c48h0mbUAhK5vV16f'
    and agpl_playerid = playerid limit 1;
	
  select ifnull(agpl_winlose, 0), ifnull(agpl_winlose_xx, 0), ifnull(agpl_winlose_x2, 0) 
    into game_winlose, game_winlose_xx, game_winlose_x2
  from agent_game_player 
  where agpl_agentid = agentid
    -- and agpl_gameid = '8x4l0rGjf026f60c48h0mbUAhK5vV16f'
	and agpl_gameid = gameid
    and agpl_playerid = playerid limit 1;
  
  select playerid, roomcard, bean, playertype, score, invitecode, state, 
         advanced, shortcode, roomcodes, whitelist, 
         nn_winlose, nn_winlose_xx, nn_winlose_x2, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice ,gameid,game_winlose, game_winlose_xx, game_winlose_x2,psign;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_player_login_1121
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_player_login_1121`;
delimiter ;;
CREATE PROCEDURE `cp_game_player_login_1121`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `nickname` varchar(100) charset utf8 collate utf8_general_ci ,IN `avatar` varchar(200) charset utf8 collate utf8_general_ci ,IN `sex` int(11) ,IN `province` varchar(100) charset utf8 collate utf8_general_ci ,IN `city` varchar(100) charset utf8 collate utf8_general_ci ,IN `marketid` varchar(100) charset utf8 collate utf8_general_ci ,IN `telphone` varchar(20) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '玩家登录游戏'
proc: begin  
  declare playerid      int(8);       -- 玩家id
  declare roomcard      int(11);      -- 玩家房卡数量 
  declare bean          int(11);      -- 玩家元宝数量
  declare playertype    int(1);       -- 玩家类型   
  declare score         int(11);      -- 积分
  declare invitecode    int(8);       -- 绑定的邀请码
  declare inviteid      int(8);       -- 绑定的邀请码
  declare state         tinyint(1);   -- 封禁状态
  declare advanced      tinyint(3);   -- 创建固定房间的权限
  declare shortcode     int(6);       -- 房间短号
  declare roomcodes     varchar(4000);-- 固定房号
  declare desone        varchar(400); 
  declare destwo        varchar(400); 
  declare whitelist     varchar(8000);-- 短号白名单
  declare lowlimit      int(11);      -- 短号房魅力值下限
  declare notice        varchar(400); -- 短号房公告  
  declare optdata       varchar(2000);
  declare nn_winlose    int(11);     -- 牛牛游戏得分 
  declare nn_winlose_xx int(11);     -- 牛牛游戏得分（星星场）
  declare nn_winlose_x2 int(11);     
  declare bankpower     tinyint(1); -- 金币银行权限
  declare bank          int(11);    -- 金币银行中的金币数量
  declare bankpwd       varchar(10);-- 金币银行密码
  
  declare game_winlose    int(11);     -- 游戏得分 
  declare game_winlose_xx int(11);     -- 游戏得分（星星场）
  declare game_winlose_x2 int(11);     -- 游戏星星输赢
  
  declare psign varchar(400);
  declare tel   varchar(20); -- 绑定的手机号
  
  -- 手机号登录时返回的额外信息
  declare ret_nickname varchar(100);
  declare ret_avatar varchar(200);
  declare ret_openid varchar(100);
  declare ret_sex int(11);
  declare ret_province varchar(100);
  declare ret_city varchar(100);
  declare ret_logindate int(11);
  declare ret_unionid varchar(100);
  
  -- 如果出现异常，自动退出并rollback
  declare exit handler for sqlexception ROLLBACK;  
  
  -- 启动事务  
  start transaction;  
  
  -- 检查是否是新玩家
  if isnull(telphone) then
    -- 微信授权或设备码登录
    select play_playerid, play_roomcard, play_bean, play_type, play_score, 
           play_invitecode, play_inviteid, play_state, play_advanced, play_shortcode, 
           play_roomcodes, play_whitelist, play_desone, play_destwo,
           play_bankpower, play_bank, play_bankpwd, play_limit, play_notice,
           play_sign, play_tel 
    into playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice, psign, tel
    from player 
    where play_agentid = agentid 
      and play_unionid = unionid limit 1;
  else
    -- 手机号登录
    select play_playerid, play_roomcard, play_bean, play_type, play_score, 
           play_invitecode, play_inviteid, play_state, play_advanced, play_shortcode, 
           play_roomcodes, play_whitelist, play_desone, play_destwo,
           play_bankpower, play_bank, play_bankpwd, play_limit, play_notice,
           play_sign, play_tel,
           play_nickname, play_avatar, play_openid, play_sex, play_province, play_city, play_logindate, play_unionid
    into playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice, psign, tel,
         ret_nickname, ret_avatar, ret_openid, ret_sex, ret_province, ret_city, ret_logindate, ret_unionid
    from player 
    where play_agentid = agentid 
      and play_tel = telphone limit 1; 
  end if;
  
  if isnull(playerid) then
     -- 如果传入了手机号，但没找到记录，说明手机号未注册，不允许自动创建新号
     if not isnull(telphone) then
        rollback;
        select -1 as result, '手机号未注册' as msg;
        leave proc;
     end if;

     -- 新玩家
     update agent set agen_maxplayerid = agen_maxplayerid + 1 where agen_agentid = agentid limit 1;

     select agen_maxplayerid, agen_initroomacard, agen_initbean into playerid, roomcard, bean 
     from agent where agen_agentid = agentid limit 1;
     
     -- 随机取一个不存在的玩家id作为新的玩家id(200000-899999)
     set playerid = ceil(rand() * 700000) + 200000;
     while exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) do
       set playerid = ceil(rand() * 700000) + 200000;
     end while;

     insert into player(play_agentid, play_playerid, play_channelid, play_openid, 
                        play_unionid, play_nickname, play_avatar, play_sex,  
                        play_province, play_city, play_regtime, play_lasttime,
                        play_roomcard, play_bean, play_marketid, play_tel)
     values(agentid, playerid, channelid, openid, unionid, nickname, avatar, sex,
            province, city, now(), now(), roomcard, bean, marketid, telphone);
     
     set optdata = CONCAT('{"openid":"', openid, '", "unionid":"', unionid, '", "nickname":"', ifnull(nickname, ''), '","avatar":"', ifnull(avatar, ''), '","sex":', ifnull(sex, 0), ',"province":"', ifnull(province, ''), '","city":"', ifnull(city, ''), '"}');
     insert into ct_user_process_log(uspl_agentid, uspl_channelid, uspl_playerid, uspl_unionid, uspl_opt, uspl_optdata, uspl_opttime)
     values(agentid, channelid, playerid, unionid, 1, optdata, now());
   
     select play_roomcard, play_bean, play_type, play_score, play_invitecode, play_inviteid, play_state,
            play_advanced, play_shortcode, play_roomcodes, play_whitelist, play_desone, play_destwo,
            play_bankpower, play_bank, play_bankpwd, play_limit, play_notice, play_sign, play_tel
     into roomcard, bean, playertype, score, invitecode, inviteid, state, 
          advanced, shortcode, roomcodes, whitelist, desone, destwo,
          bankpower, bank, bankpwd, lowlimit, notice, psign, tel
     from player 
     where play_agentid = agentid 
       and play_playerid = playerid limit 1;

     -- 按日期统计新增玩家数量
     call cp_report_agent_day(agentid, 0, 1);
  else
     -- 老玩家
     if not isnull(telphone) then
        -- 手机号登录，只更新登录时间，不修改用户信息
        update player set play_logindate = play_logindate + if(datediff(now(), play_lasttime) = 0, 0, 1),
                          play_lasttime = now()
        where play_agentid = agentid 
          and play_playerid = playerid limit 1;
     else
        -- 微信/UnionID登录，更新用户信息
        update player set play_nickname = nickname, play_avatar = avatar, play_openid = openid,
                          play_sex = sex, play_province = province, play_city = city, 
                          play_logindate = play_logindate + if(datediff(now(), play_lasttime) = 0, 0, 1),
                          play_lasttime = now(), play_unionid = unionid                     
        where play_agentid = agentid 
          and play_playerid = playerid limit 1; 
     end if;
  end if;
   
  -- 统计玩家的最后登录时间和累积登录天数
  if not exists(select 1 from agent_game_player 
                where agpl_agentid = agentid 
                  and agpl_gameid = gameid 
                  and agpl_playerid = playerid) then
    insert into agent_game_player(agpl_agentid, agpl_gameid, agpl_playerid, agpl_openid, agpl_firsttime, agpl_lasttime)
    values(agentid, gameid, playerid, openid, now(), now());
    
    -- 按日期统计新增玩家数量
    call cp_report_game_day(agentid, gameid, now(), 0, 1, null);
  else
    update agent_game_player set agpl_logindate = agpl_logindate + if(datediff(now(), agpl_lasttime) = 0, 0, 1),
                                 agpl_lasttime = now()
    where agpl_agentid = agentid 
      and agpl_gameid = gameid 
      and agpl_playerid = playerid limit 1;
  end if;
  
  -- 看是否自动绑定过邀请码
  if isnull(invitecode) then
    call cp_game_get_player_invitecode_insales(agentid, playerid, unionid, invitecode); 
  end if;
  
  -- 运行没有异常，提交事务  
  commit;  
  
  -- 返回执行结果
  select ifnull(agpl_winlose, 0), ifnull(agpl_winlose_xx, 0), ifnull(agpl_winlose_x2, 0) 
    into nn_winlose, nn_winlose_xx, nn_winlose_x2
  from agent_game_player 
  where agpl_agentid = agentid
    and agpl_gameid = '8x4l0rGjf026f60c48h0mbUAhK5vV16f'
    and agpl_playerid = playerid limit 1;
	
  select ifnull(agpl_winlose, 0), ifnull(agpl_winlose_xx, 0), ifnull(agpl_winlose_x2, 0) 
    into game_winlose, game_winlose_xx, game_winlose_x2
  from agent_game_player 
  where agpl_agentid = agentid
    -- and agpl_gameid = '8x4l0rGjf026f60c48h0mbUAhK5vV16f'
	and agpl_gameid = gameid
    and agpl_playerid = playerid limit 1;
  
  select playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, 
         nn_winlose, nn_winlose_xx, nn_winlose_x2, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice ,gameid,game_winlose, 
         game_winlose_xx, game_winlose_x2, psign, tel,
         ret_nickname, ret_avatar, ret_openid, ret_sex, ret_province, ret_city, ret_logindate, ret_unionid;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_player_login_1121_bak
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_player_login_1121_bak`;
delimiter ;;
CREATE PROCEDURE `cp_game_player_login_1121_bak`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `nickname` varchar(100) charset utf8 collate utf8_general_ci ,IN `avatar` varchar(200) charset utf8 collate utf8_general_ci ,IN `sex` int(11) ,IN `province` varchar(100) charset utf8 collate utf8_general_ci ,IN `city` varchar(100) charset utf8 collate utf8_general_ci ,IN `marketid` varchar(100) charset utf8 collate utf8_general_ci ,IN `telphone` varchar(20) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '玩家登录游戏'
begin  
  declare playerid      int(8);       -- 玩家id
  declare roomcard      int(11);      -- 玩家房卡数量 
  declare bean          int(11);      -- 玩家元宝数量
  declare playertype    int(1);       -- 玩家类型   
  declare score         int(11);      -- 积分
  declare invitecode    int(8);       -- 绑定的邀请码
  declare inviteid      int(8);       -- 绑定的邀请码
  declare state         tinyint(1);   -- 封禁状态
  declare advanced      tinyint(3);   -- 创建固定房间的权限
  declare shortcode     int(6);       -- 房间短号
  declare roomcodes     varchar(4000);-- 固定房号
  declare desone        varchar(400); 
  declare destwo        varchar(400); 
  declare whitelist     varchar(8000);-- 短号白名单
  declare lowlimit      int(11);      -- 短号房魅力值下限
  declare notice        varchar(400); -- 短号房公告  
  declare optdata       varchar(2000);
  declare nn_winlose    int(11);     -- 牛牛游戏得分 
  declare nn_winlose_xx int(11);     -- 牛牛游戏得分（星星场）
  declare nn_winlose_x2 int(11);     
  declare bankpower     tinyint(1); -- 金币银行权限
  declare bank          int(11);    -- 金币银行中的金币数量
  declare bankpwd       varchar(10);-- 金币银行密码
  
  declare game_winlose    int(11);     -- 游戏得分 
  declare game_winlose_xx int(11);     -- 游戏得分（星星场）
  declare game_winlose_x2 int(11);     -- 游戏星星输赢
  
  declare psign varchar(400);
  declare tel   varchar(20); -- 绑定的手机号
  
  -- 如果出现异常，自动退出并rollback
  declare exit handler for sqlexception ROLLBACK;  
  
  -- 启动事务  
  start transaction;  
  
  -- 检查是否是新玩家
  if isnull(telphone) then
    -- 微信授权或设备码登录
    select play_playerid, play_roomcard, play_bean, play_type, play_score, 
           play_invitecode, play_inviteid, play_state, play_advanced, play_shortcode, 
           play_roomcodes, play_whitelist, play_desone, play_destwo,
           play_bankpower, play_bank, play_bankpwd, play_limit, play_notice,
           play_sign, play_tel 
    into playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice, psign, tel
    from player 
    where play_agentid = agentid 
      and play_unionid = unionid limit 1;
  else
    -- 手机号登录
    select play_playerid, play_roomcard, play_bean, play_type, play_score, 
           play_invitecode, play_inviteid, play_state, play_advanced, play_shortcode, 
           play_roomcodes, play_whitelist, play_desone, play_destwo,
           play_bankpower, play_bank, play_bankpwd, play_limit, play_notice,
           play_sign, play_tel 
    into playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice, psign, tel
    from player 
    where play_agentid = agentid 
      and play_tel = telphone limit 1; 
  end if;
  
  if isnull(playerid) then
     -- 新玩家
     update agent set agen_maxplayerid = agen_maxplayerid + 1 where agen_agentid = agentid limit 1;

     select agen_maxplayerid, agen_initroomacard, agen_initbean into playerid, roomcard, bean 
     from agent where agen_agentid = agentid limit 1;
     
     -- 随机取一个不存在的玩家id作为新的玩家id(200000-899999)
     set playerid = ceil(rand() * 700000) + 200000;
     while exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) do
       set playerid = ceil(rand() * 700000) + 200000;
     end while;

     insert into player(play_agentid, play_playerid, play_channelid, play_openid, 
                        play_unionid, play_nickname, play_avatar, play_sex,  
                        play_province, play_city, play_regtime, play_lasttime,
                        play_roomcard, play_bean, play_marketid, play_tel)
     values(agentid, playerid, channelid, openid, unionid, nickname, avatar, sex,
            province, city, now(), now(), roomcard, bean, marketid, telphone);
     
     set optdata = CONCAT('{"openid":"', openid, '", "unionid":"', unionid, '", "nickname":"', ifnull(nickname, ''), '","avatar":"', ifnull(avatar, ''), '","sex":', ifnull(sex, 0), ',"province":"', ifnull(province, ''), '","city":"', ifnull(city, ''), '"}');
     insert into ct_user_process_log(uspl_agentid, uspl_channelid, uspl_playerid, uspl_unionid, uspl_opt, uspl_optdata, uspl_opttime)
     values(agentid, channelid, playerid, unionid, 1, optdata, now());
   
     select play_roomcard, play_bean, play_type, play_score, play_invitecode, play_inviteid, play_state,
            play_advanced, play_shortcode, play_roomcodes, play_whitelist, play_desone, play_destwo,
            play_bankpower, play_bank, play_bankpwd, play_limit, play_notice, play_sign, play_tel
     into roomcard, bean, playertype, score, invitecode, inviteid, state, 
          advanced, shortcode, roomcodes, whitelist, desone, destwo,
          bankpower, bank, bankpwd, lowlimit, notice, psign, tel
     from player 
     where play_agentid = agentid 
       and play_playerid = playerid limit 1;

     -- 按日期统计新增玩家数量
     call cp_report_agent_day(agentid, 0, 1);
  else
     -- 老玩家
     update player set play_nickname = nickname, play_avatar = avatar, play_openid = openid,
                       play_sex = sex, play_province = province, play_city = city, 
                       play_logindate = play_logindate + if(datediff(now(), play_lasttime) = 0, 0, 1),
                       play_lasttime = now(), play_unionid = unionid                     
     where play_agentid = agentid 
       and play_playerid = playerid limit 1; 
  end if;
   
  -- 统计玩家的最后登录时间和累积登录天数
  if not exists(select 1 from agent_game_player 
                where agpl_agentid = agentid 
                  and agpl_gameid = gameid 
                  and agpl_playerid = playerid) then
    insert into agent_game_player(agpl_agentid, agpl_gameid, agpl_playerid, agpl_openid, agpl_firsttime, agpl_lasttime)
    values(agentid, gameid, playerid, openid, now(), now());
    
    -- 按日期统计新增玩家数量
    call cp_report_game_day(agentid, gameid, now(), 0, 1, null);
  else
    update agent_game_player set agpl_logindate = agpl_logindate + if(datediff(now(), agpl_lasttime) = 0, 0, 1),
                                 agpl_lasttime = now()
    where agpl_agentid = agentid 
      and agpl_gameid = gameid 
      and agpl_playerid = playerid limit 1;
  end if;
  
  -- 看是否自动绑定过邀请码
  if isnull(invitecode) then
    call cp_game_get_player_invitecode_insales(agentid, playerid, unionid, invitecode); 
  end if;
  
  -- 运行没有异常，提交事务  
  commit;  
  
  -- 返回执行结果
  select ifnull(agpl_winlose, 0), ifnull(agpl_winlose_xx, 0), ifnull(agpl_winlose_x2, 0) 
    into nn_winlose, nn_winlose_xx, nn_winlose_x2
  from agent_game_player 
  where agpl_agentid = agentid
    and agpl_gameid = '8x4l0rGjf026f60c48h0mbUAhK5vV16f'
    and agpl_playerid = playerid limit 1;
	
  select ifnull(agpl_winlose, 0), ifnull(agpl_winlose_xx, 0), ifnull(agpl_winlose_x2, 0) 
    into game_winlose, game_winlose_xx, game_winlose_x2
  from agent_game_player 
  where agpl_agentid = agentid
    -- and agpl_gameid = '8x4l0rGjf026f60c48h0mbUAhK5vV16f'
	and agpl_gameid = gameid
    and agpl_playerid = playerid limit 1;
  
  select playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, 
         nn_winlose, nn_winlose_xx, nn_winlose_x2, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice ,gameid,game_winlose, 
         game_winlose_xx, game_winlose_x2, psign, tel;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_player_login_test
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_player_login_test`;
delimiter ;;
CREATE PROCEDURE `cp_game_player_login_test`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `nickname` varchar(100) charset utf8 collate utf8_general_ci ,IN `avatar` varchar(200) charset utf8 collate utf8_general_ci ,IN `sex` int(11) ,IN `province` varchar(100) charset utf8 collate utf8_general_ci ,IN `city` varchar(100) charset utf8 collate utf8_general_ci ,IN `marketid` varchar(100) charset utf8 collate utf8_general_ci ,IN `telphone` varchar(20) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '玩家登录游戏'
begin  
  declare playerid      int(8);       -- 玩家id
  declare roomcard      int(11);      -- 玩家房卡数量 
  declare bean          int(11);      -- 玩家元宝数量
  declare playertype    int(1);       -- 玩家类型   
  declare score         int(11);      -- 积分
  declare invitecode    int(8);       -- 绑定的邀请码
  declare inviteid      int(8);       -- 绑定的邀请码
  declare state         tinyint(1);   -- 封禁状态
  declare advanced      tinyint(3);   -- 创建固定房间的权限
  declare shortcode     int(6);       -- 房间短号
  declare roomcodes     varchar(4000);-- 固定房号
  declare desone        varchar(400); 
  declare destwo        varchar(400); 
  declare whitelist     varchar(8000);-- 短号白名单
  declare lowlimit      int(11);      -- 短号房魅力值下限
  declare notice        varchar(400); -- 短号房公告  
  declare optdata       varchar(2000);
  declare nn_winlose    int(11);     -- 牛牛游戏得分 
  declare nn_winlose_xx int(11);     -- 牛牛游戏得分（星星场）
  declare nn_winlose_x2 int(11);     
  declare bankpower     tinyint(1); -- 金币银行权限
  declare bank          int(11);    -- 金币银行中的金币数量
  declare bankpwd       varchar(10);-- 金币银行密码
  
  declare game_winlose    int(11);     -- 游戏得分 
  declare game_winlose_xx int(11);     -- 游戏得分（星星场）
  declare game_winlose_x2 int(11);     -- 游戏星星输赢
  
  declare psign varchar(400);
  declare tel   varchar(20); -- 绑定的手机号
  
  -- 如果出现异常，自动退出并rollback
  declare exit handler for sqlexception ROLLBACK;  
  
  -- 启动事务  
  start transaction;  
select 1, telphone;  
  -- 检查是否是新玩家
  if isnull(telphone) then
    -- 微信授权或设备码登录
    select play_playerid, play_roomcard, play_bean, play_type, play_score, 
           play_invitecode, play_inviteid, play_state, play_advanced, play_shortcode, 
           play_roomcodes, play_whitelist, play_desone, play_destwo,
           play_bankpower, play_bank, play_bankpwd, play_limit, play_notice,
           play_sign, play_tel 
    into playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice, psign, tel
    from player 
    where play_agentid = agentid 
      and play_unionid = unionid limit 1;
select 2, playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice, psign, tel;  
  else
    -- 手机号登录
    select play_playerid, play_roomcard, play_bean, play_type, play_score, 
           play_invitecode, play_inviteid, play_state, play_advanced, play_shortcode, 
           play_roomcodes, play_whitelist, play_desone, play_destwo,
           play_bankpower, play_bank, play_bankpwd, play_limit, play_notice,
           play_sign, play_tel 
    into playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice, psign, tel
    from player 
    where play_agentid = agentid 
      and play_tel = telphone limit 1; 
select 3, playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice, psign, tel;  
  end if;
  
  if isnull(playerid) then
select 4;
     -- 新玩家
     update agent set agen_maxplayerid = agen_maxplayerid + 1 where agen_agentid = agentid limit 1;
select 5;
     select agen_maxplayerid, agen_initroomacard, agen_initbean into playerid, roomcard, bean 
     from agent where agen_agentid = agentid limit 1;
select 6;     
     -- 随机取一个不存在的玩家id作为新的玩家id(200000-899999)
     set playerid = ceil(rand() * 700000) + 200000;
     while exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) do
       set playerid = ceil(rand() * 700000) + 200000;
     end while;
select 7, agentid, playerid, channelid, openid, unionid, nickname, avatar, sex,
            province, city, roomcard, bean, marketid, telphone;
     insert into player(play_agentid, play_playerid, play_channelid, play_openid, 
                        play_unionid, play_nickname, play_avatar, play_sex,  
                        play_province, play_city, play_regtime, play_lasttime,
                        play_roomcard, play_bean, play_marketid, play_tel)
     values(agentid, playerid, channelid, openid, unionid, nickname, avatar, sex,
            province, city, now(), now(), roomcard, bean, marketid, telphone);
select 8;     
     set optdata = CONCAT('{"openid":"', openid, '", "unionid":"', unionid, '", "nickname":"', ifnull(nickname, ''), '","avatar":"', ifnull(avatar, ''), '","sex":', ifnull(sex, 0), ',"province":"', ifnull(province, ''), '","city":"', ifnull(city, ''), '"}');
     insert into ct_user_process_log(uspl_agentid, uspl_channelid, uspl_playerid, uspl_unionid, uspl_opt, uspl_optdata, uspl_opttime)
     values(agentid, channelid, playerid, unionid, 1, optdata, now());
select 9;   
     select play_roomcard, play_bean, play_type, play_score, play_invitecode, play_inviteid, play_state,
            play_advanced, play_shortcode, play_roomcodes, play_whitelist, play_desone, play_destwo,
            play_bankpower, play_bank, play_bankpwd, play_limit, play_notice, play_sign, play_tel
     into roomcard, bean, playertype, score, invitecode, inviteid, state, 
          advanced, shortcode, roomcodes, whitelist, desone, destwo,
          bankpower, bank, bankpwd, lowlimit, notice, psign, tel
     from player 
     where play_agentid = agentid 
       and play_playerid = playerid limit 1;
select 10;
     -- 按日期统计新增玩家数量
     call cp_report_agent_day(agentid, 0, 1);
select 11;
  else
select 14;
     -- 老玩家
     update player set play_nickname = nickname, play_avatar = avatar, play_openid = openid,
                       play_sex = sex, play_province = province, play_city = city, 
                       play_logindate = play_logindate + if(datediff(now(), play_lasttime) = 0, 0, 1),
                       play_lasttime = now(), play_unionid = unionid                     
     where play_agentid = agentid 
       and play_playerid = playerid limit 1; 
select 15;
  end if;
   
  -- 统计玩家的最后登录时间和累积登录天数
  if not exists(select 1 from agent_game_player 
                where agpl_agentid = agentid 
                  and agpl_gameid = gameid 
                  and agpl_playerid = playerid) then
    insert into agent_game_player(agpl_agentid, agpl_gameid, agpl_playerid, agpl_openid, agpl_firsttime, agpl_lasttime)
    values(agentid, gameid, playerid, openid, now(), now());
    
    -- 按日期统计新增玩家数量
    call cp_report_game_day(agentid, gameid, now(), 0, 1, null);
  else
    update agent_game_player set agpl_logindate = agpl_logindate + if(datediff(now(), agpl_lasttime) = 0, 0, 1),
                                 agpl_lasttime = now()
    where agpl_agentid = agentid 
      and agpl_gameid = gameid 
      and agpl_playerid = playerid limit 1;
  end if;
  
  -- 看是否自动绑定过邀请码
  if isnull(invitecode) then
    call cp_game_get_player_invitecode_insales(agentid, playerid, unionid, invitecode); 
  end if;
  
  -- 运行没有异常，提交事务  
  commit;  
  
  -- 返回执行结果
  select ifnull(agpl_winlose, 0), ifnull(agpl_winlose_xx, 0), ifnull(agpl_winlose_x2, 0) 
    into nn_winlose, nn_winlose_xx, nn_winlose_x2
  from agent_game_player 
  where agpl_agentid = agentid
    and agpl_gameid = '8x4l0rGjf026f60c48h0mbUAhK5vV16f'
    and agpl_playerid = playerid limit 1;
	
  select ifnull(agpl_winlose, 0), ifnull(agpl_winlose_xx, 0), ifnull(agpl_winlose_x2, 0) 
    into game_winlose, game_winlose_xx, game_winlose_x2
  from agent_game_player 
  where agpl_agentid = agentid
    -- and agpl_gameid = '8x4l0rGjf026f60c48h0mbUAhK5vV16f'
	and agpl_gameid = gameid
    and agpl_playerid = playerid limit 1;
  
  select playerid, roomcard, bean, playertype, score, invitecode, inviteid, state, 
         advanced, shortcode, roomcodes, whitelist, 
         nn_winlose, nn_winlose_xx, nn_winlose_x2, desone, destwo,
         bankpower, bank, bankpwd, lowlimit, notice ,gameid,game_winlose, 
         game_winlose_xx, game_winlose_x2, psign, tel;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_player_whitelist
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_player_whitelist`;
delimiter ;;
CREATE PROCEDURE `cp_game_player_whitelist`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `whitelist` varchar(6000) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '设置短号白名单'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述    
  set result = 0;
     
  -- 检验agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error = '运营商id不存在';
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验playerid
  if not exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) then
    set result = 2;
    set error = '玩家id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  update player set play_whitelist = whitelist 
  where play_agentid = agentid and play_playerid = playerid limit 1;

  -- 返回执行结果 
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_sub_bean
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_sub_bean`;
delimiter ;;
CREATE PROCEDURE `cp_game_sub_bean`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `amount` int(8))
  SQL SECURITY INVOKER
  COMMENT '减豆豆(第三方接口)'
label_cp: begin
  declare result tinyint(1);   -- 0:成功  >0:失败 
  declare error  varchar(100); -- 失败描述 
  declare bean   int(8);

  set result = 0;
  if not exists(select 1 from agent where agen_agentid = agentid) then 
    set result = 1;
    set error  = 'agentid不存在';
    select result, error;
    leave label_cp;
  end if; 
  
  set bean = null;
  select play_bean into bean from player 
  where play_agentid = agentid and play_playerid = playerid limit 1;
  if isnull(bean) then 
    set result = 1;
    set error  = 'player不存在';
    select result, error;
    leave label_cp;  
  end if; 
  
  if amount = 0 then
    update player set play_bean = 0
    where play_agentid = agentid 
      and play_playerid = playerid limit 1; 
      
    select result, agentid, playerid, bean as amount, 0 as bean;       
  else
    if amount > bean then
      set result = 1;
      set error  = '数量不够';
      select result, error;
      leave label_cp;    
    end if; 
    
    update player set play_bean = play_bean - amount
    where play_agentid = agentid 
      and play_playerid = playerid limit 1;   
      
    select result, agentid, playerid, amount, bean - amount as bean;      
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_task_award
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_task_award`;
delimiter ;;
CREATE PROCEDURE `cp_game_task_award`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `taskid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '玩家领取任务奖励'
label_cp: begin
  declare result          tinyint(1);   -- 0:成功  >0:失败 
  declare error           varchar(100); -- 失败描述 
  declare agentname       varchar(100); -- 代理商名称 
  declare playername      varchar(100); -- 玩家昵称
  declare playerroomcard  int(11);      -- 玩家房卡数量
  declare tasktype        tinyint(1);   -- 任务类型
  declare tasktotal       int(8);       -- 任务的任务总量
  declare taskaward       int(8);       -- 任务的完成奖励
  declare taskstate       tinyint(1) default null; -- 当前任务的任务状态
  declare playertaskstate tinyint(1);   -- 玩家总的任务状态

  set result = 0;
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
   
  -- 检验playerid
  call cp_check_2_player(agentid, playerid, result, error, playername, playerroomcard);
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
  
  -- 检验taskid
  call cp_check_8_task(agentid, taskid, result, error, tasktype, tasktotal, taskaward);
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
  
  -- 检查任务是否完成
  select tapl_state into taskstate from task_player 
  where tapl_agentid = agentid and tapl_playerid = playerid and tapl_taskid = taskid;
  
  if ifnull(taskstate, 0) = 0 then
    set result = 8;
    set error = '任务未完成，不可领取奖励';
    select result, error;
    leave label_cp;    
  end if;  
  
  if ifnull(taskstate, 0) = 2 then
    set result = 8;
    set error = '任务奖励已领取，不可重复领取';
    select result, error;
    leave label_cp;
  end if;
    
  -- 修改玩家房卡数量
  if tasktype = 2 then
    select tapl_finish * taskaward into taskaward 
    from task_player 
    where tapl_agentid = agentid
      and tapl_playerid = playerid
      and tapl_taskid = taskid;
  elseif tasktype = 3 then
    select tapl_finish into taskaward 
    from task_player 
    where tapl_agentid = agentid
      and tapl_playerid = playerid
      and tapl_taskid = taskid;  
  end if;
  
  update player set play_roomcard = play_roomcard + taskaward,
                    play_taskaward = play_taskaward + taskaward
  where play_agentid = agentid and play_playerid = playerid;  
  
  -- 按日期统计玩家领取的奖励房卡数量
  call cp_report_agent_day(agentid, 2, taskaward);

  -- 修改任务状态
  if tasktype in (2, 3) then
    update task_player set tapl_state = 0, tapl_finish = 0
    where tapl_agentid = agentid and tapl_playerid = playerid and tapl_taskid = taskid;  
  else
    update task_player set tapl_state = 2, tapl_awardtime = now()
    where tapl_agentid = agentid and tapl_playerid = playerid and tapl_taskid = taskid;  
  end if;
  
  -- 获取玩家总的任务状态
  -- call cp_game_get_player_taskstate(agentid, playerid, playertaskstate);
  set playertaskstate = 1;
  
  -- 返回玩家最新的房卡数量
  select result, error, play_roomcard as roomcard, taskaward, playertaskstate
  from player
  where play_agentid = agentid and play_playerid = playerid;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_task_finish
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_task_finish`;
delimiter ;;
CREATE PROCEDURE `cp_game_task_finish`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `taskid` varchar(32) charset utf8 collate utf8_general_ci ,IN `amount` int(8) ,IN `reflag` int(1))
  SQL SECURITY INVOKER
  COMMENT '玩家完成部分任务量'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述 
  declare agentname      varchar(100); -- 代理商名称 
  declare playername     varchar(100); -- 玩家昵称
  declare playerroomcard int(11);      -- 玩家房卡数量
  declare tasktype       tinyint(1);   -- 任务状态
  declare tasktotal      int(8);       -- 任务的任务总量
  declare taskaward      int(8);       -- 任务的完成奖励
  declare newtaskflag    tinyint(1);   -- 对于玩家而言是否是新任务的标志
  declare taskfinish     int(8) default null;  -- 玩家已完成的任务量
  declare taskstate      tinyint(1);   -- 玩家的任务状态

  set result = 0;
  
  if isnull(reflag) then
    set reflag = 1;
  end if;
  
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 and reflag = 1 then 
    select result, error;
    leave label_cp;
  end if;  
   
  -- 检验playerid
  call cp_check_2_player(agentid, playerid, result, error, playername, playerroomcard);
  if result > 0 and reflag = 1 then
    select result, error;
    leave label_cp;
  end if;
  
  -- 检验taskid
  call cp_check_8_task(agentid, taskid, result, error, tasktype, tasktotal, taskaward);
  if result > 0 and reflag = 1 then
    select result, error;
    leave label_cp;
  end if;

  set taskfinish = null;
  set taskstate  = null;
  
  select tapl_finish, tapl_state into taskfinish, taskstate from task_player 
  where tapl_agentid = agentid and tapl_playerid = playerid and tapl_taskid = taskid;

  if isnull(taskfinish) then
    -- 新任务
    set newtaskflag = 1;
    set taskfinish = amount;
  else  
    -- 老任务
    if (tasktype in (0,1)) and (taskstate <> 0) then
      set result = 16;
      set error = '任务已经完成';
      if reflag = 1 then
        select result, error;
      end if;
      leave label_cp;
    end if;

    set newtaskflag = 0;
    set taskfinish = taskfinish + amount;
  end if;
  
  if taskfinish >= tasktotal then
    -- 已完成
    set taskstate = 1;
  else
    -- 未完成
    set taskstate = 0;
  end if;
  
  if newtaskflag = 1 then  
    -- 新任务
    if taskstate = 0 then
      -- 未完成
      insert into task_player (tapl_agentid, tapl_playerid, tapl_taskid, tapl_finish, tapl_state, tapl_createtime)
      values (agentid, playerid, taskid, taskfinish, taskstate, now());
    else
      -- 已完成
      insert into task_player (tapl_agentid, tapl_playerid, tapl_taskid, tapl_finish, tapl_state, tapl_createtime, tapl_finishtime)
      values (agentid, playerid, taskid, taskfinish, taskstate, now(), now());  
    end if;   
  else
    -- 老任务
    if taskstate = 0 then
      -- 未完成
      update task_player set tapl_finish = taskfinish 
      where tapl_agentid = agentid and tapl_playerid = playerid and tapl_taskid = taskid;
    else
      -- 已完成  
      update task_player set tapl_finish = taskfinish, tapl_state = taskstate, tapl_finishtime = now()
      where tapl_agentid = agentid and tapl_playerid = playerid and tapl_taskid = taskid;
    end if;
  end if;
  
  if reflag = 1 then
    select result, error, tasktotal, taskfinish, taskstate, taskaward;
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_task_list
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_task_list`;
delimiter ;;
CREATE PROCEDURE `cp_game_task_list`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '玩家获取任务列表'
begin
  select task_taskid as taskid, task_type as type, task_title as title,
         task_memo as memo, task_total as total, 
         case task_type 
           when 2 then if(ifnull(tapl_finish, 0) = 0, task_award, tapl_finish * task_award)
           when 3 then ifnull(tapl_finish, 0)
           else task_award
         end as award, 
         ifnull(tapl_finish, 0) as finish, ifnull(tapl_state, 0) as state
  from task
  left join task_player on tapl_agentid = agentid
                       and tapl_playerid = playerid
                       and tapl_taskid = task_taskid
  where task_agentid = agentid
    and ((task_type in (0, 2, 3))
      or (task_type = 1 and
          (task_begintime is null or now() >= task_begintime) and
          (task_endtime   is null or now() <= task_endtime)
         ) 
        )
  order by task.idx; 
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_topup_card
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_topup_card`;
delimiter ;;
CREATE PROCEDURE `cp_game_topup_card`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `cardno` varchar(50) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '充值卡充值'
label_cp: begin
  declare result tinyint(1);   -- 0:成功  >0:失败 
  declare error  varchar(100); -- 失败描述
  declare cardstate  tinyint(1);
  declare cardtype   tinyint(1);
  declare cardamount int(11);

  set result = 0;
  set error  = '';
  set cardstate  = null;
  
  if not exists(select 1 from agent where agen_agentid = agentid limit 1) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if not exists(select 1 from player where play_agentid = agentid and play_playerid = playerid limit 1) then
    set result = 2;
    set error  = '参数错误：玩家id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  select toca_state into cardstate from topup_card where toca_cardno = cardno;
  if isnull(cardstate) then
    set result = 3;
    set error  = '充值失败：卡号不存在';
    select result, error;
    leave label_cp;
  end if;  
  
  if cardstate = 1 then
    set result = 4;
    set error  = '充值失败：该卡号已使用';
    select result, error;
    leave label_cp;
  end if;  
  
  set cardtype   = substring(cardno, 33, 1);
  set cardamount = substring(cardno, 34, 20);
  
  if cardtype = 0 then
    update player set play_roomcard = play_roomcard + cardamount
    where play_agentid = agentid and play_playerid = playerid
    limit 1;  
  elseif cardtype = 1 then 
    update player set play_bean = play_bean + cardamount
    where play_agentid = agentid and play_playerid = playerid
    limit 1;    
  end if;
  
  update topup_card
  set toca_usetime = now(), toca_agentid = agentid, toca_playerid = playerid, toca_state =1 
  where toca_cardno = cardno;
   
  select result, error, player.*
  from player
  where play_agentid = agentid 
    and play_playerid = playerid
  limit 1;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_update_bean
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_update_bean`;
delimiter ;;
CREATE PROCEDURE `cp_game_update_bean`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `deduct` int(8) ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '修改玩家豆豆数量'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 
  declare bean     int(8);
  
  set result = 0;
  if not exists(select 1 from agent where agen_agentid = agentid) then 
    set result = 1;
    set error  = 'agentid不存在';
    select result, error;
    leave label_cp;
  end if; 
  
  set bean = null;
  select play_bean into bean from player 
  where play_agentid = agentid and play_playerid = playerid limit 1;
  if isnull(bean) then 
    set result = 1;
    set error  = 'player不存在';
    select result, error;
    leave label_cp;  
  end if; 
  
--  if (-1 * deduct > bean) then
--    set result = 1;
--    set error  = '数量不够';
--    select result, error;
--    leave label_cp;    
--  end if;

  update player set play_bean = play_bean + deduct
  where play_agentid = agentid 
    and play_playerid = playerid limit 1;
 
  select result, playerid, play_bean as bean, deduct
  from player 
  where play_agentid = agentid and play_playerid = playerid limit 1;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_update_coinrebate
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_update_coinrebate`;
delimiter ;;
CREATE PROCEDURE `cp_game_update_coinrebate`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `mode1` tinyint(1) ,IN `set1` int(11) ,IN `mode2` tinyint(1) ,IN `set2` int(11))
  SQL SECURITY INVOKER
  COMMENT '设置星星场系统抽成'
label_cp: begin
  declare result tinyint(1);   -- 0:成功  >0:失败 
  declare error  varchar(100); -- 失败描述    
  set result = 0;
     
  -- 检验agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error = '运营商id不存在';
    select result, error;
    leave label_cp;
  end if;  
   
  update agent set agen_rebatemode1 = mode1,
                   agen_rebateset1 = set1,
                   agen_rebatemode2 = mode2,
                   agen_rebateset2 = set2
  where agen_agentid = agentid limit 1;

  -- 返回执行结果 
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_update_pond
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_update_pond`;
delimiter ;;
CREATE PROCEDURE `cp_game_update_pond`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `pondid` int(11) ,IN `amount` int(11))
  SQL SECURITY INVOKER
  COMMENT '获取玩家绑定的邀请码'
begin   
  if exists(select 1 from agent_game_pond where aggp_agentid = agentid and aggp_gameid = gameid and aggp_pondid = pondid) then
    update agent_game_pond set aggp_value = aggp_value + amount 
    where aggp_agentid = agentid and aggp_gameid = gameid and aggp_pondid = pondid;
  else 
    insert into agent_game_pond(aggp_agentid, aggp_gameid, aggp_pondid, aggp_value)
    values (agentid, gameid, pondid, amount);
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_game_update_roomcard
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_game_update_roomcard`;
delimiter ;;
CREATE PROCEDURE `cp_game_update_roomcard`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `deduct` int(8))
  SQL SECURITY INVOKER
  COMMENT '修改玩家房卡数量'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 
  declare roomcard int(8);
  
  set result = 0;
  if not exists(select 1 from agent where agen_agentid = agentid) then 
    set result = 1;
    set error  = 'agentid不存在';
    select result, error;
    leave label_cp;
  end if; 
  
  set roomcard = null;
  select play_roomcard into roomcard from player 
  where play_agentid = agentid and play_playerid = playerid limit 1;
  if isnull(roomcard) then 
    set result = 1;
    set error  = 'player不存在';
    select result, error;
    leave label_cp;  
  end if; 
  
  if (-1 * deduct > roomcard) then
    set result = 1;
    set error  = '数量不够';
    select result, error;
    leave label_cp;    
  end if;

  update player set play_roomcard = play_roomcard + deduct
  where play_agentid = agentid 
    and play_playerid = playerid limit 1;
  
  select result, playerid, play_roomcard as roomcard, deduct
  from player 
  where play_agentid = agentid and play_playerid = playerid limit 1;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_platform_get_agentchannel
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_platform_get_agentchannel`;
delimiter ;;
CREATE PROCEDURE `cp_platform_get_agentchannel`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取代理商的渠道商的公众号配置'
begin
  if not exists (select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    select agch_channelid, agch_sales_tel, agch_sales_wechat, agch_youle_appid, agch_youle_devkey, agch_youle_busiid 
    from agent_channel
    where agch_agentid = agentid
    order by idx limit 1;
  else
    select agch_channelid, agch_sales_tel, agch_sales_wechat, agch_youle_appid, agch_youle_devkey, agch_youle_busiid 
    from agent_channel
    where agch_agentid = agentid
      and agch_channelid = channelid;
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_platform_get_agentserver
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_platform_get_agentserver`;
delimiter ;;
CREATE PROCEDURE `cp_platform_get_agentserver`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取代理商的服务器地址和端口号'
begin
  if not exists (select 1 from agent where agen_agentid = agentid) then
    select agen_agentid, agen_name, agen_logo, agen_server, agen_server_visitor, agen_port_tcp,  
           agen_port_http, agen_managecode 
    from agent
    order by idx limit 1;
  else
    select agen_agentid, agen_name, agen_logo, agen_server, agen_server_visitor, agen_port_tcp,
           agen_port_http, agen_managecode 
    from agent 
    where agen_agentid = agentid;
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_platform_get_appversion
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_platform_get_appversion`;
delimiter ;;
CREATE PROCEDURE `cp_platform_get_appversion`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取app最新版本和下载地址'
begin
  -- 获取渠道商id
  if not exists (select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    select agch_channelid into channelid from agent_channel where agch_agentid = agentid order by idx limit 1;
  end if; 
  
  select agga_android_ver  as android_ver,
         agga_android_down as android_down,
         agga_ios_ver      as ios_ver,
         agga_ios_down     as ios_down
  from agent_game
  where agga_agentid = agentid
    and agga_gameid = gameid
    and agga_channelid = channelid;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_platform_get_gameversion
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_platform_get_gameversion`;
delimiter ;;
CREATE PROCEDURE `cp_platform_get_gameversion`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `vers` int(11))
  SQL SECURITY INVOKER
  COMMENT '获取游戏最新版本和下载地址'
begin
  select * from agent_game_version 
  where aggv_agentid = agentid
    and aggv_gameid = gameid
    and aggv_channelid = channelid
    and aggv_version > vers
  order by aggv_version;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_report_agent_day
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_report_agent_day`;
delimiter ;;
CREATE PROCEDURE `cp_report_agent_day`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `opt` tinyint(1) ,IN `amount` decimal(10,2))
  SQL SECURITY INVOKER
  COMMENT '统计代理商的日报表'
begin
  declare _day varchar(50);  -- 当前日期
  select date_format(now(), "%Y-%m-%d") into _day;
  
  if not exists(select 1 from report_agent_day where read_agentid = agentid and read_day = _day) then
    insert into report_agent_day(read_agentid, read_day) values(agentid, _day);
  end if;
  
  if opt = 0 then     -- 新增玩家数量
    update report_agent_day 
    set read_newplayer = read_newplayer + amount 
    where read_agentid = agentid and read_day = _day limit 1;
  elseif opt = 1 then -- 新增个人代理数量
    update report_agent_day 
    set read_newsalesman = read_newsalesman + amount 
    where read_agentid = agentid and read_day = _day limit 1;
  elseif opt = 2 then -- 玩家得到的奖励房卡数量 
    update report_agent_day 
    set read_playeraward = read_playeraward + amount 
    where read_agentid = agentid and read_day = _day limit 1;
  elseif opt = 3 then -- 房卡销售金额
    update report_agent_day 
    set read_salesmoney = read_salesmoney + amount 
    where read_agentid = agentid and read_day = _day limit 1;  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_report_game_day
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_report_game_day`;
delimiter ;;
CREATE PROCEDURE `cp_report_game_day`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `reportday` datetime ,IN `opt` tinyint(1) ,IN `amount` decimal(10,2) ,IN `maxtime` datetime)
  SQL SECURITY INVOKER
  COMMENT '统计代理商的日报表'
begin
  declare _day varchar(50);  -- 当前日期
  select date_format(reportday, "%Y-%m-%d") into _day;
  
  if not exists(select 1 from report_game_day where regd_agentid = agentid and regd_gameid = gameid and regd_day = _day) then
    insert into report_game_day(regd_agentid, regd_gameid, regd_day) values(agentid, gameid, _day);
  end if;
  
  if opt = 0 then     -- 新增玩家数量
    update report_game_day 
    set regd_newplayer = regd_newplayer + amount 
    where regd_agentid = agentid and regd_gameid = gameid and regd_day = _day limit 1;
  elseif opt = 1 then -- 消耗房卡数量
    update report_game_day 
    set regd_useroomcard = regd_useroomcard + amount 
    where regd_agentid = agentid and regd_gameid = gameid and regd_day = _day limit 1;
  elseif opt = 2 then -- 玩家一共玩了多少游戏局（大局）
    update report_game_day 
    set regd_asetcount = regd_asetcount + amount 
    where regd_agentid = agentid and regd_gameid = gameid and regd_day = _day limit 1;
  elseif opt = 3 then -- 最大在线玩家数量  
    update report_game_day 
    set regd_maxplayer = amount, regd_maxplayertime = maxtime 
    where regd_agentid = agentid and regd_gameid = gameid and regd_day = _day limit 1; 
  elseif opt = 4 then -- 最大开房数量
  
    update report_game_day 
    set regd_maxroom = amount, regd_maxroomtime = maxtime 
    where regd_agentid = agentid and regd_gameid = gameid and regd_day = _day limit 1;     
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_change_bank
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_change_bank`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_change_bank`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `pwd` varchar(10) charset utf8 collate utf8_general_ci ,IN `newplayerid` int(8) ,IN `oldplayerid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0变更代理id'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 
  
  declare oldBank int(11);
  declare oldPwd  varchar(10);

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  
  
  
  if exists(select 1 from player where play_agentid = agentid and play_playerid = oldplayerid) then
    if exists(select 1 from player where play_agentid = agentid and play_playerid = newplayerid) then  
       
       
	   select play_bankpwd ,play_bank
		into oldPwd ,oldBank
		from player 
		where play_agentid = agentid and play_playerid = oldplayerid;
		
		if oldPwd = pwd then 
			update player n, player o   	   
			   set n.play_bean = if(isnull(n.play_bean), 0, n.play_bean) + if(o.play_bankpwd = pwd, if(isnull(o.play_bank), 0, o.play_bank), 0)
			   
		    where n.play_agentid = agentid
				 and n.play_playerid = newplayerid
				 and o.play_agentid = agentid
				 and o.play_playerid = oldplayerid;
			update player 
				set play_bank = 0
				where play_agentid = agentid
				and play_playerid = oldplayerid;
		else
			set result = 1;
			set error  = '密码错误';
			select result, error;
			leave label_cp;
		end if;
		
		
	
       
    end if;
  end if;
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_change_salesid
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_change_salesid`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_change_salesid`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `oldsalesid` int(8) ,IN `newsalesid` int(8) ,IN `oldplayerid` int(8) ,IN `newplayerid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0变更代理id'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 
  
  declare initCard int(8);
  declare initBean int(8);
  
  declare oldCard int(8);
  declare oldBean int(8);

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  select agen_initroomacard , agen_initbean
	into initCard , initBean
	from agent 
	where agen_agentid = agentid;
  
  if exists(select 1 from sales_user where saus_agentid = agentid and saus_salesid = oldsalesid) then
    if exists(select 1 from sales_user where saus_agentid = agentid and saus_salesid = newsalesid) then
      update player 
      set play_invitecode = newsalesid 
      where play_agentid = agentid
        and play_invitecode = oldsalesid;
    end if;
  end if;
  
  if exists(select 1 from player where play_agentid = agentid and play_playerid = oldplayerid) then
    if exists(select 1 from player where play_agentid = agentid and play_playerid = newplayerid) then      
       update player n, player o   
       set n.play_roomcard = if(isnull(n.play_roomcard), 0, n.play_roomcard) + if(isnull(o.play_roomcard), 0, if(o.play_roomcard > initCard,o.play_roomcard - initCard,0)),
           n.play_bean = if(isnull(n.play_bean), 0, n.play_bean) + if(isnull(o.play_bean), 0, if(o.play_bean > initBean ,o.play_bean - initBean,0))
		   
       where n.play_agentid = agentid
         and n.play_playerid = newplayerid
         and o.play_agentid = agentid
         and o.play_playerid = oldplayerid;
       
	   select play_roomcard , play_bean
			into oldCard , oldBean
			from player 
		where play_agentid = agentid and play_playerid = oldplayerid;
		
		if oldCard > initCard then 
			set oldCard = initCard;
		end if;
		
		if oldBean > initBean then 
			set oldBean = initBean;
		end if;
	
       update player 
        set play_roomcard = oldCard, play_bean = oldBean
	   -- set play_roomcard = 0, play_bean = 0
       where play_agentid = agentid
         and play_playerid = oldplayerid;
    end if;
  end if;
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_disbinding_player
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_disbinding_player`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_disbinding_player`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0玩家解除绑定'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if not exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) then
    set result = 2;
    set error  = '参数错误：玩家id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  update player set play_invitecode = null where play_agentid = agentid and play_playerid = playerid;
  
  update sales_user, player 
  set saus_invitecode = null 
  where saus_agentid =  agentid
    and play_agentid = agentid
    and play_playerid = playerid
    and saus_unionid = play_unionid;
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_disbinding_sales
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_disbinding_sales`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_disbinding_sales`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `salesid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0解除绑定了我的玩家'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if not exists(select 1 from sales_user where saus_agentid = agentid and saus_salesid = salesid) then
    set result = 2;
    set error  = '参数错误：代理id不存在';
    select result, error;
    leave label_cp;
  end if;

  update sales_user, player 
  set saus_invitecode = null 
  where saus_agentid =  agentid
    and play_agentid = agentid
    and play_invitecode = salesid
    and saus_unionid = play_unionid;
    
  update player set play_invitecode = null where play_agentid = agentid and play_invitecode = salesid;   
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_new_salesman
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_new_salesman`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_new_salesman`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `nickname` varchar(100) charset utf8 collate utf8_general_ci ,IN `avatar` varchar(200) charset utf8 collate utf8_general_ci ,IN `sex` tinyint(1) ,IN `province` varchar(100) charset utf8 collate utf8_general_ci ,IN `city` varchar(100) charset utf8 collate utf8_general_ci ,IN `salesid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0新增代理接口'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if exists(select 1 from sales_user where saus_agentid = agentid and saus_salesid = salesid) then
    set result = 2;
    set error  = '参数错误：代理id已存在';
    select result, error;
    leave label_cp;
  end if;
    
  if exists(select 1 from sales_user where saus_agentid = agentid and saus_unionid = unionid) then
    update sales_user set saus_salesman = 1, saus_salesid = salesid 
    where saus_agentid = agentid and saus_unionid = unionid;  
  else
    insert into sales_user(saus_agentid, saus_channelid, saus_openid, saus_unionid, 
      saus_nickname, saus_avatar, saus_sex, saus_province, saus_city, saus_salesman, saus_salesid)
    values(agentid, channelid, openid, unionid, nickname, avatar, sex, province, city, 1, salesid);    
  end if;  
  
  update agent set agen_maxsalesid = salesid where agen_agentid = agentid;
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_player_abled
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_player_abled`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_player_abled`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0解封玩家'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if not exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) then
    set result = 2;
    set error  = '参数错误：玩家id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  update player set play_state = 0 where play_agentid = agentid and play_playerid = playerid;
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_player_bindinginvitecode
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_player_bindinginvitecode`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_player_bindinginvitecode`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `invitecode` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0玩家绑定邀请码接口'
label_cp: begin
  declare result      tinyint(1);   -- 0:成功  >0:失败 
  declare error       varchar(100); -- 失败描述 
  declare playerid    int(8);
  declare salesstatus tinyint(1);

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  select play_playerid into playerid from player where play_agentid = agentid and play_unionid = unionid; 
  if isnull(playerid) then
    set result = 2;
    set error  = '参数错误：玩家不存在';
    select result, error;
    leave label_cp;
  end if;
  
  select saus_status into salesstatus from sales_user where saus_agentid = agentid and saus_salesid = invitecode;
  if isnull(salesstatus) then
    set result = 3;
    set error  = '参数错误：邀请码不存在';
    select result, error;
    leave label_cp;
  elseif salesstatus = 1 then
    set result = 4;
    set error  = '参数错误：邀请码已经被封禁';
    select result, error;    
  end if; 
  
  update player set play_invitecode = invitecode
  where play_agentid = agentid
    and play_unionid = unionid;
                  
  -- 完成绑定邀请码任务
  call cp_game_task_finish(agentid, playerid, 'UEFsfbv29YnlacKLo0mjomK48Bv82hGv', 1, 0);
  
  select result, error, playerid;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_player_disabled
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_player_disabled`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_player_disabled`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0封禁玩家'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if not exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) then
    set result = 2;
    set error  = '参数错误：玩家id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  update player set play_state = 1 where play_agentid = agentid and play_playerid = playerid;
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_player_topup
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_player_topup`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_player_topup`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `topup_card` int(10) ,IN `topup_bean` int(10))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0玩家充值接口'
label_cp: begin
  declare result tinyint(1);   -- 0:成功  >0:失败 
  declare error  varchar(100); -- 失败描述 

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if not exists(select 1 from player where play_agentid = agentid and play_playerid = playerid) then
    set result = 2;
    set error  = '参数错误：玩家id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if isnull(topup_card) then
    set topup_card = 0;
  end if;
  
  if isnull(topup_bean) then
    set topup_bean = 0;
  end if;  
  
  update player set play_roomcard = play_roomcard + topup_card,
                    play_bean = play_bean + topup_bean 
  where play_agentid = agentid 
    and play_playerid = playerid;
  
  select result, error, player.*
  from player
  where play_agentid = agentid 
    and play_playerid = playerid;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_salesman_abled
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_salesman_abled`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_salesman_abled`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `salesid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0解封代理接口'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if not exists(select 1 from sales_user where saus_agentid = agentid and saus_salesid = salesid) then
    set result = 2;
    set error  = '参数错误：代理id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  update sales_user set saus_status = 0 where saus_agentid = agentid and saus_salesid = salesid;
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales2_salesman_disabled
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales2_salesman_disabled`;
delimiter ;;
CREATE PROCEDURE `cp_sales2_salesman_disabled`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `salesid` int(8))
  SQL SECURITY INVOKER
  COMMENT '代理后台2.0封禁代理接口'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述 

  set result = 0;
  set error  = '';
  
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '参数错误：运营商id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if not exists(select 1 from sales_user where saus_agentid = agentid and saus_salesid = salesid) then
    set result = 2;
    set error  = '参数错误：代理id不存在';
    select result, error;
    leave label_cp;
  end if;
  
  update sales_user set saus_status = 1 where saus_agentid = agentid and saus_salesid = salesid;
  
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_accept_award
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_accept_award`;
delimiter ;;
CREATE PROCEDURE `cp_sales_accept_award`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `awardid` int(11))
  SQL SECURITY INVOKER
  COMMENT '领取奖励'
label_cp: begin
  declare result     tinyint(1);   -- 0:成功  >0:失败 
  declare error      varchar(100); -- 失败描述 
  declare mysalesid  int(8);       -- 我的代理id
  declare award      int(11);      -- 奖励的房卡数量
  declare awardstate tinyint(1);   -- 奖励状态 
  declare myroomcard int(11);      -- 领取后我的房卡数量
  declare mystate    tinyint(1);   -- 领取后我的奖励状态 0无奖励 1有奖励可领取
  
  set result = 0;
  -- 获取我的代理id
  select saus_salesid into mysalesid
  from sales_user 
  where saus_agentid = agentid
    and saus_openid = openid;
    
  -- 检查奖励是否存在
  if not exists(select 1 from sales_award
                where saaw_agentid = agentid
                  and saaw_salesid = mysalesid
                  and idx = awardid) then
    set result = 1;
    set error = '奖励不存在';
    select result, error;
    leave label_cp;            
  end if;     
  
  -- 获取奖励的房卡数量和状态
  select saaw_award, saaw_state into award, awardstate 
  from sales_award
  where saaw_agentid = agentid
    and saaw_salesid = mysalesid
    and idx = awardid;
    
  if awardstate = 1 then
    set result = 2;
    set error = '奖励已领取过，不能重复领取';
    select result, error;
    leave label_cp;            
  end if;
  
  -- 修改领取状态
  update sales_award set saaw_state = 1, saaw_gettime = now()
  where saaw_agentid = agentid
    and saaw_salesid = mysalesid
    and idx = awardid;
      
  -- 修改房卡
  update sales_user set saus_roomcard = saus_roomcard + award
  where saus_agentid = agentid
    and saus_openid = openid;
  
  -- 获取领取后我的房卡数量
  select saus_roomcard into myroomcard
  from sales_user
  where saus_agentid = agentid
    and saus_openid = openid;
  
  -- 获取领取后我的奖励状态
  if exists(select 1 from sales_award 
            where saaw_agentid = agentid
              and saaw_salesid = mysalesid
              and saaw_state = 0) then
    set mystate = 1;
  else
    set mystate = 0;
  end if;   
  
  select result, error, myroomcard, mystate;    
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_apply_sales
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_apply_sales`;
delimiter ;;
CREATE PROCEDURE `cp_sales_apply_sales`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `wechat` varchar(50) charset utf8 collate utf8_general_ci ,IN `tel` varchar(20) charset utf8 collate utf8_general_ci ,IN `inivtecode` int(8))
  SQL SECURITY INVOKER
  COMMENT '申请为个人代理'
label_cp: begin
  declare result       tinyint(1);   -- 0:成功  >0:失败 
  declare error        varchar(100); -- 失败描述
  declare salesman     tinyint(1);   -- 微信公众号用户是否是个人代理
  declare salesid      int(8);       -- 新代理id
  declare salespower   varchar(10);  -- 默认的个人代理权限
  declare parentid     int(8);       -- 父亲代理id
  
  set result = 0;
     
  -- 检验agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then 
    set result = 1;
    set error = '运营商id不存在';
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验微信公众号用户
  select saus_salesman into salesman 
  from sales_user
  where saus_agentid = agentid and saus_openid = openid;
  if isnull(salesman) then 
    set result = 2;
    set error = '用户不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if salesman = 1 then
    set result = 3;
    set error = '您已经是代理了，无需再次申请';
    select result, error;
    leave label_cp;  
  end if;

  -- 新个人代理
  update agent set agen_maxsalesid = agen_maxsalesid + floor(rand() * (12-6) + 6) where agen_agentid = agentid;
 
  select agen_maxsalesid, agen_salespower
  into salesid, salespower 
  from agent 
  where agen_agentid = agentid;
  
  if isnull(inivtecode) or (inivtecode = '') or (inivtecode = 0) then
    set parentid = null;
  else
    select saus_salesid into parentid
    from sales_user
    where saus_agentid = agentid and saus_salesid = inivtecode;
  end if;      
  
  if openid = 'oIv1dwGjgqhngUd3fkJa5Zlc13zE' then
    update sales_user set saus_salesman = 1, saus_salesid = salesid,
                          saus_saletime = now(), saus_salestype = 1, 
                          saus_wechat = wechat, saus_tel = tel,
                          saus_power = salespower,  saus_parentid = parentid,
                          saus_roomcard = 100000, saus_power = '22'
    where saus_agentid = agentid and saus_openid = openid;
  else
    update sales_user set saus_salesman = 1, saus_salesid = salesid,
                          saus_saletime = now(), saus_salestype = 1, 
                          saus_wechat = wechat, saus_tel = tel,
                          saus_power = salespower,  saus_parentid = parentid
    where saus_agentid = agentid and saus_openid = openid;
  end if;
  
  -- 按日期统计新增个人代理人数
  call cp_report_agent_day(agentid, 1, 1);

  
  -- 返回执行结果 
  select result, error, parentid as inivtecode;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_ask_dealbill
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_ask_dealbill`;
delimiter ;;
CREATE PROCEDURE `cp_sales_ask_dealbill`(IN `_idx` int(11) ,IN `dealid` int(8) ,IN `dealstate` tinyint(1))
  SQL SECURITY INVOKER
  COMMENT '处理索要房卡订单'
label_cp: begin
  declare result   tinyint(1);   -- 0:成功  >0:失败 
  declare error    varchar(100); -- 失败描述
  declare agentid  varchar(32);
  declare billtype tinyint(1);
  declare askid    int(8);
  declare salesid  int(8);
  declare amount   int(8);
  declare salesroomcard int(11); -- 受理者的房卡数量
  declare askerroomcard int(11); -- 索取者的房卡数量
  
  set result = 0;
  
  -- 检验订单是否存在
  set agentid = null;
  
  select saab_agentid, saab_type, saab_askid, saab_salesid, saab_amount
  into agentid, billtype, askid, salesid, amount
  from sales_ask_bill
  where idx = _idx;
  
  if isnull(agentid) then
    set result = 1;
    set error = '订单不存在';
    select result, error;
    leave label_cp;
  end if;
  
  if dealstate = 1 then
    -- 充卡数量不能是负数
    if amount < 0 then
      set result = 2;
      set error = '充卡数量必须大于0';
      select result, error;
      leave label_cp;  
    end if;   
  
    -- 检验个人代理的房卡数量是否够
    set salesroomcard = 0;
    select saus_roomcard 
    into salesroomcard 
    from sales_user 
    where saus_agentid = agentid
      and saus_salesman = 1
      and saus_salesid = salesid;
    
    if (salesroomcard = 0) or (salesroomcard < amount) then
      set result = 3;
      set error = '房卡数量不足';
      select result, error;
      leave label_cp;  
    end if; 
  end if;
  
  if (dealstate = 1 or dealstate = 3) then
    if dealid <> salesid then
      set result = 4;
      set error = '无此订单的操作权限';
      select result, error;
      leave label_cp;  
    end if;
  elseif dealstate = 2 then
    if dealid <> askid then
      set result = 5;
      set error = '无此订单的操作权限';
      select result, error;
      leave label_cp;  
    end if;  
  end if;
  
  -- 修改订单状态
  update sales_ask_bill set saab_state = dealstate, saab_dealtime = now() where idx = _idx; 
  
  -- 充卡
  if dealstate = 1 then
    if billtype = 0 then -- 玩家
      update player set play_roomcard = play_roomcard + amount where play_agentid = agentid and play_playerid = askid;      
      select play_roomcard into askerroomcard from player where play_agentid = agentid and play_playerid = askid;
    elseif billtype = 1 then -- 个人代理
      update sales_user set saus_roomcard = saus_roomcard + amount where saus_agentid = agentid and saus_salesid = askid;      
      select saus_roomcard into askerroomcard from sales_user where saus_agentid = agentid and saus_salesid = askid;
    end if; 
    update sales_user set saus_roomcard = saus_roomcard - amount where saus_agentid = agentid and saus_salesid = salesid; 
    select saus_roomcard into salesroomcard from sales_user where saus_agentid = agentid and saus_salesid = salesid; 
    
    select result, error, agentid, askid, amount, askerroomcard, salesroomcard;
  else
    select result, error; 
  end if;  
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_ask_getmyaskbill
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_ask_getmyaskbill`;
delimiter ;;
CREATE PROCEDURE `cp_sales_ask_getmyaskbill`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `billtype` tinyint(1) ,IN `askid` int(8))
  SQL SECURITY INVOKER
  COMMENT '获取我发起的索要房卡订单列表'
begin  
  select idx, saab_asktime as asktime, saab_amount as amount, saab_state as state, 
         case saab_state
           when 0 then 0
           else 1
         end as stateidx         
  from sales_ask_bill
  where saab_agentid = agentid
    and saab_type = billtype
    and saab_askid = askid
  order by stateidx, asktime desc
  limit 50;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_ask_getmydealbill
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_ask_getmydealbill`;
delimiter ;;
CREATE PROCEDURE `cp_sales_ask_getmydealbill`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `billtype` tinyint(1) ,IN `salesid` int(8))
  SQL SECURITY INVOKER
  COMMENT '获取我受理的索要房卡订单列表'
begin  
  select idx, saab_asktime as asktime, saab_amount as amount, saab_state as state, 
         case saab_state
           when 0 then 0
           else 1
         end as stateidx,
         saab_askid as askid, saab_asknickname as nickname, saab_askavatar as avatar
  from sales_ask_bill
  where saab_agentid = agentid
    and saab_type = billtype
    and saab_salesid = salesid
  order by stateidx, asktime desc
  limit 100;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_ask_newbill
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_ask_newbill`;
delimiter ;;
CREATE PROCEDURE `cp_sales_ask_newbill`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `billtype` tinyint(1) ,IN `askid` int(8) ,IN `amount` int(8))
  SQL SECURITY INVOKER
  COMMENT '新建索要房卡订单'
label_cp: begin
  declare result      tinyint(1);   -- 0:成功  >0:失败 
  declare error       varchar(100); -- 失败描述 
  declare asknickname varchar(100); -- 发起者昵称
  declare askavatar   varchar(200); -- 发起者头像
  declare invitecode  int(8);       -- 已经绑定的邀请码  
  
  set result = 0;  
  set invitecode = null; 
  
  if billtype = 0 then
    select play_nickname, play_avatar, play_invitecode 
    into asknickname, askavatar, invitecode 
    from player 
    where play_agentid = agentid
      and play_playerid = askid;
  elseif billtype = 1 then  
    select saus_nickname, saus_avatar, saus_parentid 
    into asknickname, askavatar, invitecode
    from sales_user 
    where saus_agentid = agentid
      and saus_salesman = 1
      and saus_salesid = askid;
  end if;
  if isnull(invitecode) then
    set result = 1;
    set error = '索要房卡失败：未绑定邀请码';
    select result, error;
    leave label_cp;
  end if;
  
  insert into sales_ask_bill(saab_agentid, saab_type, saab_askid, saab_asknickname,
    saab_askavatar, saab_salesid, saab_amount, saab_state, saab_asktime)
  values(agentid, billtype, askid, asknickname, askavatar, invitecode, amount, 0, now());
  
  select result, error; 
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_ask_player_getsalesman
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_ask_player_getsalesman`;
delimiter ;;
CREATE PROCEDURE `cp_sales_ask_player_getsalesman`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8))
  SQL SECURITY INVOKER
  COMMENT '玩家获取自己所属的个人代理信息'
begin  
  select saus_salesid as sales_id, saus_wechat as sales_wechat, 
         saus_tel as sales_tel, saus_nickname as sales_nickname, 
         saus_avatar as sales_avatar
  from player, sales_user 
  where play_agentid = agentid 
    and play_playerid = playerid
    and play_invitecode is not null
    and saus_agentid = agentid
    and saus_salesman = 1 
    and saus_salesid = play_invitecode;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_ask_sales_getparentman
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_ask_sales_getparentman`;
delimiter ;;
CREATE PROCEDURE `cp_sales_ask_sales_getparentman`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `salesid` int(8))
  SQL SECURITY INVOKER
  COMMENT '个人代理获取自己的上级代理信息'
begin  
  select u2.saus_salesid as sales_id, u2.saus_wechat as sales_wechat, 
         u2.saus_tel as sales_tel, u2.saus_nickname as sales_nickname, 
         u2.saus_avatar as sales_avatar
  from sales_user as u1, sales_user as u2
  where u1.saus_agentid = agentid 
    and u1.saus_salesman = 1 
    and u1.saus_salesid = salesid
    and u1.saus_parentid is not null
    and u2.saus_agentid = agentid
    and u2.saus_salesman = 1 
    and u2.saus_salesid = u1.saus_parentid;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_binding_parent
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_binding_parent`;
delimiter ;;
CREATE PROCEDURE `cp_sales_binding_parent`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `salesid` int(8))
  SQL SECURITY INVOKER
  COMMENT '绑定我的推荐人'
label_cp: begin
  declare result     tinyint(1); -- 0:成功  >0:失败 
  declare error      varchar(100);
  declare mysalesid  int(8);     -- 我的代理id
  declare myparentid int(8);     -- 我的上级代理id  
  declare pid        int(8);     -- 推荐人的上级代理id
  declare ppid       int(8);     -- 推荐人的上级的上级代理id
  declare i int; 
  
  declare _salesid  int(8); 
	declare wechat    varchar(100);
	declare tel       varchar(50);
	declare nickname  varchar(100);
	declare avatar    varchar(200);
  
  set result = 0;
  
  -- 检查推荐人是否存在
  set _salesid = null;
  select saus_salesid, saus_nickname, saus_avatar, saus_wechat, saus_tel
  into _salesid, nickname, avatar, wechat, tel
  from sales_user 
  where saus_agentid = agentid 
    and saus_salesid = salesid;
  if isnull(_salesid) then
    set result = 1;
    set error = '邀请码不存在';
    select result, error;
    leave label_cp;
  end if; 
 
  -- 获取我的代理id
  select saus_salesid, saus_parentid into mysalesid, myparentid
  from sales_user 
  where saus_agentid = agentid
    and saus_openid = openid
    and saus_salesman = 1; 
    
  -- 检查我是否已经是代理
  if isnull(mysalesid) then
    set result = 5;
    set error = '您还不是代理，请先申请成为代理再绑定邀请码';
    select result, error;
    leave label_cp;
  end if;     
    
  -- 检查是否已经绑定了邀请码
  if isnull(myparentid) then
    -- 不能绑自己
    if mysalesid = salesid then
      set result = 1;
      set error = '不能绑定自己的邀请码';
      select result, error;
      leave label_cp;
    end if;
  
    -- 检查推荐人的上级代理是否有我  
    set i = 0;
    set pid = salesid;
    label_wh: while i < 2 do
      select saus_parentid into ppid from sales_user where saus_agentid = agentid and saus_salesid = pid;
      
      if isnull(ppid) then
        leave label_wh;
      elseif ppid = mysalesid then
        set result = 1;
        set error = '不能绑定自己下级的邀请码';
        select result, error;
        leave label_cp;  
      end if;
      set i = i + 1;
      set pid = ppid;
    end while; 
    
    -- 检查通过后修改我的推荐人
    update sales_user set saus_parentid = salesid 
    where saus_agentid = agentid
      and saus_openid = openid;
    
    -- 如果是第一次绑定则添加推荐人的奖励
    if isnull(myparentid) then
      call cp_sales_new_award(agentid, salesid, mysalesid, 0, null);   
    end if;   
  
    select result, salesid, wechat, tel, nickname, avatar;
  else
    set result = 2;
    set error  = '已经绑定过上级代理，不能再次绑定';  
    
    select saus_salesid, saus_nickname, saus_avatar, saus_wechat, saus_tel
    into salesid, nickname, avatar, wechat, tel
    from sales_user 
    where saus_agentid = agentid 
      and saus_salesid = myparentid;
      
    select result, error, salesid, wechat, tel, nickname, avatar;  
  end if; 
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_finish_task
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_finish_task`;
delimiter ;;
CREATE PROCEDURE `cp_sales_finish_task`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `opneid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `taskid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '根据unionid判断是否完成了相关任务'
begin
  declare playerid varchar(32);
  
  if isnull(unionid) then
    select saus_unionid into unionid from sales_user where saus_agentid = agentid and saus_openid = opneid;
  end if;
  
  if not isnull(unionid) then
    select play_playerid into playerid from player where play_agentid = agentid and play_unionid = unionid;
    if not isnull(playerid) then
      call cp_game_task_finish(agentid, playerid, taskid, 1, 0);  
    end if;
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_award
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_award`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_award`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取我的奖励列表'
begin
  select sales_award.idx as awardid, saaw_type as type, saaw_childid as childid, 
         c.saus_nickname as childname, c.saus_avatar as childavatar, saaw_award as award, 
         saaw_state as state, saaw_createtime as awardtime, saaw_gettime as gettime 
  from sales_user as i
  inner join sales_user as c on c.saus_agentid = agentid 
  inner join sales_award on saaw_agentid = agentid
                        and saaw_salesid = i.saus_salesid
                        and saaw_childid = c.saus_salesid
  where i.saus_agentid = agentid 
    and i.saus_openid = openid
    and i.saus_salesid is not null
  order by saaw_createtime desc;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_child
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_child`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_child`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取我的子代理'
begin
  select s2.saus_salesid as salesid, s2.saus_nickname as name, 
         s2.saus_avatar as avatar, ifnull(sum(saaw_award), 0) as awardtotal 
  from sales_user as s1
  inner join sales_user as s2 on s2.saus_agentid = agentid 
                             and s2.saus_parentid = s1.saus_salesid
  left join sales_award on saaw_agentid = agentid
                       and saaw_salesid = s1.saus_salesid
                       and saaw_childid = s2.saus_salesid
                       and saaw_state = 1
  where s1.saus_agentid = agentid 
    and s1.saus_openid = openid
    and s1.saus_salesid is not null
  group by salesid, name, avatar;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_gamelist
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_gamelist`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_gamelist`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取代理商的游戏列表及下载地址'
begin 
  if not exists (select 1 from agent where agen_agentid = agentid) then
    select agen_agentid into agentid from agent order by idx limit 1;
  end if;
  
  -- 获取渠道商id
  if not exists (select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    select agch_channelid into channelid from agent_channel where agch_agentid = agentid order by idx limit 1;
  end if; 
  
  select agga_aliasname as name, agga_image as image, agga_state as state,
	       agga_gamememo as memo, 
         agga_ios_down as ios_down, agga_ios_size as ios_size,
	       agga_android_down as android_down, agga_android_size as android_size
	from agent_game
  where agga_agentid = agentid
    and agga_channelid = channelid
  order by idx;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_invitecodeinfo
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_invitecodeinfo`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_invitecodeinfo`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取玩家绑定的邀请码的代理信息'
begin
  select p.saus_salesid, p.saus_nickname, p.saus_avatar
  from sales_user as i
  inner join sales_user as p on p.saus_agentid = agentid 
                            and p.saus_salesid is not null
                            and p.saus_salesid = i.saus_invitecode
  where i.saus_agentid = agentid 
    and i.saus_openid = openid;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_myplayer
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_myplayer`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_myplayer`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '绑定了我的邀请码的玩家列表'
begin
  declare salesid int(8);
  set salesid = null;
  
  select saus_salesid into salesid from sales_user 
  where saus_agentid = agentid and saus_openid = openid and saus_salesman = 1; 
  
  if not isnull(salesid) then
    select play_playerid as playerid, play_nickname as nickname, 
           play_avatar as avatar, ifnull(v.money, 0) as money
    from player
    left join (select sabu_agentid, sabu_playerid, sum(sabu_paymoney) as money
               from sales_buybill 
               where sabu_billtype = 0
                 and sabu_paystate = 1
                 and yearweek(date_format(sabu_paytime, '%Y-%m-%d')) = yearweek(now())
               group by sabu_agentid, sabu_playerid
               ) as v
      on v.sabu_agentid = play_agentid
     and v.sabu_playerid = play_playerid
    where play_agentid = agentid
      and play_invitecode = salesid
    order by playerid;  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_mysalesman
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_mysalesman`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_mysalesman`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '我的下级代理列表'
begin
  declare salesid int(8);
  set salesid = null;
  
  select saus_salesid into salesid from sales_user 
  where saus_agentid = agentid and saus_openid = openid and saus_salesman = 1; 
  
  if not isnull(salesid) then
    select s1.saus_salesid as salesid, s1.saus_nickname as nickname, s1.saus_avatar as avatar, 
           ifnull(v1.salesmancount, 0) as salesmancount,
           ifnull(v2.playercount, 0) as playercount
    from sales_user as s1
    left join (select s2.saus_parentid, count(1) as salesmancount
               from sales_user as s2
               where s2.saus_agentid = agentid
                 and s2.saus_salesman = 1
                 and s2.saus_parentid is not null
               group by s2.saus_parentid
               ) as v1 on v1.saus_parentid = s1.saus_salesid
    left join (select play_invitecode, count(1) as playercount
               from player
               where play_agentid = agentid
                 and play_invitecode is not null
               group by play_invitecode
               ) as v2 on v2.play_invitecode = s1.saus_salesid
    where s1.saus_agentid = agentid
      and s1.saus_salesman = 1
      and s1.saus_parentid = salesid;
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_parentinfo
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_parentinfo`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_parentinfo`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取我的推荐人信息'
begin
  select p.saus_salesid, p.saus_nickname, p.saus_avatar
  from sales_user as i
  inner join sales_user as p on p.saus_agentid = agentid 
                            and p.saus_salesid is not null
                            and p.saus_salesid = i.saus_parentid
  where i.saus_agentid = agentid 
    and i.saus_openid = openid
    and i.saus_salesid is not null;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_topupname
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_topupname`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_topupname`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取充卡名单'
begin
  select distinct(sase_playerid) as playerid, play_nickname as name, 
         play_avatar as avatar, 
         sum(sase_amount) as total, max(sase_selltime) as lastselltime
  from sales_sellbill
  inner join player on play_agentid = agentid
                   and play_playerid = sase_playerid
  where sase_agentid = agentid
    and sase_openid = openid
  group by playerid, name, avatar
  order by lastselltime desc;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_get_transfername
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_get_transfername`;
delimiter ;;
CREATE PROCEDURE `cp_sales_get_transfername`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取转卡名单'
begin
  select distinct(satr_salesid) as salesid, saus_nickname as name, 
         saus_avatar as avatar, 
         sum(satr_amount) as total, max(satr_transfertime) as lasttransfertime
  from sales_transferbill
  inner join sales_user on saus_agentid = agentid
                       and saus_salesid = satr_salesid
  where satr_agentid = agentid
    and satr_openid = openid
  group by salesid, name, avatar
  order by lasttransfertime desc;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_new_award
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_new_award`;
delimiter ;;
CREATE PROCEDURE `cp_sales_new_award`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `salesid` int(8) ,IN `childid` int(8) ,IN `type` tinyint(1) ,IN `billcode` varchar(50) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '添加推荐人奖励'
begin
  if type = 0 then
    insert into sales_award (saaw_agentid, saaw_salesid, saaw_childid, 
      saaw_type, saaw_award, saaw_state, saaw_createtime)
    values(agentid, salesid, childid, type, 100, 0, now());   
  else
    insert into sales_award (saaw_agentid, saaw_salesid, saaw_childid, 
      saaw_type, saaw_buybill, saaw_award, saaw_state, saaw_createtime)
    values(agentid, salesid, childid, type, billcode, 200, 0, now());
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_new_bill
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_new_bill`;
delimiter ;;
CREATE PROCEDURE `cp_sales_new_bill`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `billcode` varchar(100) charset utf8 collate utf8_general_ci ,IN `billtype` tinyint(1) ,IN `productid` varchar(32) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `tel` varchar(50) charset utf8 collate utf8_general_ci ,IN `wechat` varchar(50) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '新增一条购卡订单'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述 
  declare agentname      varchar(100); -- 代理商名称 
  declare username       varchar(100); -- 微信公众号用户昵称 
  declare usersalesman   tinyint(1);   -- 微信公众号用户是否是个人代理   
  declare productname    varchar(100); -- 产品名称
  declare productamount  int(11);      -- 产品的房卡数量
  declare productmoney   decimal(10,2);-- 产品的所需金额  
  declare playername     varchar(100); -- 充入者的昵称
  declare playerroomcard int(11);      -- 充入者的房卡数量

  set result = 0;
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验微信公众号用户
  call cp_check_4_salesuser(agentid, openid, result, error, username, usersalesman);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;

  -- 检验productid
  call cp_check_5_product(agentid, productid, result, error, productname, productamount, productmoney);
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验playerid
  if (billtype = 0) then
    call cp_check_2_player(agentid, playerid, result, error, playername, playerroomcard);
    if result > 0 then 
      select result, error;
      leave label_cp;
    end if;
  end if; 
  
  -- 获取渠道商id
  if not exists (select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    select agch_channelid into channelid from agent_channel where agch_agentid = agentid order by idx limit 1;
  end if; 

  -- 保存订单
  if (billtype = 0) then
    insert into sales_buybill(sabu_agentid, sabu_openid, sabu_channelid, sabu_billcode, sabu_productid, 
                              sabu_amount, sabu_money, sabu_createtime, sabu_billtype, 
                              sabu_playerid, sabu_playername)
    values(agentid, openid, channelid, billcode, productid, productamount, productmoney, now(),
           billtype, playerid, playername);
  else
    insert into sales_buybill(sabu_agentid, sabu_openid, sabu_channelid, sabu_billcode, sabu_productid, 
                              sabu_amount, sabu_money, sabu_createtime, sabu_billtype)
    values(agentid, openid, channelid, billcode, productid, productamount, productmoney, now(), billtype); 
    
    -- 保存个人代理的联系方式
    update sales_user set saus_tel = tel, saus_wechat = wechat where saus_agentid = agentid and saus_openid = openid; 
  end if;

  -- 返回执行结果    
  select result, error, productname, productamount, productmoney, playername;  
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_pay_query
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_pay_query`;
delimiter ;;
CREATE PROCEDURE `cp_sales_pay_query`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `billcode` varchar(50) charset utf8 collate utf8_general_ci ,IN `paymoney` decimal(10,2) ,IN `appid` varchar(50) charset utf8 collate utf8_general_ci ,IN `devkey` varchar(50) charset utf8 collate utf8_general_ci ,IN `business_id` varchar(50) charset utf8 collate utf8_general_ci ,IN `parentid` int(8))
  SQL SECURITY INVOKER
  COMMENT '订单支付查询成功，修改实际支付金额'
label_cp: begin
  declare result       tinyint(1);   -- 0:成功  >0:失败 
  declare error        varchar(100); -- 失败描述 
  declare agentname    varchar(100); -- 代理商名称   
  declare username     varchar(100); -- 微信公众号用户昵称 
  declare usersalesman tinyint(1);   -- 微信公众号用户是否是个人代理
  declare billtype     tinyint(1);   -- 订单类型
  declare playerid     int(8);       -- 充入者玩家id
  declare playername   varchar(100); -- 充入者昵称
  declare amount       int(11);      -- 购卡数量
  declare money        decimal(10,2);-- 产品中的所需金额
  declare paystate     tinyint(1);   -- 支付状态
  declare roomcard     int(11);      -- 购卡后房卡数量

  set result = 0;

  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  

  -- 检验微信公众号用户
  call cp_check_4_salesuser(agentid, openid, result, error, username, usersalesman);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
  
  -- 检验订单
  call cp_check_6_buybill(agentid, billcode, result, error, billtype, playerid, playername, amount, money, paystate);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if; 
  
  -- 修改实际支付金额
  update sales_buybill set sabu_paymoney = paymoney,
                           sabu_appid = appid, sabu_devkey = devkey, 
                           sabu_business_id = business_id
  where sabu_agentid = agentid and sabu_billcode = billcode;
  
  -- 返回执行结果
  if (billtype = 0) then
    -- 返回玩家购卡后的房卡数量
    select play_roomcard into roomcard from player where play_agentid = agentid and play_playerid = playerid;
  
    -- 返回执行结果 
    select result, error, billtype, playerid, playername, amount, roomcard;
  else
    -- 无推荐人
    if isnull(parentid) or (parentid = '') or (parentid = 0) then
      select result, error, billtype, saus_salesid as salesid, 
             saus_nickname as salesname, amount, saus_roomcard as roomcard
      from sales_user where saus_agentid = agentid and saus_openid = openid; 
    else
      select result, error, billtype, u.saus_salesid as salesid, 
             u.saus_nickname as salesname, amount, u.saus_roomcard as roomcard,
             p.saus_salesid as parentid, p.saus_nickname as parentname
      from sales_user as u
      left join sales_user as p on p.saus_agentid = agentid
                               and p.saus_salesid = u.saus_parentid      
      where u.saus_agentid = agentid 
        and u.saus_openid = openid; 
    end if;  
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_pay_succ
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_pay_succ`;
delimiter ;;
CREATE PROCEDURE `cp_sales_pay_succ`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `billcode` varchar(50) charset utf8 collate utf8_general_ci ,IN `transid` varchar(100) charset utf8 collate utf8_general_ci ,IN `outtradeNo` varchar(100) charset utf8 collate utf8_general_ci ,IN `signkey` varchar(50) charset utf8 collate utf8_general_ci ,IN `paymoney` decimal(10,2) ,IN `parentid` int(8))
  SQL SECURITY INVOKER
  COMMENT '订单支付成功'
label_cp: begin
  declare result       tinyint(1);   -- 0:成功  >0:失败 
  declare error        varchar(100); -- 失败描述 
  declare agentname    varchar(100); -- 代理商名称   
  declare username     varchar(100); -- 微信公众号用户昵称 
  declare usersalesman tinyint(1);   -- 微信公众号用户是否是个人代理
  declare usersalesid  int(8);       -- 个人代理id 
  declare userparentid int(8);       -- 上级个人代理id   
  declare billtype     tinyint(1);   -- 订单类型
  declare playerid     int(8);       -- 充入者玩家id
  declare playername   varchar(100); -- 充入者昵称
  declare amount       int(11);      -- 购卡数量
  declare money        decimal(10,2);-- 产品中的所需金额
  declare paystate     tinyint(1);   -- 支付状态
  declare roomcard     int(11);      -- 购卡后房卡数量
  declare salesid      int(8);       -- 新代理id
  declare salespower   varchar(10);  -- 默认的个人代理权限
  
  declare salesid1     int(8); -- 玩家绑定的上一级个人代理id
  declare salesid2     int(8); -- 玩家绑定的上二级个人代理id
  declare pushrate1    int(4); -- 玩家的上一级代理的提成比例
  declare pushrate2    int(4); -- 玩家的上二级代理的提成比例
  
  set result = 0;
     
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验微信公众号用户
  call cp_check_4_salesuser(agentid, openid, result, error, username, usersalesman);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
  
  -- 检验订单
  call cp_check_6_buybill(agentid, billcode, result, error, billtype, playerid, playername, amount, money, paystate);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if; 
  
  if paystate = 1 then
    set result = 11;
    set error = '订单已支付'; 
    select result, error;
    leave label_cp;
  end if;
  
  -- 获取渠道商id
  if not exists (select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    select agch_channelid into channelid from agent_channel where agch_agentid = agentid order by idx limit 1;
  end if; 
  
  -- 检验signkey
  if not exists(select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid and agch_youle_signkey = signkey) then
    set result = 12;
    set error = '微信支付签名不正确'; 
    select result, error;
    leave label_cp;
  end if;
    
  -- 修改订单状态
  update sales_buybill set sabu_paystate = 1, sabu_paytime = now(),
                           sabu_transid = transid, sabu_outtradeNo = outtradeNo,
                           sabu_signkey = signkey, sabu_paymoney = paymoney
  where sabu_agentid = agentid and sabu_billcode = billcode;
  
  -- 统计总流水
  update agent set agen_selftotal = agen_selftotal + paymoney where agen_agentid = agentid;
  
  -- 按日期统计房卡销售金额
  call cp_report_agent_day(agentid, 3, paymoney);
  
  -- 检验支付金额
  if paymoney <> money then
     set result = 13;
     set error = '支付金额不正确'; 
     select result, error;
     leave label_cp;
  end if;
  
  -- 完成购买任意金额房卡的任务
  call cp_sales_finish_task(agentid, openid, null, 'heB1piC7b8M4nfifn34k9ouV2qL9osTM');   
  
  if (billtype = 0) then
    -- 修改玩家房卡数量
    update player set play_roomcard = play_roomcard + amount
    where play_agentid = agentid and play_playerid = playerid;
  
    -- 返回玩家购卡后的房卡数量
    select play_roomcard into roomcard from player 
    where play_agentid = agentid and play_playerid = playerid;

    -- 统计绑定的个人代理的提成
    select play_invitecode into salesid1
    from player
    where play_agentid = agentid and play_playerid = playerid;

    if not isnull(salesid1) then
      select saus_parentid, saus_pushrate1 into salesid2, pushrate1
      from sales_user
      where saus_agentid = agentid and saus_salesid = salesid1;

      update sales_buybill set  sabu_pushsalesid1 = salesid1,
                                sabu_pushrate1    = pushrate1, 
                                sabu_pushmoney1   = if(isnull(pushrate1), null, paymoney * pushrate1 / 100)
      where sabu_agentid = agentid and sabu_billcode = billcode;

      if not isnull(pushrate1) then
        update sales_user set saus_pushmoney1 = saus_pushmoney1 + paymoney * pushrate1 / 100
        where saus_agentid = agentid and saus_salesid = salesid1;
      end if;

      if not isnull(salesid2) then
        select saus_pushrate2 into pushrate2
        from sales_user
        where saus_agentid = agentid and saus_salesid = salesid2;

        update sales_buybill set  sabu_pushsalesid2 = salesid2,
                                  sabu_pushrate2    = pushrate2, 
                                  sabu_pushmoney2   = if(isnull(pushrate2), null, paymoney * pushrate2 / 100)
        where sabu_agentid = agentid and sabu_billcode = billcode;

        if not isnull(pushrate2) then
          update sales_user set saus_pushmoney2 = saus_pushmoney2 + paymoney * pushrate2 / 100
          where saus_agentid = agentid and saus_salesid = salesid2;
        end if;
      end if;
    end if;
  
    -- 返回执行结果 
    select result, error, billtype, playerid, playername, amount, roomcard;
  else
    if (usersalesman = 0) then
      -- 新个人代理
      update agent set agen_maxsalesid = agen_maxsalesid + floor(rand() * (12-6) + 6) where agen_agentid = agentid;
     
      select agen_maxsalesid, agen_salespower
      into salesid, salespower 
      from agent 
      where agen_agentid = agentid;     
      
      -- 无推荐人
      if isnull(parentid) or (parentid = '') or (parentid = 0) then
        update sales_user set saus_roomcard = saus_roomcard + amount,
                              saus_salesman = 1, saus_salesid = salesid,
                              saus_level = 0, saus_saletime = now(),
                              saus_salestype = 1, saus_power = salespower
        where saus_agentid = agentid and saus_openid = openid;
      else -- 有推荐人
        update sales_user set saus_roomcard = saus_roomcard + amount,
                              saus_salesman = 1, saus_salesid = salesid,
                              saus_saletime = now(), 
                              saus_salestype = 1, saus_power = salespower,
                              saus_parentid = parentid
        where saus_agentid = agentid and saus_openid = openid;

        -- 推荐人奖励
        call cp_sales_new_award(agentid, parentid, salesid, 0, billcode); 
      end if;
      
      -- 按日期统计新增个人代理人数
      call cp_report_agent_day(agentid, 1, 1);
    else
      -- 老个人代理
      update sales_user set saus_roomcard = saus_roomcard + amount 
      where saus_agentid = agentid and saus_openid = openid; 
      
      -- 推荐人的奖励
      select saus_salesid, saus_parentid into usersalesid, userparentid 
      from sales_user where saus_agentid = agentid and saus_openid = openid; 
      if not isnull(userparentid) then
        call cp_sales_new_award(agentid, userparentid, usersalesid, 1, billcode); 
      end if;
    end if; 
    
    -- 返回执行结果 
    select result, error, billtype;
  end if;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_player_binding_invitecode
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_player_binding_invitecode`;
delimiter ;;
CREATE PROCEDURE `cp_sales_player_binding_invitecode`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `invitecode` int(8))
  SQL SECURITY INVOKER
  COMMENT '玩家自动绑定邀请码'
label_cp: begin
  declare result       tinyint(1);   -- 0:成功  >0:失败 
  declare error        varchar(100); -- 失败描述
  
  declare salesid      int(8);
  declare nickname     varchar(100);
  declare avatar       varchar(200);
  declare wechat       varchar(50);
  declare tel          varchar(20);
  
  declare myinvitecode int(8);  -- 已经绑定的邀请码  
 
  -- 检验邀请码是否存在
  select saus_salesid, saus_nickname, saus_avatar, saus_wechat, saus_tel
  into salesid, nickname, avatar, wechat, tel
  from sales_user 
  where saus_agentid = agentid 
    and saus_salesid = invitecode
    and saus_salesman = 1;   
    
  if isnull(salesid) then
    set result = 1;
    set error = '邀请码不存在';
    select result, error;
    leave label_cp;
  end if; 
  
  -- 检查是否已经绑定了邀请码
  select saus_invitecode into myinvitecode 
  from sales_user 
  where saus_agentid = agentid
    and saus_openid = openid;
    
  if isnull(myinvitecode) then
    update sales_user 
    set saus_invitecode = invitecode
    where saus_agentid = agentid
      and saus_openid = openid;
        
    set result = 0;
    set error  = '绑定邀请码成功'; 
  else
    set result = 2;
    set error  = '已经绑定过邀请码，不能再次绑定';
  
    select saus_salesid, saus_nickname, saus_avatar, saus_wechat, saus_tel
    into salesid, nickname, avatar, wechat, tel
    from sales_user 
    where saus_agentid = agentid 
      and saus_salesid = myinvitecode
      and saus_salesman = 1;   
  end if;
  
  select result, error, salesid, nickname, avatar, wechat, tel;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_query_player
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_query_player`;
delimiter ;;
CREATE PROCEDURE `cp_sales_query_player`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `playerid` int(8))
  SQL SECURITY INVOKER
  COMMENT '通过玩家id查询玩家昵称和房卡数量'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述 
  declare agentname      varchar(100); -- 代理商名称 
  declare roomcard       int(11);      -- 个人代理房卡数量  
  declare playername     varchar(100); -- 充入者的昵称
  declare playerroomcard int(11);      -- 充入者的房卡数量

  set result = 0;
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验是否是个人代理
  call cp_check_7_salesman(agentid, openid, result, error, roomcard);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
   
  -- 检验playerid
  call cp_check_2_player(agentid, playerid, result, error, playername, playerroomcard);
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
 
  select result, error, playerid, playername, playerroomcard;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_query_player_bean
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_query_player_bean`;
delimiter ;;
CREATE PROCEDURE `cp_sales_query_player_bean`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `playerid` int(8))
  SQL SECURITY INVOKER
  COMMENT '通过玩家id查询玩家昵称和房卡数量'
label_cp: begin
  declare result     tinyint(1);   -- 0:成功  >0:失败 
  declare error      varchar(100); -- 失败描述 
  declare _playerid  int(8);
  declare playername varchar(100); -- 玩家的昵称
  declare playerbean int(11);      -- 玩家的星星数量

  set result = 0;
  -- 检验agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error  = '运营商不存在'; 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验是否是个人代理
  if not exists(select 1 from sales_user where saus_agentid = agentid and saus_openid = openid and saus_salesman = 1) then
    set result = 7;
    set error  = '您不是个人代理'; 
    select result, error;
    leave label_cp;
  end if;
   
  -- 检验playerid
  select play_playerid, play_nickname, play_bean into _playerid, playername, playerbean 
  from player 
  where play_agentid = agentid and play_playerid = playerid;
  if isnull(_playerid) then
    set result = 2;
    set error  = '玩家不存在'; 
    select result, error;
    leave label_cp;
  end if;
 
  select result, error, playerid, playername, playerbean;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_query_salesman
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_query_salesman`;
delimiter ;;
CREATE PROCEDURE `cp_sales_query_salesman`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `salesid` int(8))
  SQL SECURITY INVOKER
  COMMENT '通过个人代理id查询个人代理昵称和房卡数量'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述 
  declare agentname      varchar(100); -- 代理商名称 
  declare roomcard       int(11);      -- 用户的房卡数量  
  declare salesname      varchar(100); -- 查询的个人代理昵称
  declare salesroomcard  int(11);      -- 查询的个人代理房卡数量

  set result = 0;
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验用户是否是个人代理
  call cp_check_7_salesman(agentid, openid, result, error, roomcard);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
   
  -- 检验salesid
  call cp_check_9_salesman(agentid, salesid, result, error, salesname, salesroomcard);
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
 
  select result, error, salesid, salesname, salesroomcard;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_topup_player
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_topup_player`;
delimiter ;;
CREATE PROCEDURE `cp_sales_topup_player`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `amount` int(11))
  SQL SECURITY INVOKER
  COMMENT '个人代理给玩家充卡'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述 
  declare agentname      varchar(100); -- 代理商名称 
  declare roomcard       int(11);      -- 个人代理房卡数量  
  declare playername     varchar(100); -- 充入者的昵称
  declare playerroomcard int(11);      -- 充入者的房卡数量

  declare salespower       varchar(10); -- 个人代理的权限
  declare topuppower       varchar(1);  -- 给玩家充值权限
  declare playerinvitecode int(8);      -- 充入者绑定的邀请码
  declare mysalesid        int(8);      -- 我的个人代理id

  set result = 0;
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验是否是个人代理
  call cp_check_7_salesman(agentid, openid, result, error, roomcard);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
   
  -- 检验playerid
  call cp_check_2_player(agentid, playerid, result, error, playername, playerroomcard);
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
 
  -- 检验个人代理的房卡数量是否够
  if roomcard < amount then
    set result = 11;
    set error = '房卡数量不足';
    select result, error;
    leave label_cp;  
  end if;
  
  -- 充卡数量不能是负数
  if amount < 0 then
    set result = 12;
    set error = '充卡数量必须大于0';
    select result, error;
    leave label_cp;  
  end if;  
  
  -- 判断是否有给玩家充值的权限
  select saus_salesid, saus_power 
  into mysalesid, salespower   
  from sales_user
  where saus_agentid = agentid
    and saus_openid = openid;  
    
  if isnull(salespower) then
    select agen_salespower
    into salespower 
    from agent 
    where agen_agentid = agentid;  
  end if;
  
  set topuppower = substring(salespower, 2, 1);
    
  if topuppower = '0' then
      set result = 13;
      set error = '您没有给玩家充卡的权限';
      select result, error;
      leave label_cp; 
  end if;      
   
  if topuppower = '1' then
    select play_invitecode into playerinvitecode
    from player
    where play_agentid = agentid
      and play_playerid = playerid;
      
    if isnull(playerinvitecode) or (playerinvitecode <> mysalesid) then
      set result = 14;
      set error = '只能给绑定了自己邀请码的玩家充卡';
      select result, error;
      leave label_cp;  
    end if;  
  end if;
  
  -- 保存充卡记录
  insert into sales_sellbill(sase_agentid, sase_openid, sase_playerid, 
                             sase_amount, sase_selltime)
  values(agentid, openid, playerid, amount, now());
 
  -- 修改个人代理的房卡数量
  update sales_user set saus_roomcard = saus_roomcard - amount
  where saus_agentid = agentid and saus_openid = openid;
  
  select saus_roomcard into roomcard from sales_user
  where saus_agentid = agentid and saus_openid = openid;
    
  -- 修改玩家的房卡数量
  update player set play_roomcard = play_roomcard + amount 
  where play_agentid = agentid and play_playerid = playerid;
  
  select play_roomcard into playerroomcard from player
  where play_agentid = agentid and play_playerid = playerid;
  
  -- 返回执行结果
  select result, error, roomcard, amount, playerid, playername, playerroomcard;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_topup_player_bean
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_topup_player_bean`;
delimiter ;;
CREATE PROCEDURE `cp_sales_topup_player_bean`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `playerid` int(8) ,IN `amount` int(11))
  SQL SECURITY INVOKER
  COMMENT '个人代理给玩家充星星'
label_cp: begin
  declare result tinyint(1);   -- 0:成功  >0:失败 
  declare error  varchar(100); -- 失败描述 
  declare agentsalespower  varchar(10);  -- 代理商设置的默认权限
  declare salesid          int(8);       -- 我的个人代理id
  declare salespower       varchar(10);  -- 个人代理的权限
  declare topuppower       varchar(1);   -- 给玩家充星星权限
  declare salesbean        int(11);      -- 个人代理星星数量
  declare _playerid        int(8);       -- 玩家id   
  declare playername       varchar(100); -- 玩家昵称
  declare playerbean       int(11);      -- 玩家星星数量   
  declare playerinvitecode int(8);       -- 玩家绑定的邀请码
  

  set result = 0;
  
  -- 检验agentid
  set agentsalespower = '';
  select agen_salespower into agentsalespower from agent where agen_agentid = agentid;
  if isnull(agentsalespower) then
    set result = 1;
    set error  = '运营商不存在'; 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验是否是个人代理
  select saus_salesid, saus_power, saus_bean into salesid, salespower, salesbean  
  from sales_user 
  where saus_agentid = agentid and saus_openid = openid and saus_salesman = 1;
  if isnull(salesid) then
    set result = 7;
    set error  = '您不是个人代理'; 
    select result, error;
    leave label_cp;
  end if;
  
  -- 检验playerid
  select play_playerid, play_nickname, play_invitecode into _playerid, playername, playerinvitecode 
  from player 
  where play_agentid = agentid and play_playerid = playerid;
  if isnull(_playerid) then
    set result = 2;
    set error  = '玩家不存在'; 
    select result, error;
    leave label_cp;
  end if;
  
  -- 充值数量不能是负数
  if amount < 0 then
    set result = 12;
    set error = '充值数量必须大于0';
    select result, error;
    leave label_cp;  
  end if;  
  
  -- 检验个人代理的星星数量是否够
  if salesbean < amount then
    set result = 11;
    set error = '星星数量不足';
    select result, error;
    leave label_cp;  
  end if;
  
  -- 判断是否有给玩家充值的权限  
  if isnull(salespower) then
    set salespower = agentsalespower;  
  end if;
  set topuppower = substring(salespower, 3, 1);
  
  if topuppower = '' or topuppower = '0' then
      set result = 13;
      set error = '您没有给玩家充值的权限';
      select result, error;
      leave label_cp; 
  end if; 
  
  if topuppower = '1' then
    if isnull(playerinvitecode) or (playerinvitecode <> salesid) then
      set result = 14;
      set error = '只能给绑定了自己邀请码的玩家充值星星';
      select result, error;
      leave label_cp;  
    end if;  
  end if;
  
  -- 保存充卡记录
  insert into sales_sellbill_bean(
    ssbe_agentid, ssbe_openid, ssbe_playerid, ssbe_amount, ssbe_selltime)
  values(agentid, openid, playerid, amount, now());
 
  -- 修改个人代理的星星数量
  update sales_user set saus_bean = saus_bean - amount
  where saus_agentid = agentid and saus_openid = openid;
  
  select saus_bean into salesbean from sales_user
  where saus_agentid = agentid and saus_openid = openid;
    
  -- 修改玩家的房卡数量
  update player set play_bean = play_bean + amount 
  where play_agentid = agentid and play_playerid = playerid;
  
  select play_bean into playerbean from player
  where play_agentid = agentid and play_playerid = playerid;
  
  -- 返回执行结果
  select result, error, salesbean, amount, playerid, playername, playerbean;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_topup_salesman
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_topup_salesman`;
delimiter ;;
CREATE PROCEDURE `cp_sales_topup_salesman`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `salesid` int(8) ,IN `amount` int(11))
  SQL SECURITY INVOKER
  COMMENT '个人代理给其他个人代理转卡'
label_cp: begin
  declare result         tinyint(1);   -- 0:成功  >0:失败 
  declare error          varchar(100); -- 失败描述 
  declare agentname      varchar(100); -- 代理商名称 
  declare roomcard       int(11);      -- 个人代理房卡数量  
  declare salesname      varchar(100); -- 转入的个人代理昵称
  declare salesroomcard  int(11);      -- 转入的个人代理房卡数量
  
  declare salespower     varchar(10);-- 个人代理的权限
  declare topuppower     varchar(1); -- 转卡权限
  declare parentid       int(8);     -- 充入者的上级代理id
  declare mysalesid      int(8);     -- 我的个人代理id  

  set result = 0;
  -- 检验agentid
  call cp_check_1_agent(agentid, result, error, agentname);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验是否是个人代理
  call cp_check_7_salesman(agentid, openid, result, error, roomcard);  
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
   
  -- 检验salesid
  call cp_check_9_salesman(agentid, salesid, result, error, salesname, salesroomcard);
  if result > 0 then 
    select result, error;
    leave label_cp;
  end if;
 
  -- 检验个人代理的房卡数量是否够
  if roomcard < amount then
    set result = 11;
    set error = '房卡数量不足';
    select result, error;
    leave label_cp;  
  end if;
  
  -- 转卡数量不能是负数
  if amount < 0 then
    set result = 12;
    set error = '转卡数量必须大于0';
    select result, error;
    leave label_cp;  
  end if;  
  
  
  -- 判断是否有给转卡的权限
  select saus_salesid, saus_power 
  into mysalesid, salespower   
  from sales_user
  where saus_agentid = agentid
    and saus_openid = openid;  
    
  if isnull(salespower) then
    select agen_salespower
    into salespower 
    from agent 
    where agen_agentid = agentid;  
  end if;
  
  set topuppower = substring(salespower, 1, 1);
      
  if topuppower = '0' then
      set result = 13;
      set error = '您没有给其他代理转卡的权限';
      select result, error;
      leave label_cp; 
  end if;      
   
  if topuppower = '1' then
    select saus_parentid into parentid
    from sales_user
    where saus_agentid = agentid
      and saus_salesid = salesid;
      
    if isnull(parentid) or (parentid <> mysalesid) then
      set result = 14;
      set error = '只能给绑定了自己邀请码的子代理转卡';
      select result, error;
      leave label_cp;  
    end if;  
  end if;    
  
  -- 保存转卡记录
  insert into sales_transferbill(satr_agentid, satr_openid, satr_salesid, 
                                 satr_amount, satr_transfertime)
  values(agentid, openid, salesid, amount, now());
 
  -- 修改转出的个人代理的房卡数量
  update sales_user set saus_roomcard = saus_roomcard - amount
  where saus_agentid = agentid and saus_openid = openid;
  
  select saus_roomcard into roomcard from sales_user
  where saus_agentid = agentid and saus_openid = openid;
    
  -- 修改转入的个人代理的房卡数量
  update sales_user set saus_roomcard = saus_roomcard + amount
  where saus_agentid = agentid and saus_salesid = salesid;
  
  select saus_roomcard into salesroomcard from sales_user
  where saus_agentid = agentid and saus_salesid = salesid;
  
  -- 返回执行结果
  select result, error, roomcard, amount, salesid, salesname, salesroomcard;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_update_mywechat
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_update_mywechat`;
delimiter ;;
CREATE PROCEDURE `cp_sales_update_mywechat`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `wechat` varchar(50) charset utf8 collate utf8_general_ci ,IN `tel` varchar(20) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '修改个人代理的联系方式'
label_cp: begin
  declare result       tinyint(1);   -- 0:成功  >0:失败 
  declare error        varchar(100); -- 失败描述
  
  set result = 0;
     
  -- 检验agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then 
    set result = 1;
    set error = '运营商id不存在';
    select result, error;
    leave label_cp;
  end if;  
  
  -- 检验微信公众号用户
  if not exists(select 1 from sales_user where saus_agentid = agentid and saus_openid = openid) then 
    set result = 2;
    set error = '用户不存在';
    select result, error;
    leave label_cp;
  end if;
  
  update sales_user set saus_wechat = wechat, saus_tel = tel
  where saus_agentid = agentid and saus_openid = openid;
  
  -- 返回执行结果 
  select result, error;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_sales_user_login
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_sales_user_login`;
delimiter ;;
CREATE PROCEDURE `cp_sales_user_login`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `nickname` varchar(100) charset utf8 collate utf8_general_ci ,IN `avatar` varchar(200) charset utf8 collate utf8_general_ci ,IN `sex` tinyint(1) ,IN `province` varchar(100) charset utf8 collate utf8_general_ci ,IN `city` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '微信公众号用户登录'
begin
  declare old_openid   varchar(100);
  declare salesman     tinyint(1);
  declare salesid      int(8);
  declare saleslevel   int(4);
  declare salestype    tinyint(1);
  declare roomcard     int(11);
  declare bean         int(11);
  declare pushmoney    decimal(10,2);
  declare salespower   varchar(10);
  declare playerask    tinyint(1);
  declare salesask     tinyint(1);
  declare invitecode   int(8);
  
  -- 获取代理商id
  if not exists (select 1 from agent where agen_agentid = agentid) then
    select agen_agentid into agentid from agent order by idx limit 1;
  end if; 
  
  -- 获取渠道商id
  if not exists (select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    select agch_channelid into channelid from agent_channel where agch_agentid = agentid order by idx limit 1;
  end if; 
  
  -- 获取用户信息
  select saus_openid, saus_salesman, saus_salesid, saus_level, saus_salestype, 
         saus_roomcard, saus_bean, saus_power, saus_invitecode, 
         ifnull(saus_pushmoney1, 0) + ifnull(saus_pushmoney2, 0)
  into old_openid, salesman, salesid, saleslevel, salestype, 
       roomcard, bean, salespower, invitecode, pushmoney
  from sales_user 
  where saus_agentid = agentid 
    and saus_unionid = unionid;    

  if isnull(old_openid) then
    -- 新用户
    insert into sales_user (saus_agentid, saus_channelid, saus_openid, saus_unionid, 
                            saus_nickname, saus_avatar, saus_sex, saus_province, 
                            saus_city, saus_firsttime, saus_lasttime)
    values (agentid, channelid, openid, unionid, nickname, avatar, sex, province, city, now(), now());      
  else
    -- 老用户
    update sales_user set saus_openid = openid, saus_nickname = nickname, 
                          saus_avatar = avatar, saus_sex = sex, 
                          saus_province = province, saus_city = city, 
                          saus_lasttime = now()
    where saus_agentid = agentid and saus_unionid = unionid; 
    
    -- 更换了授权后openid会发生变化
    if openid <> old_openid then       
       update sales_buybill       set sabu_openid = openid where sabu_agentid = agentid and sabu_openid = old_openid;
       update sales_sellbill      set sase_openid = openid where sase_agentid = agentid and sase_openid = old_openid;
       update sales_sellbill_bean set ssbe_openid = openid where ssbe_agentid = agentid and ssbe_openid = old_openid;
       update sales_transferbill  set satr_openid = openid where satr_agentid = agentid and satr_openid = old_openid;
    end if;
  end if; 
  
  select saus_openid, saus_salesman, saus_salesid, saus_level, saus_salestype, 
         saus_roomcard, saus_bean, saus_power, saus_invitecode, 
         ifnull(saus_pushmoney1, 0) + ifnull(saus_pushmoney2, 0)
  into old_openid, salesman, salesid, saleslevel, salestype, 
       roomcard, bean, salespower, invitecode, pushmoney
  from sales_user 
  where saus_agentid = agentid 
    and saus_unionid = unionid;   
   
  if salesman = 1 then   
    -- 获取是否有新的玩家索要房卡记录
    if exists(select 1 from sales_ask_bill 
              where saab_agentid = agentid
                and saab_salesid = salesid
                and saab_state = 0
                and saab_type = 0) then
      set playerask = 1;
    else
      set playerask = 0;
    end if;    
    
    -- 获取是否有新的代理索要房卡记录
    if exists(select 1 from sales_ask_bill 
              where saab_agentid = agentid
                and saab_salesid = salesid
                and saab_state = 0
                and saab_type = 1) then
      set salesask = 1;
    else
      set salesask = 0;
    end if;     
  end if;  
  
  -- 完成关注公众号的任务
  call cp_sales_finish_task(agentid, null, unionid, 'lXA1XUuHPvKyupdGlbQI4y5D37Kbgodo');
  
  -- 看是否绑定过邀请码
  if isnull(invitecode) then
    select play_invitecode into invitecode
    from player
    where play_agentid = agentid
      and play_unionid = unionid;
      
    if not isnull(invitecode) then
       update sales_user set saus_invitecode = invitecode
       where saus_agentid = agentid
         and saus_unionid = unionid;
    end if; 
  end if;  
    
  -- 返回结果
  select salesman, salesid, saleslevel, salestype, roomcard, bean,
         salespower, playerask, salesask, pushmoney;   
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_third_change_roomcard
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_third_change_roomcard`;
delimiter ;;
CREATE PROCEDURE `cp_third_change_roomcard`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `amount` int(11))
  SQL SECURITY INVOKER
  COMMENT '修改房卡数量'
label_cp: begin
  declare result   tinyint(1);    -- 0:成功  >0:失败
  declare error    varchar(100);  -- 失败描述
  declare playerid int(8);       -- 玩家id
  declare roomcard int(11);      -- 玩家房卡数量 
  
  -- 检查agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error = 'a参数错误';
    select result, error;
    leave label_cp;
  end if;
  
  -- 检查channelid
  if not exists(select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    set result = 2;
    set error = 'c参数错误';
    select result, error;
    leave label_cp;
  end if;
    
  -- 检查gameid
  if not exists(select 1 from game where game_gameid = gameid) then
    set result = 3;
    set error = 'g参数错误';
    select result, error;
    leave label_cp;
  end if;
  
  -- 检查玩家
  select play_roomcard into roomcard
  from player 
  where play_agentid = agentid and play_unionid = unionid;
  if isnull(roomcard) then
    set result = 4;
    set error = '玩家不存在';
    select result, error;
    leave label_cp;  
  end if; 
  
  if amount > 0 then
    set result = 5;
    set error = '没有该权限';
    select result, error;
    leave label_cp;  
  end if;    
  
  -- 检查房卡数量是否够
  if roomcard < -1 * amount then
    set result = 6;
    set error = '玩家房卡数量不够';
    select result, error;
    leave label_cp;  
  end if; 
 
  update player set play_roomcard = play_roomcard + amount
  where play_agentid = agentid and play_unionid = unionid;  
  
  -- 返回执行结果
  set result = 0;
  set error = ''; 
  select result, error, play_playerid as playerid, play_roomcard as roomcard, amount
  from player 
  where play_agentid = agentid and play_unionid = unionid;
end
;;
delimiter ;

-- ----------------------------
-- Procedure structure for cp_third_get_roomcard
-- ----------------------------
DROP PROCEDURE IF EXISTS `cp_third_get_roomcard`;
delimiter ;;
CREATE PROCEDURE `cp_third_get_roomcard`(IN `agentid` varchar(32) charset utf8 collate utf8_general_ci ,IN `channelid` varchar(32) charset utf8 collate utf8_general_ci ,IN `gameid` varchar(32) charset utf8 collate utf8_general_ci ,IN `openid` varchar(100) charset utf8 collate utf8_general_ci ,IN `unionid` varchar(100) charset utf8 collate utf8_general_ci ,IN `nickname` varchar(100) charset utf8 collate utf8_general_ci ,IN `avatar` varchar(200) charset utf8 collate utf8_general_ci ,IN `sex` int(11) ,IN `province` varchar(100) charset utf8 collate utf8_general_ci ,IN `city` varchar(100) charset utf8 collate utf8_general_ci)
  SQL SECURITY INVOKER
  COMMENT '获取房卡数量'
label_cp: begin
  declare result   tinyint(1);    -- 0:成功  >0:失败
  declare error    varchar(100);  -- 失败描述
  declare playerid int(8);       -- 玩家id
  declare roomcard int(11);      -- 玩家房卡数量 
  
  -- 检查agentid
  if not exists(select 1 from agent where agen_agentid = agentid) then
    set result = 1;
    set error = 'a参数错误';
    select result, error;
    leave label_cp;
  end if;
  
  -- 检查channelid
  if not exists(select 1 from agent_channel where agch_agentid = agentid and agch_channelid = channelid) then
    set result = 2;
    set error = 'c参数错误';
    select result, error;
    leave label_cp;
  end if;
  
  -- 检查gameid
  if not exists(select 1 from game where game_gameid = gameid) then
    set result = 3;
    set error = 'g参数错误';
    select result, error;
    leave label_cp;
  end if;
  
  -- 检查是否是新玩家
  select play_playerid, play_roomcard
  into playerid, roomcard
  from player 
  where play_agentid = agentid 
    and play_unionid = unionid;
  
  if isnull(playerid) then
     -- 新玩家
     update agent set agen_maxplayerid = agen_maxplayerid + 1 where agen_agentid = agentid;

     select agen_maxplayerid into playerid from agent where agen_agentid = agentid;

     insert into player(play_agentid, play_playerid, play_channelid, play_openid, 
                        play_unionid, play_nickname, play_avatar, play_sex,  
                        play_province, play_city, play_regtime, play_lasttime)
     values(agentid, playerid, channelid, openid, unionid, nickname, avatar, sex, province, city, now(), now());
   
     select play_roomcard
     into roomcard
     from player 
     where play_agentid = agentid 
       and play_unionid = unionid;
     
     -- 按日期统计新增玩家数量
     call cp_report_agent_day(agentid, 0, 1);
  else
     -- 老玩家
     update player set play_nickname = nickname, play_avatar = avatar, play_openid = openid,
                       play_sex = sex, play_province = province, play_city = city, 
                       play_logindate = play_logindate + if(datediff(now(), play_lasttime) = 0, 0, 1),
                       play_lasttime = now()                       
     where play_agentid = agentid 
       and play_unionid = unionid; 
  end if;

  -- 统计玩家的最后登录时间和累积登录天数
  if not exists(select 1 from agent_game_player 
                where agpl_agentid = agentid 
                  and agpl_gameid = gameid 
                  and agpl_playerid = playerid) then
    insert into agent_game_player(agpl_agentid, agpl_gameid, agpl_playerid, agpl_openid, agpl_firsttime, agpl_lasttime)
    values(agentid, gameid, playerid, openid, now(), now());
    
    -- 按日期统计新增玩家数量
    call cp_report_game_day(agentid, gameid, now(), 0, 1, null);
  else
    update agent_game_player 
    set agpl_logindate = agpl_logindate + if(datediff(now(), agpl_lasttime) = 0, 0, 1),
        agpl_lasttime = now()
    where agpl_agentid = agentid 
      and agpl_gameid = gameid 
      and agpl_playerid = playerid;
  end if;
  
  -- 返回执行结果
  set result = 0;
  set error = '';
  select result, error, playerid, roomcard;
end
;;
delimiter ;

SET FOREIGN_KEY_CHECKS = 1;
