package com.sifang.modules.customer.Service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.excel.MaterialExcel;
import com.sifang.modules.customer.utils.ExcelData;
import com.sifang.modules.customer.utils.ExportExcelUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.PlanMaterialEntryDao;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.excel.ExportExcel;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lzp
 * @create 2021-05-24 下午9:21
 * @desc excel测试类
 **/

@Service
public class ExcelService {

    @Autowired
    CustomerEntryDao customerEntryDao;

    @Autowired
    PlanMaterialEntryDao entryDao;

    private Logger logger = LoggerFactory.getLogger(getClass());


    public boolean deleteFile(String sPath) {
        boolean flag = false;
        //处理文件路径,将"/"替换成计算机识别的"\\"
        sPath = sPath.replace("/", File.separator);
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }


    public void exportExcel(Map<String, String> map, HttpServletResponse response) {
        long s1 = System.currentTimeMillis();

        Date now = new Date();
        String sn = DateUtils.formatDate(now, "yyyyMMddHHmmss");
        User user = UserUtils.getUser();
        String fileName = CrmUtils.getUserXM(user)+ "物料清单-"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
       // ExcelData data = new ExcelData();
        List<Record> list = customerEntryDao.getMaterialByCustomerEntry(map,user);
//        Record rds = customerEntryDao.getMaterialcomponentCount(map,user);
//        BigDecimal component_count = rds.getBigDecimal("component_count");
        logger.info("exportExcel map :{} ,list :{} ",map);
        //需要更具列表条件查询出所有项目信息
        if (list.size() < 1) {
            throw new AuthorizationException("产品信息为空！");
        }
        String name = "";
        if (CustomerEntryConstants.ADVANCE_STATUS_THREE.equals(map.get("status"))) {
            name = "待下单";
        }else if (CustomerEntryConstants.ADVANCE_STATUS_FIVE.equals(map.get("status"))) {
            name = "待安装";
        }else{
            name = "全部";
        }

        List<MaterialExcel> listex = new ArrayList<>();
        int sort=1;

            for (Record rd : list) {
                if(rd == null){
                    continue;
                }
                MaterialExcel platformOrderExcel = new MaterialExcel();
                platformOrderExcel.setSort(sort);
                platformOrderExcel.setCode(rd.getStr("code"));
                platformOrderExcel.setName(rd.getStr("name"));
                if(rd.getBigDecimal("amount") != null){
                    platformOrderExcel.setAmount(rd.getBigDecimal("amount").compareTo(BigDecimal.ZERO)>0?rd.getBigDecimal("amount").intValue():0);
                }else{
                    platformOrderExcel.setAmount(0);
                }
                platformOrderExcel.setSpec(rd.getStr("spec"));
                platformOrderExcel.setUnit(rd.getStr("unit"));
                platformOrderExcel.setComponentSpec(rd.getStr("component_spec"));
//                platformOrderExcel.setComponentCount(component_count.intValue());
                listex.add(platformOrderExcel);
                sort++;
            }

        long s2 = System.currentTimeMillis();
        logger.info(" >> [{}] doSave use {}ms ", sn, (s2 - s1));
        try {
            new ExportExcel(name+"物料清单", MaterialExcel.class)
                    .setDataList(listex)
                    .write(response, fileName)
                    .dispose();
        }catch (Exception e){
            logger.error("exportExcel  Exception :{}",e);
        }

    }

    public void exportMadlsdkd(Map<String, String> map, HttpServletResponse response){
        long s1 = System.currentTimeMillis();
        Date now = new Date();
        String sn = DateUtils.formatDate(now, "yyyyMMddHHmmss");
        System.out.println("计算统计----" + sn);

        String name = "全部";
        ExcelData data = new ExcelData();
        data.setTitle(name + "物料明细");
        List<Record> entrys = customerEntryDao.getCustomerEntryByScheme(map);
        List<List<Object>> rows = new ArrayList();

    /*    if (entrys.size() == 1) {
            Record rd = entrys.get(0);
            List<Object> row3 = new ArrayList();
            row3.add("产品名称");
            row3.add(rd.getStr("planName"));
            List<Object> row4 = new ArrayList();
            row4.add("项目编码");
            row4.add(rd.getStr("planCode"));
            rows.add(row3);
            rows.add(row4);
        }*/

        List<String> titles = new ArrayList();
        titles.add("序号");
        titles.add("物料编码");
        titles.add("物料名称");
        titles.add("规格");
        titles.add("单位");
        titles.add("数量");
        data.setTitles(titles);
        // 记录行数
        int n = 1;
        for(int i=0;i<10000;i++) {
            if (entrys != null && entrys.size() > 0) {
                // 遍历
                for (Record a : entrys) {
                    List<Object> row = new ArrayList();
                    row.add(n);
                    row.add(a.getStr("code"));
                    row.add(a.getStr("name"));
                    row.add(a.getStr("spec"));
                    row.add(a.getStr("unit"));
                    row.add(a.getBigDecimal("amount"));
                    rows.add(row);
                    n++;
                }
            }
        }

        data.setRows(rows);
        long s2 = System.currentTimeMillis();
        logger.info(" >> [{}] doSave use {}ms ", sn, (s2 - s1));
        try {

            ExportExcelUtils.exportExcel(response, "物料明细-"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx", data);
        }catch (Exception e){

        }
        long s3 = System.currentTimeMillis();
        logger.info(" >> [{}] end saving statistic use {}ms", sn, (s3 - s2));
    }


}