package cn.com.ctop.finance.payment.controller;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.finance.payment.entity.FinancePaymentRechargeApplication;
import cn.com.ctop.finance.payment.service.IFinancePaymentRechargeAccountService;
import cn.com.ctop.finance.payment.service.IFinancePaymentRechargeApplicationService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 充值申请表
 */
@Slf4j
@Api(tags = "充值申请表")
@RestController
@RequestMapping("/financePayment/rechargeApplication")
public class FinancePaymentRechargeApplicationController {
    @Autowired
    private IFinancePaymentRechargeApplicationService financePaymentRechargeApplicationService;

    @Autowired
    private IFinancePaymentRechargeAccountService rechargeAccountService;
    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 分页列表查询
     */
    @ApiOperation(value = "充值申请表-分页列表查询", notes = "充值申请表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<Object> queryPageList(FinancePaymentRechargeApplication recharge,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            //查询用户角色
            String roleCode = sysRoleService.getRoleCodeByUserId(recharge.getUserId());
            if ("saleAssistant".equals(roleCode)) {
                //曹媛 可以看所有人的
                if ("4f6454dbad954a8094013bf4c6d74796".equals(recharge.getUserId()) || "163a4cc9a72c425e873d36d08e75f2cd".equals(recharge.getUserId())) {
                    List<String> userIds = new ArrayList<>();
                    userIds.add("4f6454dbad954a8094013bf4c6d74796");//曹媛 销售助理
                    userIds.add("42e137a90ca94cbfa89b21b306cb2e78");//侯加鑫
                    userIds.add("959842590bfc4ad38e0aced255177ced");//王维新
                    userIds.add("f0190eaabfb4488caa22e123e94dadc8");//高洪哲
                    userIds.add("f33798b117a3486a9fae7ba0dab2e0be");//赵欣 销售助理
                    userIds.add("515b962ad5544991b17e744df2b87bab");//支春雨 销售助理
                    userIds.add("5c6abd3bc1d64a1aa365157f7edd3ecd");//关蕊 销售助理
                    userIds.add("2f2d8cd186db4ddcbfc38ead7d116e1c");//许安鑫 销售助理
                    userIds.add("02afeb64079043e6b9d6c9581dcef164");//李小治
                    userIds.add("ec8f6954b6ae49e7a356d173dd6568d1");//王莹
                    userIds.add("96058e7c29f14e4380dfbdddde21175b");//杜鑫艳 销售助理
                    userIds.add("fe4965692844468798e4fc265e3cdfc8");//崔泽
                    userIds.add("9a99a2e906b64f5082f87c3a60a20b2e");//王明雨
                    userIds.add("e2d55e2888e849ed911bc89b72fc8211");//支一淼 销售助理
                    userIds.add("102f7edf378b42d2a730d28d11a8cc1e");//张鹤玲  销售助理
                    userIds.add("163a4cc9a72c425e873d36d08e75f2cd");//陈心瑞 销售助理
                    userIds.add("5398af2d95874451aa012ebb8a15c50d");//陈颖
                    userIds.add("b2b6f57dd1a848cd8397e319cd9db1fc");//周菁
                    recharge.setUserIds(userIds);
                } else if ("f33798b117a3486a9fae7ba0dab2e0be".equals(recharge.getUserId())
                        || "515b962ad5544991b17e744df2b87bab".equals(recharge.getUserId())
                        || "5c6abd3bc1d64a1aa365157f7edd3ecd".equals(recharge.getUserId())
                        || "2f2d8cd186db4ddcbfc38ead7d116e1c".equals(recharge.getUserId())
                        || "96058e7c29f14e4380dfbdddde21175b".equals(recharge.getUserId())

                ) {
                    /*销售助理 关蕊组 5c6abd3bc1d64a1aa365157f7edd3ecd：侯加鑫、王维新、高洪哲             */
                    List<String> userIds = new ArrayList<>();
                    userIds.add("4f6454dbad954a8094013bf4c6d74796");//曹媛 销售助理
                    userIds.add("42e137a90ca94cbfa89b21b306cb2e78");//侯加鑫
                    userIds.add("959842590bfc4ad38e0aced255177ced");//王维新
                    userIds.add("f0190eaabfb4488caa22e123e94dadc8");//高洪哲
                    userIds.add("f33798b117a3486a9fae7ba0dab2e0be");//赵欣 销售助理
                    userIds.add("515b962ad5544991b17e744df2b87bab");//支春雨 销售助理
                    userIds.add("5c6abd3bc1d64a1aa365157f7edd3ecd");//关蕊 销售助理
                    userIds.add("2f2d8cd186db4ddcbfc38ead7d116e1c");//许安鑫 销售助理
                    userIds.add("02afeb64079043e6b9d6c9581dcef164");//李小治
                    userIds.add("ec8f6954b6ae49e7a356d173dd6568d1");//王莹
                    userIds.add("96058e7c29f14e4380dfbdddde21175b");//杜鑫艳 销售助理
                    recharge.setUserIds(userIds);
                } else if ("e2d55e2888e849ed911bc89b72fc8211".equals(recharge.getUserId())
                        || "102f7edf378b42d2a730d28d11a8cc1e".equals(recharge.getUserId())
                ) {
                    /*销售助理 陈心瑞组：崔泽、王明雨                 */
                    List<String> userIds = new ArrayList<>();
                    userIds.add("163a4cc9a72c425e873d36d08e75f2cd");//陈心瑞 销售助理
                    userIds.add("fe4965692844468798e4fc265e3cdfc8");//崔泽
                    userIds.add("9a99a2e906b64f5082f87c3a60a20b2e");//王明雨
                    userIds.add("e2d55e2888e849ed911bc89b72fc8211");//支一淼 销售助理
                    userIds.add("102f7edf378b42d2a730d28d11a8cc1e");//张鹤玲  销售助理
                    userIds.add("42e137a90ca94cbfa89b21b306cb2e78");//侯加鑫
                    userIds.add("959842590bfc4ad38e0aced255177ced");//王维新
                    recharge.setUserIds(userIds);
                } else {
                    recharge.setApplicanterId(recharge.getUserId());
                }
            }
            return financePaymentRechargeApplicationService.queryPageList(recharge, pageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败！");
        }
    }

    /**
     * 查询充值账户详情
     */
    @GetMapping(value = "/queryRechargeAccountDetails")
    public Result<Object> queryRechargeAccountDetails(Long rechargeId) {
        try {
            return financePaymentRechargeApplicationService.queryRechargeAccountDetails(rechargeId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败！");
        }
    }

    /**
     * 添加
     */
    @PostMapping(value = "/add")
    public Result add(@RequestBody JSONObject data) {
        try {
            return financePaymentRechargeApplicationService.add(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("新增异常");
    }

    /**
     * 更新
     */
    @PostMapping(value = "/editAll")
    public Result<Object> editAll(@RequestBody JSONObject data) {
        try {
            FinancePaymentRechargeApplication recharge = JSONObject.parseObject(JSONObject.toJSONString(data), FinancePaymentRechargeApplication.class);
            financePaymentRechargeApplicationService.updateById(recharge);
            return Result.ok();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("修改异常");
    }

    /**
     * 编辑
     */
    @PostMapping(value = "/edit")
    public Result<Object> edit(@RequestBody JSONObject data) {
        try {
            return financePaymentRechargeApplicationService.edit(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("修改异常");
    }

    /**
     * 更改状态
     */
    @PostMapping(value = "/updateStatus")
    public Result<Object> updateStatus(@RequestBody JSONObject data) {
        try {
            return financePaymentRechargeApplicationService.updateStatus(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("修改异常");
    }

    /**
     * 通过id删除
     */
    @GetMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            FinancePaymentRechargeApplication application = financePaymentRechargeApplicationService.getById(id);
            if (Check.isNull(application)) {
                return Result.error("未找到对应实体");
            }
            if ("1".equals(application.getAuditStatus()) || "2".equals(application.getAuditStatus())) {
                financePaymentRechargeApplicationService.removeById(id);
                rechargeAccountService.delByRechargeId(Long.valueOf(id));
            } else {
                return Result.error("当前状态不允许删除！");
            }
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 通过id查询
     */
    @GetMapping(value = "/queryById")
    public Result<FinancePaymentRechargeApplication> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FinancePaymentRechargeApplication> result = new Result<>();
        FinancePaymentRechargeApplication financePaymentRechargeApplication = financePaymentRechargeApplicationService.getById(id);
        if (financePaymentRechargeApplication == null) {
            result.error500("未找到对应实体");
        } else {
            financePaymentRechargeApplication.setPortName(getName(financePaymentRechargeApplication.getPaymentPort()));
            result.setResult(financePaymentRechargeApplication);
            result.setSuccess(true);
        }
        return result;
    }

    public String getName(String paymentPort) {
        if ("1".equals(paymentPort)) {
            return "汇创";
        } else if ("2".equals(paymentPort)) {
            return "骄阳";
        } else if ("3".equals(paymentPort)) {
            return "江西五七";
        } else {
            return "北京五六七";
        }
    }

    /**
     * 上传临时文件，更新状态
     */
    @PostMapping(value = "/updateTemporaryFiles")
    public Result<Object> updateTemporaryFiles(@RequestBody JSONObject data) {
        try {
            return financePaymentRechargeApplicationService.updateTemporaryFiles(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("数据异常");
    }

    /**
     * 查询审核流程
     */
    @GetMapping(value = "/queryAuditProcess")
    public Result<Object> queryAuditProcess(Long id) {
        try {
            if (Check.isNull(id)) {
                return Result.error("缺少参数");
            }
            return financePaymentRechargeApplicationService.queryAuditProcess(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询异常");
    }


    /**
     * 下载
     */
    @GetMapping(value = "/excelInfo")
    public void excelInfo(HttpServletResponse response, FinancePaymentRechargeApplication recharge,
                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            //查询用户角色
            String roleCode = sysRoleService.getRoleCodeByUserId(recharge.getUserId());
            if ("saleAssistant".equals(roleCode)) {
                //曹媛 可以看所有人的
                if ("4f6454dbad954a8094013bf4c6d74796".equals(recharge.getUserId()) || "163a4cc9a72c425e873d36d08e75f2cd".equals(recharge.getUserId())) {
                    List<String> userIds = new ArrayList<>();
                    userIds.add("4f6454dbad954a8094013bf4c6d74796");//曹媛 销售助理
                    userIds.add("42e137a90ca94cbfa89b21b306cb2e78");//侯加鑫
                    userIds.add("959842590bfc4ad38e0aced255177ced");//王维新
                    userIds.add("f0190eaabfb4488caa22e123e94dadc8");//高洪哲
                    userIds.add("f33798b117a3486a9fae7ba0dab2e0be");//赵欣 销售助理
                    userIds.add("515b962ad5544991b17e744df2b87bab");//支春雨 销售助理
                    userIds.add("5c6abd3bc1d64a1aa365157f7edd3ecd");//关蕊 销售助理
                    userIds.add("2f2d8cd186db4ddcbfc38ead7d116e1c");//许安鑫 销售助理
                    userIds.add("02afeb64079043e6b9d6c9581dcef164");//李小治
                    userIds.add("ec8f6954b6ae49e7a356d173dd6568d1");//王莹
                    userIds.add("96058e7c29f14e4380dfbdddde21175b");//杜鑫艳 销售助理
                    userIds.add("fe4965692844468798e4fc265e3cdfc8");//崔泽
                    userIds.add("9a99a2e906b64f5082f87c3a60a20b2e");//王明雨
                    userIds.add("e2d55e2888e849ed911bc89b72fc8211");//支一淼 销售助理
                    userIds.add("102f7edf378b42d2a730d28d11a8cc1e");//张鹤玲  销售助理
                    userIds.add("163a4cc9a72c425e873d36d08e75f2cd");//陈心瑞 销售助理
                    userIds.add("5398af2d95874451aa012ebb8a15c50d");//陈颖
                    userIds.add("b2b6f57dd1a848cd8397e319cd9db1fc");//周菁
                    recharge.setUserIds(userIds);
                } else if ("f33798b117a3486a9fae7ba0dab2e0be".equals(recharge.getUserId())
                        || "515b962ad5544991b17e744df2b87bab".equals(recharge.getUserId())
                        || "2f2d8cd186db4ddcbfc38ead7d116e1c".equals(recharge.getUserId())
                        || "5c6abd3bc1d64a1aa365157f7edd3ecd".equals(recharge.getUserId())
                        || "96058e7c29f14e4380dfbdddde21175b".equals(recharge.getUserId())

                ) {
                    /*销售助理 关蕊组 5c6abd3bc1d64a1aa365157f7edd3ecd：侯加鑫、王维新、高洪哲             */
                    List<String> userIds = new ArrayList<>();
                    userIds.add("4f6454dbad954a8094013bf4c6d74796");//曹媛 销售助理
                    userIds.add("42e137a90ca94cbfa89b21b306cb2e78");//侯加鑫
                    userIds.add("959842590bfc4ad38e0aced255177ced");//王维新
                    userIds.add("f0190eaabfb4488caa22e123e94dadc8");//高洪哲
                    userIds.add("f33798b117a3486a9fae7ba0dab2e0be");//赵欣 销售助理
                    userIds.add("515b962ad5544991b17e744df2b87bab");//支春雨 销售助理
                    userIds.add("5c6abd3bc1d64a1aa365157f7edd3ecd");//关蕊 销售助理
                    userIds.add("2f2d8cd186db4ddcbfc38ead7d116e1c");//许安鑫
                    userIds.add("02afeb64079043e6b9d6c9581dcef164");//李小治
                    userIds.add("ec8f6954b6ae49e7a356d173dd6568d1");//王莹
                    userIds.add("96058e7c29f14e4380dfbdddde21175b");//杜鑫艳 销售助理
                    recharge.setUserIds(userIds);
                } else if (
                        "e2d55e2888e849ed911bc89b72fc8211".equals(recharge.getUserId())
                                || "102f7edf378b42d2a730d28d11a8cc1e".equals(recharge.getUserId())
                ) {

                    /*销售助理 陈心瑞组：崔泽、王明雨                 */
                    List<String> userIds = new ArrayList<>();
                    userIds.add("163a4cc9a72c425e873d36d08e75f2cd");//陈心瑞 销售助理
                    userIds.add("42e137a90ca94cbfa89b21b306cb2e78");//侯加鑫
                    userIds.add("959842590bfc4ad38e0aced255177ced");//王维新
                    userIds.add("fe4965692844468798e4fc265e3cdfc8");//崔泽
                    userIds.add("9a99a2e906b64f5082f87c3a60a20b2e");//王明雨
                    userIds.add("e2d55e2888e849ed911bc89b72fc8211");//支一淼 销售助理
                    userIds.add("102f7edf378b42d2a730d28d11a8cc1e");//张鹤玲  销售助理
                    recharge.setUserIds(userIds);
                } else {
                    recharge.setApplicanterId(recharge.getUserId());
                }
            }

            List<JSONObject> list = financePaymentRechargeApplicationService.queryAccountList(recharge);
            List<List<Object>> excelList = new ArrayList<>();
            if (!list.isEmpty()) {
                Map<String, String> map = getStatusStr();
                list.forEach(data -> {
                    List<Object> temp = new ArrayList<>();
                    temp.add(data.getString("advertiserName"));
                    temp.add(data.getString("agentName"));
                    String amends = data.getString("amends");
                    temp.add("1".equals(amends) ? "是" : "否");
                    temp.add(data.getString("productName"));
                    if ("-".equals(data.getString("projectName"))) {
                        temp.add("-");
                    } else {
                        temp.add(data.getString("projectName") + "（" + data.getString("projectId") + "）");
                    }
                    temp.add(data.getString("accountId"));
                    temp.add(data.getString("accountName"));
                    temp.add(data.getString("cashAmounts"));
                    temp.add(data.getString("receivedAmounts"));
                    temp.add(data.getString("rebateRate"));
                    String rebateType = data.getString("rebateType");
                    temp.add("1".equals(rebateType) ? "返货" : "返现");
                    temp.add(data.getString("applicanter"));
                    temp.add(data.getString("createTime"));
                    temp.add(map.get(data.getString("auditStatus")));
                    temp.add(data.getString("remarks"));
                    temp.add(data.getString("approvalContent"));
                    excelList.add(temp);
                });
            }

            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            String[] titles = {"客户名称", "代理商", "是否后补", "产品名称", "项目", "账户ID", "账户名称", "现金金额", "账显金额",
                    "返点比例", "返点类型", "申请人", "申请时间", "状态", "充值备注", "拒绝原因"};
            eeu.exportExcelForAttendance(workbook, 0, "充值列表", titles, excelList);
            HttpUtils.setResponseHeader(response, "info.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String, String> getStatusStr() {
        Map<String, String> map = new HashMap<>();
        map.put("-1", "退回修改");
        map.put("0", "创建申请");
        map.put("1", "待审核");
        map.put("2", "待充值");
        map.put("3", "充值完成");
        map.put("4", "临时充值");
        map.put("5", "审核拒绝");
        return map;
    }

}
