package com.sifang.modules.sunshine.SystemSetting.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.OrderCustomerSettlementTemplateDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmOrderCustomerSettlementTemplate;
import com.sifang.modules.sunshine.SystemSetting.form.StaticParamsCode;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.persistence.Page;
import com.sifang.modules.sys.common.service.BaseService;


@Service
public class CrmOrderCustomerSettlementTemplateService extends BaseService {

    private Logger logger = Logger.getLogger(CrmOrderCustomerSettlementTemplateService.class);

    @Autowired
    private OrderCustomerSettlementTemplateDao crmOrderCustomerSettlementTemplateDao;


    public CrmOrderCustomerSettlementTemplate getById(String id){
        return crmOrderCustomerSettlementTemplateDao.get(id);
    }


    // 获取信息列表分页信息
    public Page<Record> loadSettlementSetPage(Page<Record> page, Map<String, String> map) {
        List<Record> list = getSettlementSetList(page, map);
        page.setList(list);
        Long count = getCounts(map);
        page.setCount(count);
        return page;
    }

    // 获取结算设置-列表分页信息
    public List<Record> getSettlementSetList(Page<Record> page, Map<String, String> map) {
        StringBuilder sb = new StringBuilder("");
        sb.append("  SELECT any_value(a.id) AS id ,any_value(a.number) AS number,any_value(a.warranty_type) AS warranty_type,any_value(a.service_type) AS service_type ");
        sb.append(" ,any_value(a.charge_amount) AS charge_amount,any_value(a.service_step) AS service_step,any_value(a.service_content) AS service_content ");
        sb.append(" from crm_order_customer_settlement_template a where any_value(a.status) ='0'  ");
        sb.append(sqlConditions(map));
        sb.append(" group by a.number ");
        sb.append(" order by any_value(a.create_time) desc  ");
        if (page != null) {
            sb.append(" limit " + page.getPageSize() + " offset " + (page.getPageNo() - 1) * page.getPageSize());
        }
   //     logger.info("获取结算设置-列表分页信息  - " + sb.toString());
        List<Record> list = Db.find(sb.toString());
        return list;
    }

    // 列表查询条件
    public String sqlConditions(Map<String, String> map) {
        StringBuilder sb = new StringBuilder("");
        if (map != null) {
            if (StringUtil.checkParamsValid(map.get("serviceMeasures"))) {
                sb.append(" and a.service_measures like '%" + map.get("serviceMeasures") + "%'");
            }

        }
        return sb.toString();
    }

    // 根据品类、编码获取结算项的count(数量)
    public Long getCounts(Map<String, String> map) {
        StringBuilder sb = new StringBuilder("");
        sb.append("SELECT COUNT(*) FROM (select a.number from crm_order_customer_settlement_template a where any_value(a.status) ='0' ");
        sb.append(sqlConditions(map));
        sb.append(" group by a.number ");
        sb.append(" ) AS tt   ");
        return Db.queryLong(sb.toString());
    }

    // 删除结算设置项-保存操作
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> saveDelSiteSettlementSet(Map<String, String> map) {
        String numbers = map.get("ids") != null ? map.get("ids").toString() : "";
        if (StringUtils.isBlank(numbers)) {// 品类和结算编码不能为空
            return Result.fail("参数信息有误，请检查！");
        }
        SQLQuery sql = crmOrderCustomerSettlementTemplateDao.getSession()
                    .createSQLQuery("update crm_order_customer_settlement_template a set a.status='1',update_time=now() where status='0' and a.id in ("
                            + StringUtil.joinInSql(numbers.split(",")) + ")");
        sql.executeUpdate();// 更新结算设置表信息

        return Result.ok();

    }


    // 新增结算设置-保存操作
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> addSaveSiteSettlementSet(Map<String, String> map) {
        Result result = new Result();
        try {
            String warrantyType = map.get("warrantyType") != null ? map.get("warrantyType").toString() : "";
            String serviceType = map.get("serviceType") != null ? map.get("serviceType").toString() : "";
            String serviceStep = map.get("serviceStep") != null ? map.get("serviceStep").toString() : "";
            String serviceContent = map.get("serviceContent") != null ? map.get("serviceContent").toString() : "";
            // 金额信息，json格式字符串
            String chargeAmount = map.get("chargeAmount") != null ? map.get("chargeAmount").toString() : "0";
            //只能新增
            long count = crmOrderCustomerSettlementTemplateDao.getTemplateByNumber(warrantyType,serviceStep);
            if(count > 0){
                return Result.fail("401","该保修类型下的服务措施已添加");
            }

            Date dt = new Date();
            String createBy = UserUtils.getUser().getId();

                    CrmOrderCustomerSettlementTemplate csst = new CrmOrderCustomerSettlementTemplate();
                    csst.setCreateBy(createBy);
                    csst.setCreateTime(dt);
                    csst.setNumber(PlantformUtils.getSiteNumber());
                    csst.setServiceType(serviceType);
                    csst.setStatus(StaticParamsCode.STATUS_0);
                    csst.setWarrantyType(warrantyType);
                    csst.setServiceStep(serviceStep);
                    csst.setServiceContent(serviceContent);
                    csst.setChargeAmount(new BigDecimal(chargeAmount));
            crmOrderCustomerSettlementTemplateDao.save(csst);

            result = Result.ok();
        } catch (Exception e) {
            result.setCode("205");
            result.setMsg("保存失败，请刷新再试");
            throw e;
        }
        return result;
    }

    // 修改结算设置-保存操作
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> editSaveSiteSettlementSet(Map<String, String> map) {
        Result result = new Result();
        try {
            String id = map.get("id");
            String warrantyType = map.get("warrantyType") != null ? map.get("warrantyType").toString() : "";
            String serviceStep = map.get("serviceStep") != null ? map.get("serviceStep").toString() : "";
            String serviceContent = map.get("serviceContent") != null ? map.get("serviceContent").toString() : "";
            // 金额信息，json格式字符串
            String chargeAmount = map.get("chargeAmount") != null ? map.get("chargeAmount").toString() : "0";
            // 根据品类、结算编码查询对应结算设置信息
            long listOld =  crmOrderCustomerSettlementTemplateDao.getTemplateByNumberNotById(warrantyType,serviceStep,id);
            if (listOld > 1) {// 如果查询的列表长度小于1，即修改的数据没找到，可能已被删除
                return Result.fail("该服务措施方案已存在，请刷新后重试！");
            }

            Date dt = new Date();

                    CrmOrderCustomerSettlementTemplate csst = crmOrderCustomerSettlementTemplateDao.get(id);
                    csst.setUpdateTime(dt);
                    csst.setWarrantyType(warrantyType);
                    csst.setServiceContent(serviceContent);
                    csst.setServiceStep(serviceStep);
                    csst.setChargeAmount(new BigDecimal(chargeAmount));
                // 在保存添加的数据
                crmOrderCustomerSettlementTemplateDao.save(csst);
            result = Result.ok();
        } catch (Exception e) {
            result.setCode("205");
            result.setMsg("保存失败，请刷新再试");
            throw e;
        }
        return result;
    }

    /**
     * 根据服务措施查询对应的费用
    */
    public Record getSetTemplateByServiceStep(String service_step,String warranty_type,String service_type){

        return Db.findFirst("SELECT id,service_content,service_step,warranty_type,service_type,IfNULL(charge_amount,0) AS charge_amount FROM crm_order_customer_settlement_template WHERE service_step=? AND status='0' AND warranty_type=? AND service_type=? ",service_step,warranty_type,service_type);
    }


}
