package com.engine.htxc.contract.service.impl;

import com.engine.core.impl.Service;
import com.engine.htxc.commonutil.db.DbTools;
import com.engine.htxc.contract.service.ContractListService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ContractListServiceImpl extends Service implements ContractListService {

    private DbTools dbtools=new DbTools();
    private PropBean pb=new PropBean();
    @Override
    public Map<String, Object> deleteData(Map<String, Object> paramMap) {
        String ids = paramMap.get("ids") == null? "":paramMap.get("ids").toString();
        Map<String ,Object> apiData = Maps.newHashMap();
        List<String> errorHtbhs = Lists.newArrayList();
        apiData.put("code","200");
        try {
            String sql = "select count(0) num from UF_CONTRACTLIST where zt!=0 and htbh in ("+ids+")";
            int num = dbtools.ifExist(sql);
            if (num > 0){ //删除的数据中有不是草稿的数据
                apiData.put("code","400");
                apiData.put("message","只能删除草稿状态的数据");
                return apiData;
            }
            //获得表单id及对应的billid
            String billIdSql = "select formidd,bid,htbh from UF_CONTRACTLIST where htbh in ("+ids+")";
            List<Map<String, Object>> list = dbtools.getSqlToList(billIdSql);
            Map<String, List<Map<String, Object>>> collect = list.stream().collect(Collectors.groupingBy(e -> e.get("formidd").toString()));
                collect.entrySet().forEach(e -> {
                String formid = e.getKey();
                String tableName = dbtools.getFormidToTable(formid);
                String billids = "";
                String htbh = "";
                for (Map<String, Object> map : e.getValue()){
                    billids = billids + map.get("bid") +",";
                    htbh = htbh + map.get("htbh")+",";
                }
                htbh = htbh.substring(0,htbh.length()-1);
                billids = billids.substring(0,billids.length()-1);
                String deleteSql = "delete from "+tableName+" where id in ("+billids+")";
                boolean result = dbtools.execteSql(deleteSql);
                if (!result){
                    errorHtbhs.add(htbh);
                }
            });

        }catch (Exception e){
            apiData.put("code","400");
            apiData.put("message",e.getMessage());
        }
        if (errorHtbhs.size() >0){
            apiData.put("code","400");
            apiData.put("message","删除失败");
            apiData.put("errorData",errorHtbhs);
        }
        return apiData;
    }
}
