package com.zjrs.zwnw.sxgl.blo.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.domain.blo.impl.BLOImpl;
import org.mohrss.leaf.core.framework.persistens.PageResult;
import org.mohrss.leaf.core.framework.persistens.PageUtil;
import org.mohrss.leaf.core.framework.util.CurrentUser;
import org.mohrss.leaf.core.framework.util.SecurityUtils;
import com.zjrs.zwnw.sxgl.blo.JcsxqdkBLO;
import com.zjrs.zwnw.sxgl.dto.*;
import com.zjrs.zwnw.sxgl.entity.DictMapper;
import com.zjrs.zwnw.sxgl.entity.SxpzxxMapper;
import com.zjrs.zwnw.sxgl.entity.SxtempMapper;
import com.zjrs.zwnw.sxgl.po.Aa10PO;
import com.zjrs.zwnw.sxgl.po.SxpzxxPO;
import com.zjrs.zwnw.sxgl.po.SxtempPO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class JcsxqdkBLOimpl extends BLOImpl implements JcsxqdkBLO {
    @Resource
    SxtempMapper sxtempMapper;
    @Resource
    SxpzxxMapper sxpzxxMapper;
    @Resource
    DictMapper dictMapper;
    @Override
    public PageResult getDrjgtj(SxtempQueryDTO dto, int page, int rows) {

        Page<SxtempTjListDTO> page1 = new Page<>(page, rows);
        Page<SxtempTjListDTO> pageResult = (Page) this.sxtempMapper.getDrjgtj(page1, dto.getDrph());
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public PageResult getDrjgList(SxtempQueryDTO dto, int page, int rows) {
        QueryWrapper<SxtempPO> queryWrapper = new QueryWrapper<>();
        //查询字段
        queryWrapper.eq("drph", dto.getDrph()).eq("drjg", dto.getDrjg());
        queryWrapper.orderByAsc("jbbm");

        Page<SxtempPO> page1 = new Page<>(page, rows);
        Page<SxtempPO> pageResult = (Page) this.sxtempMapper.selectPage(page1, queryWrapper);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public void exportSx(SxExportQueryDTO dto, HttpServletResponse res) {
        InputStream inputStream = null;
        try {
            inputStream = JcsxqdkBLOimpl.class.getClassLoader()
                    .getResourceAsStream("templates" + File.separator + "sxgl" + File.separator + "export.xlsx");

            String fileName = "事项导出结果.xlsx";
            res.setContentType("application/vnd.ms-excel;charset=utf-8");
            res.setHeader("Content-disposition", "attachment;filename=" + fileName);
            res.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Map<String, String> importSx(InputStream is) throws Exception {
        //导入批号
        String drph = UUID.randomUUID().toString().replaceAll("-", "");
        Map<String, String> resultMap = new HashMap<>();

        //导入所需字典
        Map<String, Object> aa10RowSet = getAa10RowSet();

        Map<String, String> fieldsMapper = new HashMap<String, String>();
        fieldsMapper.put("基本编码", "jbbm");
        fieldsMapper.put("实施清单名称", "sxmc");
        fieldsMapper.put("实施编码", "ssbm");
        fieldsMapper.put("事项类型", "sxlx");
        fieldsMapper.put("办件类型", "bjlx");

        resultMap.put("code", "0");
        resultMap.put("msg", "导入成功");
        resultMap.put("drph", drph);
        return resultMap;
    }

    @Override
    public Map<String, String> saveSxjbxx(SxpzxxXsUpdateDTO dto) {
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "操作成功");

        SxpzxxPO sxpzxxPO = new SxpzxxPO();
        BeanUtils.copyProperties(dto, sxpzxxPO);
        sxpzxxPO.setYxbz("1");
//        sxpzxxPO.setSszt("1");//确认实施
        sxpzxxPO.setFbzt("0");//未发布
        //从上下文中获取当前登陆用户
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sxpzxxPO.setTsCzsj(df.format(t));
        if (StringUtils.isNotBlank(dto.getRsSxConfigLsh())) {
            //更新
            this.sxpzxxMapper.updateById(sxpzxxPO);
        } else {
            //新增
//            sxpzxxPO.setRsSxConfigLsh(UUID.randomUUID().toString().replaceAll("-", ""));
            sxpzxxPO.setProcessDefName(dto.getSxmc());
            this.sxpzxxMapper.insert(sxpzxxPO);
        }
        return resultMap;
    }

    private void validationRule(SxpzxxPO sxpzxxPO, Map<String, Object> valuesMap, Map<String, Object> aa10RowSet, StringBuilder builder) {
        String jbbm = objToStr(valuesMap.get("jbbm"));
        String cnbjsxdw = objToStr(valuesMap.get("cnbjsxdw"));
        String sfzcwlkd = objToStr(valuesMap.get("sfzcwlkd"));
        String sxbb = objToStr(valuesMap.get("sxbb"));
        String bjlx = objToStr(valuesMap.get("bjlx"));
        if (StringUtils.isBlank(sfzcwlkd)) {
            builder.append("“是否支持物流快递”、");
        }
        if (StringUtils.isBlank(sxbb)) {
            builder.append("“事项版本”、");
        }
        if (StringUtils.isBlank(bjlx)) {
            builder.append("“办件类型”、");
        }
        if (builder.indexOf("、") > 0) {
            builder.deleteCharAt(builder.length() - 1);
            builder.append("列为必填项，内容不能为空;");
        }
        List<Aa10PO> sxlxList = (List<Aa10PO>) aa10RowSet.get("sxlx");
        List<Aa10PO> dxccsList = (List<Aa10PO>) aa10RowSet.get("dxccs");
        List<Aa10PO> sxdwList = (List<Aa10PO>) aa10RowSet.get("sxdw");
        List<Aa10PO> app001List = (List<Aa10PO>) aa10RowSet.get("app001");
        List<Aa10PO> bjlxList = (List<Aa10PO>) aa10RowSet.get("bjlx");

        Map<String, String> dictMap = null;

        if (StringUtils.isNotBlank(sfzcwlkd)) {
            dictMap = getAa10Aaa102(sfzcwlkd, app001List);
            if (StringUtils.isBlank(dictMap.get("code"))) {
                builder.append("“是否支持物流快递”列内容不符合导入要求，只能为以下其中一项：")
                        .append(dictMap.get("names")).append("；");
            } else {
                valuesMap.put("sfzcwlkdCode", dictMap.get("code"));
            }
        }
        if (StringUtils.isNotBlank(bjlx)) {
            dictMap = getAa10Aaa102(bjlx, bjlxList);
            if (StringUtils.isBlank(dictMap.get("code"))) {
                builder.append("“办件类型”列内容不符合导入要求，只能为以下其中一项：")
                        .append(dictMap.get("names")).append("；");
            } else {
                valuesMap.put("bjlx", dictMap.get("code"));
            }
        }


    }

    private Map<String, Object> getAa10RowSet() {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<Aa10PO> aa10QueryWrapper = null;
        //是否APP001
        aa10QueryWrapper = new QueryWrapper<>();
        aa10QueryWrapper.eq("AAA100", "APP001");
        List<Aa10PO> app001List = dictMapper.selectList(aa10QueryWrapper);
        //办件类型
        aa10QueryWrapper = new QueryWrapper<>();
        List<Aa10PO> bjlxList = dictMapper.selectList(aa10QueryWrapper);

        result.put("app001", app001List);
        result.put("bjlx", bjlxList);
        return result;
    }

    private Map<String, String> getAa10Aaa102(String aaa103, List<Aa10PO> aa10List) {
        //事项类型,到现场次数,时限单位,APP001
        Map<String, String> resultMap = new HashMap<>();
        String code = null;
        StringBuilder names = new StringBuilder();

        resultMap.put("code", code);
        if (names != null && names.length() > 0) {
            resultMap.put("names", names.deleteCharAt(names.length() - 1).toString());
        } else {
            resultMap.put("names", "");
        }
        return resultMap;
    }

    //object对象转为String,主要处理BigDecimal
    private String objToStr(Object obj) {
        String str = null;
        if (obj instanceof String) {
            str = (String) obj;
        } else if (obj instanceof BigDecimal) {
            str = ((BigDecimal) obj).stripTrailingZeros().toPlainString();
        }
        if (StringUtils.isNotBlank(str)) {
            str = str.trim();
        }
        return str;
    }

    private int getLength(String str) {
        int length = 0;
        if (StringUtils.isNotBlank(str)) {
            try {
                length = str.trim().getBytes("GBK").length;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return length;
    }

    /**
     * 校验正整数
     * @param str
     * @return
     */
    public boolean isPureDigital(String str) {
        if (str == null || "".equals(str)){
            return false;
        }

        Pattern p;
        Matcher m;
        p = Pattern.compile("[0-9]*");
        m = p.matcher(str);
        if (m.matches()){
            return true;
        }else{
            return false;
        }
    }
}
