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

import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.PlanMaterialDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectContractDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectContract;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.handler.ContractExcelImportHandler;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
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 java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lzp
 */
@Service
public class ProjectContractService extends BaseService {

    @Autowired
    ProjectContractDao projectDao;

    @Autowired
    CustomerEntryDao entryDao;

    public List<Record> findAllPlan() {
        return projectDao.findAllPlan();
    }

    public Record getPlanById(String id) {
        return projectDao.getPlanById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addOrEditPlan(CrmProjectContract req) {
        if (StrKit.isBlank(req.getId())) {
            addPlan(req);
        } else {
            editPlan(req);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void addPlan(CrmProjectContract plan) {
        plan.setStatus(SourceConstants.ONE);
        plan.setCreateName(CrmUtils.getUserXM(UserUtils.getUser()));
        plan.setCreateTime(new Date());
        projectDao.save(plan);

    }

    @Transactional(rollbackFor = Exception.class)
    public void editPlan(CrmProjectContract req) {
        if (checkPlanCodeExists(req.getNumber(), req.getId())) {
            throw new BusinessException("方案编号已存在");
        }
        CrmProjectContract plan = projectDao.get(req.getId());


        projectDao.save(plan);

    }

    @Transactional(rollbackFor = Exception.class)
    public void deletePlan(String planIds) {
        for (String planId : planIds.split(",")) {
            CrmProjectContract plan = projectDao.get(planId);
            plan.setStatus(SourceConstants.THREE);
            projectDao.save(plan);
            if (StringUtil.isNotBlank(plan.getCustomerEntryId())) {
                CustomerEntry customerEntry = entryDao.get(plan.getCustomerEntryId());
                customerEntry.setUniformity("1");
                entryDao.save(customerEntry);
            }
        }
    }

    public List<String> findExistsCode(String status) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT CONCAT(customer_name,id_code,assembly_specs,assembly_num) AS contract")
                .line("from crm_customer_project_contract ")
                .line("where 1=1");
        if (StringUtil.isNotBlank(status)) {
            builder.line("and status ='1'");
        } else {
            builder.line(" and status !='3'");
        }

        return Db.query(builder.build());
    }


    /**
     * 所有未匹配的合同
     */
    public List<CrmProjectContract> findCrmProjectContractList() {
        String sql = "from CrmProjectContract a WHERE status='1'";
        return projectDao.find(sql);
    }

    public void addContractList(List<CrmProjectContract> list) {
        projectDao.save(list);
    }


    public void listPlan(LayuiPage<Record> page, Map<String, String> map) {
        page.setData(selectListPlan(page, map));
        page.setCount(countListPlan(map));
    }

    public List<Record> selectListPlan(LayuiPage<Record> page, Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select p.* ")
                .line("from crm_customer_project_contract p")
                .line("where p.status !='3'");
        appendCondition(builder, map);
        builder.line("order by p.create_time desc")
                .limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public Long countListPlan(Map<String, String> map) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(*) ")
                .line("from crm_customer_project_contract p")
                .line("where p.status !='3'");
        appendCondition(builder, map);
        return Db.queryLong(builder.build(), builder.params());
    }

    private boolean checkPlanCodeExists(String code, String excludeId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1)")
                .line("from crm_customer_project_contract p")
                .line("where p.status !='3' and p.number=?", code);
        if (StrKit.notBlank(excludeId)) {
            builder.line("and p.id != ?", excludeId);
        }
        return Db.queryLong(builder.build(), builder.params()) != 0;
    }


    private void appendCondition(SqlBuilder builder, Map<String, String> map) {
        if (StringUtil.checkParamsValid(map.get("number"))) {
            builder.line("and p.number like concat('%', ?, '%')", map.get("number").trim());
        }
        if (StringUtil.checkParamsValid(map.get("customerName"))) {
            builder.line("and p.customer_name like concat('%', ?, '%')", map.get("customerName").trim());
        }
        if (StringUtil.checkParamsValid(map.get("idCode"))) {
            builder.line("and p.id_code like concat('%', ?, '%')", map.get("idCode").trim());
        }
        if (StringUtil.checkParamsValid(map.get("status"))) {
            builder.line("and p.status =?", map.get("status").trim());
        }
    }

    /**
     * 校验导入物料数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> checkImportPlan(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "check");
        ContractExcelImportHandler handler = new ContractExcelImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(1);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String templateError = (String) map.get("TemplateError");
            if (!handler.isCheckFlag()) {
                handler.appendErrorDetail("<p>未填充数据</p>");
            }
            String hanl = handler.getErrorDetail();
            if (StrKit.notBlank(templateError)) {
                retMap.put("errorDetail", templateError);
                retMap.put("errorMessage", "y");
            } else if (StringUtils.isNotBlank(hanl)) {
                retMap.put("errorDetail", hanl);
                retMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                retMap.put("overLimit", "y");
            } else {
                retMap.put("pass", "y");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retMap;
    }

    /**
     * 导入物料数据
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importPlan(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "import");
        ContractExcelImportHandler handler = new ContractExcelImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);

        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);

            retMap.put("pass", "y");
            //  retMap.put("materialList", handler.getRetList());

            List<CrmProjectContract> exeSqlParams = handler.getRetList();
            if (exeSqlParams != null && exeSqlParams.size() > 0) {
                //新增导入数据
                importProjectContract(exeSqlParams);
            }
            retMap.put("successCount", exeSqlParams.size());//成功条数
        } catch (Exception e) {
            e.printStackTrace();
            retMap.put("pass", "no");
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return retMap;
    }

    public Result importProjectContract(List<CrmProjectContract> paramList) {
        Date time = new Date();
        User user = UserUtils.getUser();
        String UserName = CrmUtils.getUserXM(user);
        // List<CrmProjectContract> listorder = Lists.newArrayList();
        int i = 1;
        for (CrmProjectContract item : paramList) {
            String number = PlantformUtils.getOrderNumber() + i;
            item.setNumber(number);
            item.setCreateName(UserName);
            item.setCreateTime(time);
            item.setStatus(SourceConstants.ONE);
            i++;
        }
        projectDao.save(paramList);
        return Result.ok();
    }
}