package com.ag.rate.tariff.service;

import com.ag.base.BaseRepositoryImpl;
import com.ag.entity.fee.ItemProperties;
import com.ag.entity.fee.Tariff;
import com.ag.entity.fee.TariffRitem;
import com.ag.entity.fee.face.ReqSource;
import com.ag.entity.fee.face.SourceProperty;
import com.alibaba.fastjson.JSON;
import com.wb.util.WebUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * Created by yangxh on 2020/8/5.
 */
@Service
public class ItemPropService {
    @Autowired
    private BaseRepositoryImpl feeDao;

    public void delProperties(HttpServletRequest request){
        String id = request.getParameter("ID");
        ItemProperties prop = new ItemProperties();
        prop.setId(id);
        prop = (ItemProperties)feeDao.findById(prop, ItemProperties.class, "ID");
        String sql = "SELECT * FROM C_TARIFF_RITEM WHERE KEY_NAME =?\n" +
                "AND RULE_ID IN (SELECT ID FROM C_TARIFF WHERE CHARGING_ID=?)";
        List<TariffRitem> ritems = feeDao.list(sql, TariffRitem.class, prop.getPropertyCode(), prop.getItemId());
        Assert.isTrue(CollectionUtils.isEmpty(ritems), "该元素已被使用，不可移除！");
        feeDao.delete(prop, "ID");
    }

    public void showJSONByTariff(JSONObject param, HttpServletResponse response, HttpServletRequest request) throws IOException {
        ReqSource reqSource = new ReqSource();
        SourceProperty sourceProperty = new SourceProperty();
        reqSource.getSourceProperties().add(sourceProperty);
        String ruleId = param.getString("ruleId");
        TariffRitem entity = new TariffRitem();
        entity.setRuleId(ruleId);
        List<TariffRitem> ritems = feeDao.findByEqCriteria(entity, TariffRitem.class, "RULE_ID");
        for (TariffRitem ritem : ritems){
            if (Objects.equals("RATE", ritem.getKeyName())){
                continue;
            }
            if (Objects.equals("=", ritem.getOperChar())) {
                sourceProperty.getProperty().put(ritem.getKeyName(), ritem.getCompareVal());
            }else {
                sourceProperty.getProperty().put(ritem.getKeyName(), ritem.getOperChar()+" "+ritem.getCompareVal());
            }
        }
        Tariff tf = new Tariff();
        tf.setId(ruleId);
        Tariff tariff = (Tariff)feeDao.findById(tf, Tariff.class, "ID");
        reqSource.setContractId(tariff.getContractId());
        reqSource.setItemId(tariff.getChargingId());
        reqSource.setTenancyId(tariff.getTenancyId());
        reqSource.setOperMan(tariff.getCreatedBy());
        WebUtil.send(response, JSON.toJSONString(reqSource));
    }
}
