package com.bweb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.Base64Util;
import com.hai.common.QRCodeGenerator;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.AESEncodeUtil;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.IDGenerator;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonSysConst;
import com.hai.entity.HighGasStaff;
import com.hai.entity.HighMerchantStore;
import com.hai.enum_type.GasStaffStatus;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.CommonService;
import com.hai.service.HighGasStaffService;
import com.hai.service.HighMerchantStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.utils.URLEncodedUtils;
import org.bouncycastle.util.encoders.UrlBase64Encoder;
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.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/gasStaff")
@Api(value = "加油站员工管理")
public class HighGasStaffController {

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

    @Resource
    private HighGasStaffService gasStaffService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private CommonService commonService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/addGasStaff",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加员工")
    public ResponseData addStaff(@RequestBody JSONObject body) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            if (userInfoModel.getMerchantStore() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            if (StringUtils.isBlank(body.getString("name"))
                || StringUtils.isBlank(body.getString("telephone"))
                || StringUtils.isBlank(body.getString("positionType"))
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighGasStaff gasStaff = new HighGasStaff();
            gasStaff.setMerchantStoreId(userInfoModel.getMerchantStore().getId());
            gasStaff.setAvatar(body.getString("avatar"));
            gasStaff.setName(body.getString("name"));
            gasStaff.setTelephone(body.getString("telephone"));
            gasStaff.setPositionType(body.getInteger("positionType"));
            gasStaff.setPositionName(commonService.getDictionaryCodeName("GAS_STAFF_POSITION_TYPE", body.getString("positionType")));
            gasStaffService.addStaff(gasStaff);

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

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

    @RequestMapping(value="/updateGasStaff",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改员工")
    public ResponseData updateGasStaff(@RequestBody JSONObject body) {
        try {
            if (body.getLong("id") == null
                    || StringUtils.isBlank(body.getString("name"))
                    || StringUtils.isBlank(body.getString("telephone"))
                    || StringUtils.isBlank(body.getString("positionType"))
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询员工信息
            HighGasStaff gasStaff = gasStaffService.getStaffDetailById(body.getLong("id"));
            if (gasStaff == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到员工信息");
            }
            gasStaff.setAvatar(body.getString("avatar"));
            gasStaff.setName(body.getString("name"));
            gasStaff.setTelephone(body.getString("telephone"));
            gasStaff.setPositionType(body.getInteger("positionType"));
            gasStaff.setPositionName(commonService.getDictionaryCodeName("GAS_STAFF_POSITION_TYPE", body.getString("positionType")));
            gasStaffService.updateStaff(gasStaff);

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

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

    @RequestMapping(value="/queryQrCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询二维码")
    public ResponseData queryQrCode(@RequestBody JSONObject body) {
        try {
            if (body.getLong("gasStaffId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询员工信息
            HighGasStaff gasStaff = gasStaffService.getStaffDetailById(body.getLong("gasStaffId"));
            if (gasStaff == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到员工信息");
            }

            if (StringUtils.isBlank(gasStaff.getQrCodeImgUrl())) {

                // 查询加油站
                HighMerchantStore merchantStore = merchantStoreService.getDetailById(gasStaff.getMerchantStoreId());
                if (merchantStore == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站信息");
                }
                // 查询秘钥
                String key = commonService.getDictionaryCodeName("QR_CODE_SIGN_KEY", "1");
                if (StringUtils.isBlank(key)) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "查询失败");
                }

                // 员工ID签名
                String signId = AESEncodeUtil.base64Encode(AESEncodeUtil.aesEncryptToBytes(gasStaff.getId().toString(), key));

                // 生成二维码
                String param = CommonSysConst.getSysConfig().getHsgDomainName()+"/hsgH5?accountId=000000&gasKey=" + merchantStore.getStoreKey() + "&staffCode=" + URLEncoder.encode(signId, "UTF-8");
                String qrCodeImgUrl = DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + IDGenerator.nextId(1) +".jpg";
                QRCodeGenerator.generateQRCodeImage(param, 350, 350, SysConst.getSysConfig().getFileUrl()+"/gasStaff/"+qrCodeImgUrl);

                gasStaff.setQrCodeImgUrl(qrCodeImgUrl);
                gasStaffService.updateStaff(gasStaff);
            }

            return ResponseMsgUtil.success(gasStaff.getQrCodeImgUrl());

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

    @RequestMapping(value="/disabled",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用员工")
    public ResponseData disabled(@RequestBody JSONObject body) {
        try {
            if (body.getLong("staffId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询油站员工
            HighGasStaff gasStaff = gasStaffService.getStaffDetailById(body.getLong("staffId"));
            if (gasStaff ==  null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "未找到员工");
            }
            gasStaff.setStatus(GasStaffStatus.status2.getStatus());
            gasStaffService.editData(gasStaff);

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

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

    @RequestMapping(value="/recover",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "恢复正常")
    public ResponseData recover(@RequestBody JSONObject body) {
        try {
            if (body.getLong("staffId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询油站员工
            HighGasStaff gasStaff = gasStaffService.getStaffDetailById(body.getLong("staffId"));
            if (gasStaff ==  null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "未找到员工");
            }
            gasStaff.setStatus(GasStaffStatus.status1.getStatus());
            gasStaffService.editData(gasStaff);
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/delStaff",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除员工")
    public ResponseData delStaff(@RequestBody JSONObject body) {
        try {

            if (body.getLong("staffId") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            gasStaffService.delStaff(body.getLong("staffId"));
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/getStaffDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询员工详情")
    public ResponseData getStaffDetail(@RequestParam(name = "staffId", required = true) Long staffId) {
        try {

            return ResponseMsgUtil.success(gasStaffService.getStaffDetailById(staffId));

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


    @RequestMapping(value="/getStaffList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询员工列表")
    public ResponseData getStaffList(@RequestParam(name = "merchantStoreId", required = false) Long merchantStoreId,
                                     @RequestParam(name = "name", required = false) String name,
                                     @RequestParam(name = "telephone", required = false) String telephone,
                                     @RequestParam(name = "positionType", required = false) Integer positionType,
                                     @RequestParam(name = "status", required = false) Integer status,
                                     @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                     @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, Object> param = new HashMap<>();
            if (merchantStoreId == null) {
                UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
                if (userInfoModel == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
                }
                if (userInfoModel.getMerchantStore() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
                }
                param.put("merchantStoreId", userInfoModel.getMerchantStore().getId());
            } else {
                param.put("merchantStoreId", merchantStoreId);
            }
            param.put("name", name);
            param.put("telephone", telephone);
            param.put("positionType", positionType);
            param.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(gasStaffService.getStaffList(param)));

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

}
