package com.ag.rate.tariff.service;

import com.ag.base.BaseService;
import com.ag.base.IBaseRepository;
import com.ag.base.IRedisService;
import com.ag.base.ParamUtil;
import com.ag.entity.fee.*;
import com.ag.rate.tariff.dao.TariffDao;
import com.ag.secp.platform.spring.SpringApplicationContext;
import com.ag.util.StrUtil;
import com.ag.util.UUIDUtil;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2017/4/11 0011.
 */
@Service
public class TariffService extends BaseService {
    @Autowired
    private TariffDao tariffDao;
    @Autowired
    private TariffExtService extService;
    @Resource(name="baseRepositoryImpl")
    private IBaseRepository feeDao;

    /**
     * 查询费类
     */
    public String findAllCate(HttpServletRequest request){
        BaseCategory category = new BaseCategory();
        category.setTenancyId(super.getTenancyId(request));
        return tariffDao.findAll(category);
    }
    /**
     * 保存费类
     */
    @Transactional
    public int saveCate(HttpServletRequest request, ScriptObjectMirror so){
        /*for(Map.Entry<String, Object> en: so.entrySet()){
            System.out.println(en.getKey()+" : "+en.getValue());
        }*/
        BaseCategory category = new ParamUtil<BaseCategory>().packPOJO(super.getRequestMap(request), BaseCategory.class);
        category.setId(UUIDUtil.getUUID());
        super.setSaveUser(request, category);
        int num = tariffDao.save(category);
        if(num > 0 ){
            IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
            service.refreshByDictName("C_BASE_CATEGORY");
        }
        return num;
    }
    /**
     * 修改费类
     */
    @Transactional
    public int updateCate(HttpServletRequest request){
        BaseCategory category = new ParamUtil<BaseCategory>().packPOJO(super.getRequestMap(request), BaseCategory.class);
        super.setUpdateUser(request, category);
        int num = tariffDao.update(category, super.getRequestParam(request));
        if(num > 0 ){
            IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
            service.refreshByDictName("C_BASE_CATEGORY");
        }
        return num;
    }
    /**
     * 删除费类
     */
    @Transactional
    public int deleteCate(HttpServletRequest request, String id){
        int ct = tariffDao.isUseItemByCate(id);
        if(ct > 0){
            callExcetion("该费类在收费项目中已使用！");
        }
        BaseCategory category = new BaseCategory();
        category.setId(id);
        int num = tariffDao.delete(category);
        if(num > 0 ){
            IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
            service.refreshByDictName("C_BASE_CATEGORY");
        }
        return num;
    }



    /**
     * 查询费目
     */
    public String findAllItem(HttpServletRequest request){
        BaseChargingItem item = new BaseChargingItem();
        item.setCategoryId(request.getParameter("categoryId"));
        item.setTenancyId(super.getTenancyId(request));
        return tariffDao.findAll(item);
    }

    public String convertDictByFeeItem(HttpServletRequest request){
        BaseChargingItem item = new BaseChargingItem();
        item.setTenancyId(super.getTenancyId(request));
        String sql = tariffDao.findAll(item);
        return sql;
    }

    public List<BaseChargingItem> findBaseItemLst(HttpServletRequest request){
        BaseChargingItem item = new BaseChargingItem();
        item.setTenancyId(super.getTenancyId(request));
        return tariffDao.findBaseItemLst(item);
    }

    /**
     * 新增费目
     */
    @Transactional
    public int saveItem(HttpServletRequest request){
        BaseChargingItem item = new ParamUtil<BaseChargingItem>().packPOJO(super.getRequestMap(request), BaseChargingItem.class);
        /*Assert.isTrue(StrUtil.isNotEmpty(item.getItemCode()), "费目代码不能为空！");
        int count = feeDao.findByCount(item, "ITEM_CODE");
        Assert.isTrue(count == 0, "费目代码["+item.getItemCode()+"]已存在，请更改");*/
        item.setId(UUIDUtil.getUUID());
        super.setSaveUser(request, item);
        item.setDelFlag(0);
        int num = tariffDao.save(item);
        if(num > 0 ){
            IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
            service.refreshByDictName("C_BASE_CHARGING_ITEM");
        }
        return num;
    }
    /**
     * 修改费目
     */
    @Transactional
    public int updateItem(HttpServletRequest request){
        BaseChargingItem item = new ParamUtil<BaseChargingItem>().packPOJO(super.getRequestMap(request), BaseChargingItem.class);
        Assert.isTrue(StrUtil.isNotEmpty(item.getCategoryId()), "费类不能为空！");
        /*Assert.isTrue(StrUtil.isNotEmpty(item.getItemCode()), "费目代码不能为空！");
        String checkCodeSql = feeDao.findByEqSql(item,"ITEM_CODE")+" and id<>'"+item.getId()+"'";
        int count = feeDao.count("select count(0) from ("+checkCodeSql+")");
        Assert.isTrue(count == 0, "费目代码["+item.getItemCode()+"]已存在，请更改");*/

        //同步修改所有合同费目
        ContractItem citem = new ContractItem();
        citem.setItemId(item.getId());
        citem.setCategoryId(item.getCategoryId());
        citem.setTenancyId(item.getTenancyId());
        tariffDao.updateCategory(citem);
        super.setUpdateUser(request, item);
        int num = tariffDao.update(item, super.getRequestParam(request));

        if(num > 0 ){
            IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
            service.refreshByDictName("C_BASE_CHARGING_ITEM");
        }
        return num;
    }
    /**
     * 删除费目
     */
    @Transactional
    public int deleteItem(HttpServletRequest request, String id){
        ContractItem citem = new ContractItem();
        citem.setItemId(id);
        int count = feeDao.findByCount(citem, "ITEM_ID");
        Assert.isTrue(count == 0, "费目已被使用，不能删除");

        BaseChargingItem item = new BaseChargingItem();
        item.setId(id);
        int num = tariffDao.delete(item);
        if(num > 0 ){
            IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
            service.refreshByDictName("C_BASE_CHARGING_ITEM");
        }
        return num;
    }

    /**
     * 查询费率条件

    public String findAllRule(HttpServletRequest request){
        TariffRule rule = new ParamUtil<TariffRule>().packPOJO(super.getRequestMap(request), TariffRule.class);
        //rule.setTenancyId(super.getTenancyId(request));
        return tariffDao.findAll(rule);
    }*/

    /*
    public String findRuleByItem(HttpServletRequest request, String itemId){
        TariffRule rule = new TariffRule();
        //rule.setTenancyId(super.getTenancyId(request));
        rule.setIsShow(1);//0=不显示1=显示
        rule.setItemId(itemId);
        return tariffDao.findAll(rule);
    }*/

    /*@Deprecated
    public int saveRule(HttpServletRequest request,ScriptObjectMirror so){
        Map<String, String> map = super.getRequestMap(request);
        printMap(map);
//        for(Map.Entry<String, Object> en: so.entrySet()){
//            System.out.println(en.getKey()+" : "+en.getValue());
//        }
        TariffRule rule = new ParamUtil<TariffRule>().packPOJO(super.getRequestMap(request), TariffRule.class);
        rule.setId(UUIDUtil.getUUID());
        super.setSaveUser(request, rule);
        //int num = tariffDao.save(rule);
        return 0;
    }
    @Deprecated
    public int updateRule(HttpServletRequest request){
        TariffRule rule = new ParamUtil<TariffRule>().packPOJO(super.getRequestMap(request), TariffRule.class);
        rule.setItemId(null);
        super.setUpdateUser(request, rule);
        return tariffDao.update(rule);
    }*/
    /**
     * 删除费率条件

    @Transactional
    public int deleteRule(HttpServletRequest request, String id){
        TariffRule rule = new TariffRule();
        rule.setId(id);
        Integer used = tariffDao.queryUsedTariff(id, super.getTenancyId(request));
        Assert.isTrue(used == 0, "费率条件被使用，不能删除！");
        int num = tariffDao.delete(rule);
        if(num > 0){
            tariffDao.deleteItemByRuleId(id);
        }
        return num;
    }*/

    /**
     * 查询费率条件子表
     */
    public String findItemByRule(String ruleId){
        TariffRitem item = new TariffRitem();
        item.setRuleId(ruleId);
        return tariffDao.findAll(item);
    }



    /**
     * 合同、费类、费目树
     */
    public String getTreeSql(HttpServletRequest request){
        String sql = null;
        String level = request.getParameter("level");
        String parentId = request.getParameter("parentId");
        String contractId = request.getParameter("contractId");
        String description = request.getParameter("hidContractDESC");
        //所有合同
        if("1".equals(level)){
            sql = StringUtils.join("select ID,DESCRIPTION||'(合同)' \"text\", -1 parent_id, 2 LEVELS, ID CONTRACT_ID from C_CONTRACT " ,
                    " where CALC_FLAG=1");
            if(!StrUtil.isEmpty(super.getTenancyId(request))){
                sql = StrUtil.join(sql, " and TENANCY_ID='", super.getTenancyId(request),"'");
            }
            if (!StrUtil.isEmpty(description)){
                sql = StrUtil.join(sql, " and DESCRIPTION like '%", description, "%'");
            }
        }
        //合同下费类
        if("2".equals(level)){
            sql = StringUtils.join("select a.ID, a.DESCRIPTION||'(费类)' \"text\", b.CONTRACT_ID parent_id, 3 LEVELS, b.CONTRACT_ID CONTRACT_ID " ,
                    " from C_BASE_CATEGORY a, C_CONTRACT_CATEGORY b",
                    " where a.ID=b.CATEGORY_ID",
                    " and b.CONTRACT_ID='", parentId,"'");
        }
        //合同费类下费目
        if("3".equals(level)){
            sql = StringUtils.join("select a.ID, a.DESCRIPTION||'(费目)' \"text\", 'axis_icon' as \"iconCls\",'true' as \"leaf\", b.CATEGORY_ID parent_id, 4 LEVELS, b.CONTRACT_ID CONTRACT_ID ",
                    " from C_BASE_CHARGING_ITEM a, C_CONTRACT_ITEM b" ,
                    " where a.id = b.ITEM_ID and b.CATEGORY_ID='",parentId,
                    "' and b.CONTRACT_ID='", contractId, "'");
        }
        if(sql == null){
            sql = "select ID,DESCRIPTION \"text\", 0 parent_id, 0 LEVELS from C_BASE_CATEGORY where 1=2";
        }
        return sql;
    }


    public String getTreeSqlForCheck(HttpServletRequest request){
        String sql = "";
        String level = request.getParameter("level");
        String contractId = request.getParameter("contractId");
        String description = request.getParameter("hidContractDESC");
        String confirmStatus = request.getParameter("confirmStatus");
        //所有合同
        if("1".equals(level)){
            sql = StringUtils.join("select ID, DESCRIPTION||'(合同)' \"text\", 2 LEVELS, ID CONTRACT_ID from C_CONTRACT cc " ,
                    " where cc.del_flag=0");
            if(!StrUtil.isEmpty(confirmStatus)){
                sql = StrUtil.join(sql, " and EXISTS (SELECT 1 FROM C_TARIFF ct WHERE ct.CONFIRM_STATUS=",
                        confirmStatus, " AND ct.CONTRACT_ID =cc.ID and ct.del_flag=0)");
            }
            if (!StrUtil.isEmpty(description)){
                sql = StrUtil.join(sql, " and DESCRIPTION like '%", description, "%'");
            }
        }

        //合同费类下费目
        if("2".equals(level)){
            sql = StringUtils.join("select a.ID, a.DESCRIPTION \"text\", 'axis_icon' as \"iconCls\",'true' as \"leaf\", " ,
                    " 3 LEVELS, b.CONTRACT_ID CONTRACT_ID ",
                    " from C_BASE_CHARGING_ITEM a, C_CONTRACT_ITEM b" ,
                    " where b.del_flag=0 and a.id = b.ITEM_ID and b.CONTRACT_ID='", contractId, "'");
            if(!StrUtil.isEmpty(confirmStatus)){
                sql = StrUtil.join(sql, " and EXISTS (SELECT 1 FROM C_TARIFF ct WHERE ct.CONFIRM_STATUS=",
                        confirmStatus, " and ct.CONTRACT_ID = b.CONTRACT_ID  and ct.CHARGING_ID = a.ID and ct.del_flag=0)");
            }
        }
        if(StrUtil.isEmpty(sql)){
            sql = "select ID,DESCRIPTION \"text\", 0 parent_id, 0 LEVELS from C_BASE_CATEGORY where 1=2";
        }
        return sql;
    }


    /**
     * 新建费率
     */
    @Transactional
    public int saveTariff(HttpServletRequest request,ScriptObjectMirror so){
        Tariff tariff = new ParamUtil<Tariff>().packPOJO(super.getRequestMap(request), Tariff.class);
        tariff.setId(UUIDUtil.getUUID());
        tariff.setChargingId(request.getParameter("hidTreeID"));
        tariff.setTenancyId(super.getTenancyId(request));
        Integer num = tariffDao.findTariffNum(tariff);
        if(num > 0){
            super.callExcetion("保存失败，费率已存在！");
        }
        super.setSaveUser(request, tariff);
        //String destroy = request.getParameter("destroy");
        //String update = request.getParameter("update");
        String create = request.getParameter("create");
        List<TariffMultistep> createLst = JSONObject.parseArray(create, TariffMultistep.class);
        //List<TariffMultistep> updateLst = JSONObject.parseArray(update,TariffMultistep.class);
        //List<TariffMultistep> destroyLst = JSONObject.parseArray(destroy,TariffMultistep.class);
        for(TariffMultistep step : createLst){
            step.setId(UUIDUtil.getUUID());
            step.setTenancyId(super.getTenancyId(request));
            step.setTariffId(tariff.getId());
        }
        tariffDao.saveStep(createLst);
        //tariffDao.updateStep(updateLst);
        //tariffDao.deleteStep(destroyLst);
        return tariffDao.save(tariff);
    }

    /**
     * 修改费率属性及运算符
     */
    @Transactional
    public void updateTariff(HttpServletRequest request){
        Tariff tariff = new ParamUtil<Tariff>().packPOJO(super.getRequestMap(request), Tariff.class);
        if (StrUtil.isEmpty(tariff.getId())){
            throw new RuntimeException("未选择费率!");
        }
        String contractId = request.getParameter("CONTRACT_ID");
        String itemId = request.getParameter("ITEM_ID");
        String update = request.getParameter("update");
        List<TariffRitem> updateLst = JSONObject.parseArray(update, TariffRitem.class);
        //运算符更新
        tariffDao.updateRitem(updateLst);
        //查询所有费率条件
        TariffRitem queryRitem = new TariffRitem();
        queryRitem.setRuleId(tariff.getId());
        List<TariffRitem> ritems = feeDao.findByEntity(queryRitem, TariffRitem.class);
        //查询费率要素
        ItemProperties query = new ItemProperties();
        query.setItemId(itemId);
        List<ItemProperties> properties = feeDao.findByEntity(query, ItemProperties.class);
        properties.sort((a, b)->a.getDispOrder() - b.getDispOrder());
        //生成费率key备注，val备注
        extService.generateDescription(tariff, ritems, properties);
        //更新费率主表
        tariffDao.update(tariff, super.getRequestParam(request));
        //检查重复费率
        extService.synDescription(contractId, itemId, super.getTenancyId(request));
    }


    /**
     * 阶梯费率维护
     */
    @Transactional
    public void saveMultistepRate(HttpServletRequest request){
        String create = request.getParameter("create");
        String destroy = request.getParameter("destroy");
        String update = request.getParameter("update");
        String tariffId = request.getParameter("tariffId");
        List<TariffMultistep> createLst = JSONObject.parseArray(create, TariffMultistep.class);
        List<TariffMultistep> updateLst = JSONObject.parseArray(update,TariffMultistep.class);
        List<TariffMultistep> destroyLst = JSONObject.parseArray(destroy,TariffMultistep.class);
        for(TariffMultistep step : createLst){
            step.setId(UUIDUtil.getUUID());
            step.setTenancyId(super.getTenancyId(request));
            step.setTariffId(tariffId);
            step.setDelFlag(0);
        }
        for(TariffMultistep step : destroyLst){
            step.setDelFlag(1);
        }
        tariffDao.saveStep(createLst);
        tariffDao.updateStep(updateLst, super.getJSONParam(update));
        tariffDao.updateStep(destroyLst, null);//更新删除标识
        //tariffDao.deleteStep(destroyLst);
    }
    /**
     * 删除费率
     */
    @Transactional
    public int deleteTariff(HttpServletRequest request, String id){
        Tariff tariff = new Tariff();
        tariff.setId(id);
        return tariffDao.delete(tariff);
    }

    public String findMultistep(HttpServletRequest request){
        //String tariffId
        TariffMultistep step = new ParamUtil<TariffMultistep>().packPOJO(super.getRequestMap(request), TariffMultistep.class);
        step.setTenancyId(super.getTenancyId(request));
        step.setDelFlag(0);
        String sql = tariffDao.findMultistep(step);
        if (StrUtil.isEmpty(step.getTariffId())){
            if (sql.toLowerCase().contains(" where ")){
                sql += " and 1=2";
            } else {
                sql += " where 1=2";
            }
        }
        return sql;

    }

}
