package thyyxxk.webserver.service.outpatient.coupon;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.dao.his.outpatient.CouponManageDao;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.outpatient.coupon.CouponInquiry;
import thyyxxk.webserver.entity.outpatient.coupon.CouponState;
import thyyxxk.webserver.entity.outpatient.coupon.ZdCoupon;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.StringUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CouponManageService {
    private final CouponManageDao dao;
    private final UserCache userCache;

    @Autowired
    public CouponManageService(CouponManageDao dao, UserCache userCache) {
        this.dao = dao;
        this.userCache = userCache;
    }

    public List<ZdCoupon> getAllCoupons(CouponInquiry inquiry) {
        QueryWrapper<ZdCoupon> wrapper = new QueryWrapper<>();
        wrapper.ge("create_time", inquiry.getStart());
        wrapper.le("create_time", inquiry.getEnd());
        if (inquiry.getState() != CouponState.ALL) {
            wrapper.eq("state", inquiry.getState());
        }
        List<ZdCoupon> list = dao.selectList(wrapper);
        for (ZdCoupon item : list) {
            item.setStaffName(userCache.getEmployeeName(item.getCreateStaff()));
        }
        return list;
    }

    public String updateCouponState(ZdCoupon coupon) {
        dao.updateById(coupon);
        return "更新成功";
    }

    public UserInfo getSalesmanByCodeRs(String codeRs) {
        return dao.selectSalesman(codeRs);
    }

    public String insertNewCoupon(ZdCoupon coupon) {
        coupon.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        coupon.setLeftQuantity(coupon.getTotalQuantity());
        coupon.setCreateStaff(TokenUtil.getInstance().getTokenUserId());
        coupon.setCreateTime(new Date());
        if (StringUtil.notBlank(coupon.getAvailableCharge())) {
            coupon.setAvailableCharge(coupon.getAvailableCharge().split("_")[0]);
        } else {
            coupon.setDescription("无门槛");
        }
        int result = dao.insert(coupon);
        if (result == 1) {
            return "SUCCESS";
        }
        return "数据库错误，新增失败。";
    }
}
