package com.ag.rate.tariff.service;

import com.ag.base.BaseService;
import com.ag.base.DefaultBussniessImpl;
import com.ag.entity.fee.ContractRelation;
import com.ag.util.UUIDUtil;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangxh on 2019/9/10.
 * 客户合同关系
 */
@Service
public class RelationService extends BaseService {

    @Autowired
    private DefaultBussniessImpl<ContractRelation> relDao;

    @Transactional
    public void save(HttpServletRequest request){
        String tenancyId = super.getTenancyId(request);
        String customerId = request.getParameter("customerId");
        String ids = request.getParameter("ids");
        ContractRelation source = new ContractRelation();
        source.setTenancyId(tenancyId);
        source.setCustomerId(customerId);

        List<ContractRelation> sources = relDao.findByEntity(source, ContractRelation.class);
        JSONArray ja = JSONArray.parseArray(ids);
        List<ContractRelation> lst = new ArrayList<>();
        for(Object obj : ja.toArray()){
            boolean status = false;
            for (ContractRelation exists : sources){
                if (exists.getContractId().equals(obj.toString())){
                    status = true;
                    break;
                }
            }
            if (status){
                continue;
            }
            ContractRelation relation = new ContractRelation();
            relation.setId(UUIDUtil.getUUID());
            relation.setTenancyId(tenancyId);
            relation.setContractId(obj.toString());
            relation.setCustomerId(customerId);
            relation.setCreatedBy(super.getSysUserName(request));
            relation.setCreatedOn(super.getNow());
            lst.add(relation);
        }
        relDao.saveAll(lst);
    }

    @Transactional
    public void del(HttpServletRequest request){
        String customerId = request.getParameter("customerId");
        String ids = request.getParameter("ids");//???
        JSONArray array = JSONArray.parseArray(ids);
        List<ContractRelation> lst = new ArrayList<>();
        for(Object obj : array.toArray()){
            ContractRelation relation = new ContractRelation();
            relation.setContractId(obj.toString());
            relation.setCustomerId(customerId);
            relation.setTenancyId(super.getTenancyId(request));
            lst.add(relation);
        }
        relDao.deleteAll(lst, "CONTRACT_ID","CUSTOMER_ID", "TENANCY_ID");
    }

}
