package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.EasyExcelUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsPayQrCode;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.BsPayQrCodeService;
import com.hfkj.sysenum.PayQrCodeStatusEnum;
import com.hfkj.sysenum.SecUserTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/payQrCode")
@Api(value = "支付二维码")
public class BsPayQrCodeController {

    private static Logger log = LoggerFactory.getLogger(BsPayQrCodeController.class);

    @Resource
    private BsPayQrCodeService payQrCodeService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value = "/generatePayQrCode", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "生成支付二维码")
    public ResponseData generatePayQrCode(@RequestBody JSONObject body) {
        try {

            if (body.getInteger("generateNum") == null) {
                log.error("BsPayQrCodeController --> getOrganizationTree() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            payQrCodeService.generatePayQrCode(body.getInteger("generateNum"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("BsPayQrCodeController --> generatePayQrCode() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/assignCompany", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配公司")
    public ResponseData assignCompany(@RequestBody JSONObject body) {
        try {

            if (body.getLong("companyId") == null
                    || body.getJSONArray("qrCodeArray") == null
                    || body.getJSONArray("qrCodeArray").size() == 0
            ) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            List<Long> qrCodeIdList = new ArrayList<>();
            for (Object obj : body.getJSONArray("qrCodeArray")) {
                JSONObject data = (JSONObject) obj;
                if (data.getLong("id") == null) {
                    log.error("BsDeviceController error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                qrCodeIdList.add(data.getLong("id"));
            }

            payQrCodeService.batchAssignCompany(body.getLong("companyId"), qrCodeIdList);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("BsPayQrCodeController --> assignAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/assignAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配代理商")
    public ResponseData assignAgent(@RequestBody JSONObject body) {
        try {

            if (body.getLong("agentId") == null
                    || body.getJSONArray("qrCodeArray") == null
                    || body.getJSONArray("qrCodeArray").size() == 0
            ) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            List<Long> qrCodeIdList = new ArrayList<>();
            for (Object obj : body.getJSONArray("qrCodeArray")) {
                JSONObject data = (JSONObject) obj;
                if (data.getLong("id") == null) {
                    log.error("BsDeviceController error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                qrCodeIdList.add(data.getLong("id"));
            }

            payQrCodeService.batchAssignAgent(body.getLong("agentId"), qrCodeIdList);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("BsPayQrCodeController --> assignAgent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/assignSalesman", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配业务员")
    public ResponseData assignSalesman(@RequestBody JSONObject body) {
        try {

            if (body.getLong("salesmanId") == null
                    || body.getJSONArray("qrCodeArray") == null
                    || body.getJSONArray("qrCodeArray").size() == 0
            ) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            List<Long> qrCodeIdList = new ArrayList<>();
            for (Object obj : body.getJSONArray("qrCodeArray")) {
                JSONObject data = (JSONObject) obj;
                if (data.getLong("id") == null) {
                    log.error("BsDeviceController error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                qrCodeIdList.add(data.getLong("id"));
            }

            payQrCodeService.batchAssignSalesman(body.getLong("salesmanId"), qrCodeIdList);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("BsPayQrCodeController --> assignSalesman() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/bindStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "绑定门店")
    public ResponseData bindStore(@RequestBody JSONObject body) {
        try {

            if (body.getLong("qrCodeId") == null || body.getLong("storeId") == null) {
                log.error("configAccount error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            payQrCodeService.bindStore(body.getLong("storeId"),body.getLong("qrCodeId"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/unbindStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "解绑门店")
    public ResponseData unbindStore(@RequestBody JSONObject body) {
        try {

                if (body.getLong("qrCodeId") == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            payQrCodeService.unbindStore(body.getLong("qrCodeId"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/disabled",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用")
    public ResponseData disabled(@RequestBody JSONObject body) {
        try {

            if (body.getLong("qrCodeId") == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            payQrCodeService.disabled(body.getLong("qrCodeId"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/enable",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "启用")
    public ResponseData enable(@RequestBody JSONObject body) {
        try {

            if (body.getLong("qrCodeId") == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            payQrCodeService.enable(body.getLong("qrCodeId"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getQrCodeList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询二维码列表")
    public ResponseData getQrCodeList(@RequestParam(name = "companyId", required = false) Long companyId,
                                      @RequestParam(name = "agentId", required = false) Long agentId,
                                      @RequestParam(name = "agentName", required = false) String agentName,
                                      @RequestParam(name = "salesmanId", required = false) Long salesmanId,
                                      @RequestParam(name = "salesmanName", required = false) String salesmanName,
                                      @RequestParam(name = "merId", required = false) Long merId,
                                      @RequestParam(name = "merName", required = false) String merName,
                                      @RequestParam(name = "storeId", required = false) Long storeId,
                                      @RequestParam(name = "storeName", required = false) String storeName,
                                      @RequestParam(name = "serialNumber", required = false) String serialNumber,
                                      @RequestParam(name = "isAssignCompany", required = false) Boolean isAssignCompany,
                                      @RequestParam(name = "isAssignAgent", required = false) Boolean isAssignAgent,
                                      @RequestParam(name = "isAssignSalesman", required = false) Boolean isAssignSalesman,
                                      @RequestParam(name = "isAssignStore", required = false) Boolean isAssignStore,
                                      @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                      @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("serialNumber", serialNumber);
            param.put("isAssignCompany", isAssignCompany);
            param.put("isAssignAgent", isAssignAgent);
            param.put("isAssignSalesman", isAssignSalesman);
            param.put("isAssignStore", isAssignStore);

            if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type0.getNumber())) {
                param.put("companyId", companyId);
                param.put("agentId", agentId);
                param.put("agentName", agentName);
                param.put("salesmanId", salesmanId);
                param.put("salesmanName", salesmanName);
                param.put("merId", merId);
                param.put("merName", merName);
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type1.getNumber())) {
                param.put("companyId", userModel.getBsCompany().getId());
                param.put("agentId", agentId);
                param.put("agentName", agentName);
                param.put("salesmanId", salesmanId);
                param.put("salesmanName", salesmanName);
                param.put("merId", merId);
                param.put("merName", merName);
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type2.getNumber())) {
                param.put("agentId", userModel.getAgent().getId());
                param.put("salesmanId", salesmanId);
                param.put("salesmanName", salesmanName);
                param.put("merId", merId);
                param.put("merName", merName);
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type3.getNumber())) {
                param.put("salesmanId", userModel.getSalesman().getId());
                param.put("merId", merId);
                param.put("merName", merName);
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type4.getNumber())) {
                param.put("merId", userModel.getMer().getId());
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type5.getNumber())) {
                param.put("storeId", userModel.getStore().getId());

            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(payQrCodeService.getQrCodeList(param)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }



    @RequestMapping(value="/exportQrCodeList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出二维码列表")
    public ResponseData exportQrCodeList(@RequestParam(name = "companyId", required = false) Long companyId,
                                      @RequestParam(name = "agentId", required = false) Long agentId,
                                      @RequestParam(name = "agentName", required = false) String agentName,
                                      @RequestParam(name = "salesmanId", required = false) Long salesmanId,
                                      @RequestParam(name = "salesmanName", required = false) String salesmanName,
                                      @RequestParam(name = "merId", required = false) Long merId,
                                      @RequestParam(name = "merName", required = false) String merName,
                                      @RequestParam(name = "storeId", required = false) Long storeId,
                                      @RequestParam(name = "storeName", required = false) String storeName,
                                      @RequestParam(name = "serialNumber", required = false) String serialNumber,
                                      @RequestParam(name = "isAssignCompany", required = false) Boolean isAssignCompany,
                                      @RequestParam(name = "isAssignAgent", required = false) Boolean isAssignAgent,
                                      @RequestParam(name = "isAssignSalesman", required = false) Boolean isAssignSalesman,
                                      @RequestParam(name = "isAssignStore", required = false) Boolean isAssignStore) {
        try {

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("serialNumber", serialNumber);
            param.put("isAssignCompany", isAssignCompany);
            param.put("isAssignAgent", isAssignAgent);
            param.put("isAssignSalesman", isAssignSalesman);
            param.put("isAssignStore", isAssignStore);

            if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type0.getNumber())) {
                param.put("companyId", companyId);
                param.put("agentId", agentId);
                param.put("agentName", agentName);
                param.put("salesmanId", salesmanId);
                param.put("salesmanName", salesmanName);
                param.put("merId", merId);
                param.put("merName", merName);
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type1.getNumber())) {
                param.put("companyId", userModel.getBsCompany().getId());
                param.put("agentId", agentId);
                param.put("agentName", agentName);
                param.put("salesmanId", salesmanId);
                param.put("salesmanName", salesmanName);
                param.put("merId", merId);
                param.put("merName", merName);
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type2.getNumber())) {
                param.put("agentId", userModel.getAgent().getId());
                param.put("salesmanId", salesmanId);
                param.put("salesmanName", salesmanName);
                param.put("merId", merId);
                param.put("merName", merName);
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type3.getNumber())) {
                param.put("salesmanId", userModel.getSalesman().getId());
                param.put("merId", merId);
                param.put("merName", merName);
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type4.getNumber())) {
                param.put("merId", userModel.getMer().getId());
                param.put("storeId", storeId);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type5.getNumber())) {
                param.put("storeId", userModel.getStore().getId());

            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            List<List<Object>> dataList = new ArrayList<>();
            List<Object> data;

            List<BsPayQrCode> qrCodeList = payQrCodeService.getQrCodeList(param);
            for (BsPayQrCode payQrCode : qrCodeList) {
                data = new ArrayList<>();
                data.add(payQrCode.getSerialNumber());
                data.add(payQrCode.getQrCodeUrl());
                data.add(payQrCode.getQrCodeData());
                data.add(payQrCode.getWechatQrCodeUrl());
                data.add(payQrCode.getCompanyName());
                data.add(payQrCode.getAgentName());
                data.add(payQrCode.getSalesmanName());
                data.add(payQrCode.getMerName());
                data.add(payQrCode.getStoreName());
                data.add(PayQrCodeStatusEnum.getDataByNumber(payQrCode.getStatus()).getName());
                dataList.add(data);
            }

            List<String> headList = new ArrayList<>();;
            headList.add("序列号");
            headList.add("二维码图片地址");
            headList.add("二维码访问地址");
            headList.add("微信公众号访问地址");
            headList.add("公司");
            headList.add("代理商");
            headList.add("业务员");
            headList.add("商户");
            headList.add("门店");
            headList.add("状态");

            String fileUrl = CommonSysConst.getSysConfig().getFilesystem() + "/temporary/";
            String pathName = System.currentTimeMillis()+".xlsx";
            File file = new File(fileUrl);
            if (!file.exists()) {
                file.mkdirs();
            }
            EasyExcel.write(fileUrl+pathName).head(EasyExcelUtil.generationHead(headList)).sheet("支付二维码").doWrite(dataList);
            return ResponseMsgUtil.success(pathName);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
