package com.hfkj.service.gas.impl;

import com.hfkj.common.QRCodeGenerator;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.MD5Util;
import com.hfkj.config.CommonSysConst;
import com.hfkj.dao.BsGasStaffMapper;
import com.hfkj.entity.BsGasStaff;
import com.hfkj.entity.BsGasStaffExample;
import com.hfkj.entity.BsMerchant;
import com.hfkj.entity.SecUser;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.gas.BsGasStaffService;
import com.hfkj.service.sec.SecUserService;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import com.hfkj.sysenum.SecUserStatusEnum;
import com.hfkj.sysenum.gas.GasStaffStatus;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("gasStaffService")
public class BsGasStaffServiceImpl implements BsGasStaffService {

    @Resource
    private BsGasStaffMapper gasStaffMapper;
    @Resource
    private SecUserService userService;
    @Resource
    private BsMerchantService merchantService;

    @Override
    public void editData(BsGasStaff gasStaff) {
        if (gasStaff.getId() == null) {
            gasStaff.setCreateTime(new Date());
            gasStaff.setUpdateTime(new Date());
            gasStaff.setStatus(GasStaffStatus.status1.getStatus());
            gasStaffMapper.insert(gasStaff);
        } else {
            gasStaff.setUpdateTime(new Date());
            gasStaffMapper.updateByPrimaryKey(gasStaff);
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void addStaff(BsGasStaff gasStaff) throws Exception {
        if (userService.getDetailByLoginName(gasStaff.getTelephone()) != null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "电话已存在，请更换");
        }
        // 查询商户
        BsMerchant merchant = merchantService.getMerchant(gasStaff.getMerId());
        if (merchant == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }

        editData(gasStaff);

        // 二维码
        String qrContent = CommonSysConst.getSysConfig().getDomainName() + "/cwebh5/#/petrolStation/comfirmOrder/index?merNo=" + merchant.getMerNo()+"&gasStaffId="+gasStaff.getId();
        String qrCodeFile = "/merOilQrCode/" + merchant.getMerNo() + "/" + System.currentTimeMillis() + ".png";
        QRCodeGenerator.generateQRCodeImage(
                qrContent,
                350,
                350,
                CommonSysConst.getSysConfig().getFilesystem() + qrCodeFile);
        gasStaff.setQrCodeImgUrl(qrCodeFile);
        editData(gasStaff);

        SecUser secUser = new SecUser();
        secUser.setAvatar(gasStaff.getAvatar());
        secUser.setUserName(gasStaff.getName());
        secUser.setLoginName(gasStaff.getTelephone());
        secUser.setPassword(MD5Util.encode("123654".getBytes()));
        secUser.setStatus(1);
        secUser.setRoleId(4L);
        secUser.setObjectType(SecUserObjectTypeEnum.type3.getCode());
        secUser.setObjectId(gasStaff.getId());
        secUser.setCreateTime(new Date());
        secUser.setUpdateTime(new Date());
        userService.editUser(secUser);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void updateStaff(BsGasStaff gasStaff) {
        BsGasStaff detail = getStaffDetailById(gasStaff.getId());
        if (detail == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }

        if (!detail.getTelephone().equals(gasStaff.getTelephone())) {
            if (userService.getDetailByLoginName(gasStaff.getTelephone()) != null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "电话已存在，请更换");
            }
        }

        editData(gasStaff);

        // 查询账户
        SecUser account = userService.getDetail(SecUserObjectTypeEnum.type3, gasStaff.getId());
        if (account == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到账户");
        }
        account.setAvatar(gasStaff.getAvatar());
        account.setUserName(gasStaff.getName());
        account.setLoginName(gasStaff.getTelephone());
        account.setUpdateTime(new Date());
        userService.editUser(account);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void delStaff(Long id) {
        BsGasStaff gasStaff = getStaffDetailById(id);
        if (gasStaff ==  null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到员工");
        }
        gasStaff.setStatus(GasStaffStatus.status0.getStatus());
        editData(gasStaff);

        // 查询账户
        SecUser account = userService.getDetail(SecUserObjectTypeEnum.type3, gasStaff.getId());
        if (account == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到账户");
        }
        account.setStatus(0);
        userService.editUser(account);
    }

    @Override
    public void disabled(Long id) {
        // 查询油站员工
        BsGasStaff gasStaff = getStaffDetailById(id);
        if (gasStaff ==  null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到员工");
        }
        gasStaff.setStatus(GasStaffStatus.status2.getStatus());
        editData(gasStaff);

        SecUser secUser = userService.getDetail(SecUserObjectTypeEnum.type3, gasStaff.getId());
        if (secUser != null) {
            secUser.setStatus(SecUserStatusEnum.status2.getCode());
            userService.editUser(secUser);
        }
    }

    @Override
    public void recover(Long id) {
        // 查询油站员工
        BsGasStaff gasStaff = getStaffDetailById(id);
        if (gasStaff ==  null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到员工");
        }
        gasStaff.setStatus(GasStaffStatus.status1.getStatus());
        editData(gasStaff);

        SecUser secUser = userService.getDetail(SecUserObjectTypeEnum.type3, gasStaff.getId());
        if (secUser != null) {
            secUser.setStatus(SecUserStatusEnum.status1.getCode());
            userService.editUser(secUser);
        }
    }

    @Override
    public BsGasStaff getStaffDetailById(Long id) {
        return gasStaffMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<BsGasStaff> getStaffList(Map<String, Object> param) {
        BsGasStaffExample example = new BsGasStaffExample();
        BsGasStaffExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(0);

        if (MapUtils.getLong(param, "merId") != null) {
            criteria.andMerIdEqualTo(MapUtils.getLong(param, "merId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "name"))) {
            criteria.andNameLike("%" + MapUtils.getString(param, "name") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "telephone"))) {
            criteria.andTelephoneLike("%" + MapUtils.getString(param, "telephone") + "%");
        }

        if (MapUtils.getInteger(param, "positionType") != null) {
            criteria.andPositionTypeEqualTo(MapUtils.getInteger(param, "positionType"));
        }

        if (MapUtils.getInteger(param, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(param, "status"));
        }

        example.setOrderByClause("create_time desc");
        return gasStaffMapper.selectByExample(example);
    }
}
