drop PROCEDURE if EXISTS details;
CREATE PROCEDURE details(in uNum varchar(8))
READS SQL DATA
BEGIN
	select users.userNo 会员编号, users.name 姓名, users.level 会员等级, book.bookNo 图书编号,
	book.bookName 图书名称, year(orders.orderTime) 购买年份, orderdetails.Onumber 数量, book.price
	from users,orders,orderdetails,book
	where users.userNo = uNum
	and orders.userNo = uNum 
	and orderdetails.userNo = uNum 
	and orderdetails.bookNo = book.bookNo;
END;

call details("0000001");

drop PROCEDURE if EXISTS createOrder;
CREATE PROCEDURE createOrder(in uNum varchar(8))
READS SQL DATA
BEGIN
	declare bookMoney float(5);
	declare sNo varchar(8);
  declare oNo varchar(8);
	declare oST varchar(20);
	declare P_OrderNo varchar(50);
	declare dST varchar(10);
	declare bn varchar(20);
	declare nm int;declare i int;
	DECLARE done INT DEFAULT 0;##创建结束标志变量
	DECLARE cur cursor 
		for select bookNo,num,id
		FROM shoppingcart WHERE userNo = uNum;##创建游标
		DECLARE CONTINUE HANDLER FOR NOT found SET done = 1;##定义游标结束时的返回值
	
	set @oST='未处理';
	SET @dST='未配送';
-- 	将会员号和时间拼接起来作为订单号
	SELECT CONCAT(uNum,NOW()) into P_OrderNo;
-- 	统计此次购买金额存到bookMoney
	select sum(num * price) into bookMoney from shoppingcart where userNo = uNum;
-- 	查询此次的购物车编号存到sNo
	select distinct(scartNo) into sNo from shoppingcart where userNo = uNum;
-- 	Begin  Tran
		insert into orders (userNo, orderTime, sumMoney, scartNo,orderStatus,orderNo)
								value(uNum, now(), bookMoney, sNo,@oST,P_OrderNo);
		insert into distributionlist (orderNo, userNo, deliveryStatus)
								value(P_OrderNo, uNum, '未完成配送');						
		select last_insert_id() into oNo;
-- 	Commit  Tran
-- 购书明细信息写入订单明细表中
		open cur;	##打开游标
		read_loop:loop
		fetch cur into bn,nm,i;
		if done = 1 then
			leave read_loop;##跳出循环
		end if;
		insert into orderdetails (orderNo, deliveryStatus, bookNo, userNo,Onumber)
								value(P_OrderNo, '未配送', bn, uNum,nm);
		end loop;
    close cur;
		DELETE FROM shoppingcart WHERE userNo = uNum;
		SELECT * FROM orderdetails;
		SELECT * from shoppingcart;
END;

call createOrder("0000001");



drop PROCEDURE if EXISTS pressSales;
CREATE PROCEDURE pressSales()
BEGIN
	select press 出版社, sum(Onumber) 销售总数量 from orderdetails, book 
	where orderdetails.bookNo = book.bookNo group by orderdetails.bookNo order by sum(Onumber);
END;

call pressSales();
