package com.bizzan.bitrade.controller.finance;

import static com.bizzan.bitrade.constant.WithdrawStatus.FAIL;
import static com.bizzan.bitrade.constant.WithdrawStatus.WAITING;
import static org.springframework.util.Assert.notNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bizzan.bitrade.annotation.AccessLog;
import com.bizzan.bitrade.constant.AdminModule;
import com.bizzan.bitrade.constant.PageModel;
import com.bizzan.bitrade.constant.WithdrawStatus;
import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.entity.Member;
import com.bizzan.bitrade.entity.QMember;
import com.bizzan.bitrade.entity.QTransferRecord;
import com.bizzan.bitrade.entity.TransferRecord;
import com.bizzan.bitrade.entity.WithdrawRecord;
import com.bizzan.bitrade.model.screen.TransferRecordScreen;
import com.bizzan.bitrade.service.MemberService;
import com.bizzan.bitrade.service.TransferRecordService;
import com.bizzan.bitrade.util.MessageResult;
import com.bizzan.bitrade.util.PredicateUtils;
import com.bizzan.bitrade.vendor.provider.SMSProvider;
import com.bizzan.bitrade.vo.TransferRecordVo;
import com.querydsl.core.types.dsl.BooleanExpression;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/finance/transfer")
public class TransferRecordController extends BaseAdminController {

	@Autowired
	private TransferRecordService transferRecordService;
	@Autowired
	private MemberService memberService;
	@Autowired
    private SMSProvider smsProvider;
	
	@PostMapping("page-query")
    @AccessLog(module = AdminModule.FINANCE, operation = "分页查找交易记录TransferRecord")
    public MessageResult pageQuery(
            PageModel pageModel, TransferRecordScreen screen) {
		ArrayList<BooleanExpression> predicates = new ArrayList<>();
		if(screen.getAccount()!=null) {
			Member member = memberService.findByUsername(screen.getAccount());
	        if(member == null) {
	        	try {
	        		member = memberService.findOne(Long.parseLong(screen.getAccount()));
	        	} catch (Exception e) {
	        		
	        	}
	        }
	        if(member == null) {
	        	return error("没有找到对象");
	        }
	        predicates.add(QTransferRecord.transferRecord.memberId.eq(member.getId())
	        		.or(QTransferRecord.transferRecord.targetMemberId.eq(member.getId())));
		}
		if(screen.getMemberId()!=null) {
            predicates.add((QTransferRecord.transferRecord.memberId.eq(screen.getMemberId())));
        }
		if(screen.getTargetMemberId()!=null) {
            predicates.add((QTransferRecord.transferRecord.targetMemberId.eq(screen.getTargetMemberId())));
        }
		Page<TransferRecord> results = transferRecordService.findAll(PredicateUtils.getPredicate(predicates), pageModel.getPageable());
		return success(results);
	}
	
	@GetMapping("/{id}")
    @RequiresPermissions("finance:withdraw-record:detail")
    @AccessLog(module = AdminModule.FINANCE, operation = "提现记录TransferRecord 详情")
    public MessageResult detail(@PathVariable("id") Long id) {
		TransferRecord record = transferRecordService.findOne(id);
        notNull(record, "没有数据");
        return success(record);
    }
	
	@PostMapping("stat")
    @AccessLog(module = AdminModule.FINANCE, operation = "分页查找交易记录TransferRecord")
    public MessageResult stat(
            PageModel pageModel, TransferRecordScreen screen) {
		ArrayList<BooleanExpression> predicates = new ArrayList<>();
		if(screen.getAccount()!=null) {
			Member member = memberService.findByUsername(screen.getAccount());
	        if(member == null) {
	        	try {
	        		member = memberService.findOne(Long.parseLong(screen.getAccount()));
	        	} catch (Exception e) {
	        		
	        	}
	        }
	        if(member != null) {
	        	List<TransferRecordVo> results = transferRecordService.stat(member.getId());
	        	for(TransferRecordVo vo: results) {
	        		vo.setUsername(memberService.findOne(vo.getMemberId()).getUsername());
	        		vo.setTargetUsername(memberService.findOne(vo.getTargetMemberId()).getUsername());
	        	}
	        	return success(results);
	        }
		}
		
		return error("没有找到对象");
	}
	
	@RequiresPermissions("finance:withdraw-record:audit-pass")
    @PatchMapping("/audit-pass")
    @AccessLog(module = AdminModule.FINANCE, operation = "提现记录TransferRecord一键审核通过")
    public MessageResult auditPass(@RequestParam("ids") Long[] ids) {
		transferRecordService.audit(ids, WithdrawStatus.SUCCESS, "");
		return MessageResult.success();
    }

    //一键审核不通过
    @RequiresPermissions("finance:withdraw-record:audit-no-pass")
    @PatchMapping("/audit-no-pass")
    @AccessLog(module = AdminModule.FINANCE, operation = "提现记录TransferRecord一键审核不通过")
    public MessageResult auditNoPass(@RequestParam("ids") Long[] ids, String remark) {
    	transferRecordService.audit(ids, FAIL, remark);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = df.format(new Date());
        for(Long id : ids) {
        	TransferRecord record = transferRecordService.findOne(id);
        	Member member = memberService.findOne(record.getMemberId());
        	if(member != null) {
        		try {
					smsProvider.sendCustomMessage(member.getMobilePhone(), "尊敬的用户，万分抱歉，您于" + date + "提取 " + record.getCoin().getUnit() + "失败，数量为" + record.getAmount() + "，请联系客服处理。");
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
        }
        return success();
    }
}
