package com.izouma.awesomeadmin.web;

import com.izouma.awesomeadmin.constant.AppConstant;
import com.izouma.awesomeadmin.dto.Page;
import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.model.MemberCoin;
import com.izouma.awesomeadmin.model.MemberCoinTixian;
import com.izouma.awesomeadmin.model.UserInfo;
import com.izouma.awesomeadmin.service.MemberCoinService;
import com.izouma.awesomeadmin.service.MemberCoinTixianService;
import com.izouma.awesomeadmin.service.UserInfoService;
import com.izouma.awesomeadmin.util.DateTimeTool;
import com.izouma.awesomeadmin.util.ExportExcelUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * controller类
 */
@Controller
@RequestMapping("/memberCoinTixian")
@RequiresAuthentication
public class MemberCoinTixianController {

    @Autowired
    private MemberCoinTixianService memberCoinTixianService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MemberCoinService memberCoinService;

    /**
     * <p>获取全部记录。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Result all(MemberCoinTixian record) {
        List<MemberCoinTixian> pp = memberCoinTixianService.getMemberCoinTixianList(record);
        return new Result(true, pp);
    }

    /**
     * <p>根据Id。</p>
     */
    @RequestMapping(value = "/getMemberCoinTixian", method = RequestMethod.GET)
    @ResponseBody
    public Result getMemberCoinTixian(@RequestParam(required = false, value = "id") String id) {
        MemberCoinTixian data = memberCoinTixianService.getMemberCoinTixianById(id);
        return new Result(true, data);
    }

    /**
     * <p>根据条件获取。</p>
     */
    @RequestMapping(value = "/getOne", method = RequestMethod.GET)
    @ResponseBody
    public Result getOne(MemberCoinTixian record) {
        MemberCoinTixian data = memberCoinTixianService.getMemberCoinTixian(record);
        return new Result(true, data);
    }


    /**
     * <p>分页查询。</p>
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Result page(Page page, MemberCoinTixian record) {
        Map<String, Object> result = new HashMap<>();

        List<MemberCoinTixian> pp = memberCoinTixianService.getMemberCoinTixianByPage(page, record);

        result.put(AppConstant.PAGE, page);
        result.put("pp", pp);
        return new Result(true, result);
    }


    /**
     * <p>保存。</p>
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(MemberCoinTixian record) {

        double coin = Double.valueOf(record.getMoney());
        if (coin <= 0) {
            return new Result(false, "不能提现负值");
        }
        int userIdInt = Integer.valueOf(record.getUserId());
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userIdInt);

        userInfo = userInfoService.getSingleUserInfo(userInfo);

        if (userInfo == null) {
            return new Result(false, "提现用户不存在");
        }

        double balance = userInfo.getMoneyCoin();

        if (balance < coin) {
            return new Result(false, "用户余额不足，不能提现");
        }

        double fee = 0;
        double cash = coin - fee;
        double moneyCoin = balance - coin;

        MemberCoin memberCoin = new MemberCoin();
        memberCoin.setUserId(record.getUserId());
        memberCoin.setMoney(String.valueOf(-cash));
        memberCoin.setBalance(String.valueOf(balance - cash));
        memberCoin.setTypeFlag(AppConstant.CoinType.CASH);
        memberCoin.setRemark("余额提现：" + cash);
        memberCoinService.createMemberCoin(memberCoin);

        if (fee > 0) {
            MemberCoin memberCoinFee = new MemberCoin();
            memberCoin.setUserId(record.getUserId());
            memberCoinFee.setMoney(String.valueOf(-fee));
            memberCoinFee.setBalance(String.valueOf(moneyCoin));
            memberCoinFee.setTypeFlag(AppConstant.CoinType.TAXES);
            memberCoinFee.setRemark("余额提现手续费：" + fee);
            memberCoinService.createMemberCoin(memberCoinFee);
        }


        UserInfo updateUser = new UserInfo();
        updateUser.setId(userIdInt);
        updateUser.setMoneyCoin(moneyCoin);
        userInfoService.updateUserInfo(updateUser);

        record.setFee(String.valueOf(fee));
        record.setNetAmount(String.valueOf(cash));
        boolean num = memberCoinTixianService.createMemberCoinTixian(record);
        if (num) {
            return new Result(true, record.getId());
        }
        return new Result(false, "保存异常");
    }

    /**
     * <p>更新信息。</p>
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result updateMemberCoinTixian(MemberCoinTixian record) {
        boolean num = memberCoinTixianService.updateMemberCoinTixian(record);
        if (num) {
            return new Result(true, "保存成功");
        }
        return new Result(false, "保存异常");
    }

    /**
     * <p>删除。</p>
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteMemberCoinTixian(@RequestParam(required = true, value = "id") String id) {

        boolean num = memberCoinTixianService.deleteMemberCoinTixian(id);
        if (num) {
            return new Result(true, "删除成功");
        }
        return new Result(false, "删除异常");
    }

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @param record
     * @throws Exception
     */
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    @ResponseBody
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, MemberCoinTixian record) throws Exception {

        List<MemberCoinTixian> memberCoinTixians = memberCoinTixianService.getMemberCoinTixianList(record);


        String sheetName = "member_coin_tixian";
        String titleName = "用户余额提现数据表";
        String fileName = "用户余额提现表";
        int columnNumber = 20;
        int[] columnWidth = {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20};
        String[] columnName = {"", "删除标识", "更新时间", "更新人", "创建时间", "创建人", "用户", "金额", "状态", "手续费", "实发金额", "放款人", "放款时间", "微信", "支付宝", "银行卡号", "开户行", "开户人", "类型", "备注"};
        String[][] dataList = new String[memberCoinTixians.size()][20];

        for (int i = 0; i < memberCoinTixians.size(); i++) {

            dataList[i][0] = String.valueOf(memberCoinTixians.get(i).getId());
            dataList[i][1] = String.valueOf(memberCoinTixians.get(i).getDelFlag());
            dataList[i][2] = String.valueOf(memberCoinTixians.get(i).getUpdateTime());
            dataList[i][3] = String.valueOf(memberCoinTixians.get(i).getUpdateUser());
            dataList[i][4] = String.valueOf(memberCoinTixians.get(i).getCreateTime());
            dataList[i][5] = String.valueOf(memberCoinTixians.get(i).getCreateUser());
            dataList[i][6] = String.valueOf(memberCoinTixians.get(i).getUserId());
            dataList[i][7] = String.valueOf(memberCoinTixians.get(i).getMoney());
            dataList[i][8] = String.valueOf(memberCoinTixians.get(i).getStatusFlag());
            dataList[i][9] = String.valueOf(memberCoinTixians.get(i).getFee());
            dataList[i][10] = String.valueOf(memberCoinTixians.get(i).getNetAmount());
            dataList[i][11] = String.valueOf(memberCoinTixians.get(i).getDealUser());
            dataList[i][12] = String.valueOf(memberCoinTixians.get(i).getDealTime());
            dataList[i][13] = String.valueOf(memberCoinTixians.get(i).getWechat());
            dataList[i][14] = String.valueOf(memberCoinTixians.get(i).getAlipay());
            dataList[i][15] = String.valueOf(memberCoinTixians.get(i).getBankCard());
            dataList[i][16] = String.valueOf(memberCoinTixians.get(i).getBankName());
            dataList[i][17] = String.valueOf(memberCoinTixians.get(i).getOpenName());
            dataList[i][18] = String.valueOf(memberCoinTixians.get(i).getTypeFlag());
            dataList[i][19] = String.valueOf(memberCoinTixians.get(i).getRemark());
        }


        ExportExcelUtil.ExportWithResponse(sheetName, titleName, fileName,
                columnNumber, columnWidth, columnName, dataList, response);


    }

    @RequestMapping(value = "/pass", method = RequestMethod.POST)
    @ResponseBody
    public Result pass(MemberCoinTixian memberCoinTixian) {

        //MemberCoinTixian tiXian = memberCoinTixianService.getMemberCoinTixianById(memberCoinTixian.getId() + "");
        //UserInfo userInfo = userService.getPersonalInfo(tiXian.getMemberId() + "");
        //SendMsgUtil.sendApplicationMsg(userInfo.getTelephone(), "您的提现申请已通过，余额将转入您所提供的银行卡，请注意查收。");

        boolean num = memberCoinTixianService.updateMemberCoinTixian(memberCoinTixian);
        if (num) {
            return new Result(true, "保存成功");
        }
        return new Result(false, "保存异常");

    }


    @RequestMapping(value = "/fail", method = RequestMethod.POST)
    @ResponseBody
    public Result fail(MemberCoinTixian memberCoinTixian) {

        MemberCoinTixian tiXian = memberCoinTixianService.getMemberCoinTixianById(memberCoinTixian.getId() + "");
        UserInfo userInfo = new UserInfo();
        userInfo.setId(Integer.valueOf(tiXian.getUserId()));

        userInfo = userInfoService.getSingleUserInfo(userInfo);
        //SendMsgUtil.sendApplicationMsg(userInfo.getTelephone(), "您的提现申请未通过，余额将返还到余额账户中，请注意查收。");

        if (userInfo != null) {


            double balance = userInfo.getMoneyCoin();

            double cash = Double.valueOf(tiXian.getMoney());
            double moneyCoin = balance + cash;

            MemberCoin memberCoin = new MemberCoin();
            memberCoin.setUserId(userInfo.getId() + "");
            memberCoin.setMoney(String.valueOf(cash));
            memberCoin.setBalance(String.valueOf(balance + cash));
            memberCoin.setTypeFlag(AppConstant.CoinType.FAN_HUAN);
            memberCoin.setRemark("余额提现失败返还：" + cash);
            memberCoinService.createMemberCoin(memberCoin);

            UserInfo updateUser = new UserInfo();
            updateUser.setId(userInfo.getId());
            updateUser.setMoneyCoin(moneyCoin);
            userInfoService.updateUserInfo(updateUser);

            memberCoinTixian.setDealTime(DateTimeTool.dateTimeToTimeYYYYHHmmStr(new Date()));

            boolean num = memberCoinTixianService.updateMemberCoinTixian(memberCoinTixian);
            if (num) {
                return new Result(true, "保存成功");
            }

        }
        return new Result(false, "保存异常");

    }

}

