package com.yunzhi.marketing.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.entity.TaMiniFormids;
import com.yunzhi.marketing.mapper.TaMiniFormidsMapper;
import com.yunzhi.marketing.service.ITaMiniFormidsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class TaMiniFormidsImpl extends ServiceImpl<TaMiniFormidsMapper, TaMiniFormids> implements ITaMiniFormidsService {

    @Autowired
    TaMiniFormidsMapper taMiniFormidsMapper;

    @Override
    public ResponseBean saveFormidBy(String openid, String paramsStr) {
        JSONObject params = JSONObject.parseObject(paramsStr);
        JSONArray formids = params.getJSONArray("formids");

        for (Object formid: formids) {
            TaMiniFormids taMiniFormids = new TaMiniFormids();
            taMiniFormids.setOpenid(openid);
            taMiniFormids.setFormid(formid.toString());
            taMiniFormids.setCreateDate(LocalDateTime.now());
            taMiniFormidsMapper.insert(taMiniFormids);
        }

        return ResponseBean.success("");
    }

    @Override
    public String getFormidBy(String openid, boolean... delete) {
        TaMiniFormids taMiniFormids = taMiniFormidsMapper.getFormidCanUse(openid);
        if (null == taMiniFormids) return null;

        if (null != delete && delete.length > 0 && delete[0]) {
            QueryWrapper<TaMiniFormids> wrapper = new QueryWrapper<>();
            wrapper.eq("openid", openid);
            wrapper.eq("formid", taMiniFormids.getFormid());

            taMiniFormidsMapper.delete(wrapper);
        }

        return taMiniFormids.getFormid();
    }
}
