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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.domain.bpo.impl.BPOImpl;
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.web.exception.AppException;
import com.zjrs.zwnw.jbxxgl.blo.DwxxglBLO;
import com.zjrs.zwnw.jbxxgl.dto.*;
import com.zjrs.zwnw.jbxxgl.entity.*;
import com.zjrs.zwnw.jbxxgl.po.VRsSjxgrzDwPO;
import com.zjrs.zwnw.jbxxgl.po.VRsSjxgrzPO;
import com.zjrs.zwnw.jbxxgl.po.VSAb01PO;
import com.zjrs.zwnw.jbxxgl.po.VSSgAreaPO;
import com.zjrs.zwnw.portal.entity.VRsSyOrgAreaMapper;
import com.zjrs.zwnw.portal.po.VRsSyOrgAreaPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class DwxxglBLOimpl extends BPOImpl implements DwxxglBLO {
    private static final Logger LOG = LoggerFactory.getLogger(DwxxglBLOimpl.class);

    @Resource
    private VAb01Mapper vAb01Mapper;

    @Resource
    private VRsSyOrgAreaMapper vRsSyOrgAreaMapper;

    @Resource
    private VRsSjxgrzMapper vRsSjxgrzMapper;

    @Resource
    private VRsSjxgrzDwMapper vRsSjxgrzDwMapper;

    @Resource
    private VSSgAreaMapper vSSgAreaMapper;

    @Resource
    private VAaa3Mapper vAaa3Mapper;

    @Override
    public PageResult getDwxxList(DwxxQueryDTO dto) {
        Map<String, Object> params = new HashMap<String, Object>();
        boolean isquery = true;
        int cnt = 0;

        Page<VSAb01PO> page1 = new Page<>(dto.getPagenum(), dto.getPagesize());
        QueryWrapper<VSAb01PO> queryWrapper = new QueryWrapper<VSAb01PO>();
        if (StringUtils.isNotBlank(dto.getAab004())) {
            //单位名称
            queryWrapper.like("aab004", dto.getAab004().trim());
            cnt++;
        }
        if (StringUtils.isNotBlank(dto.getCjsjc()) && StringUtils.isNotBlank(dto.getCjsjz())) {
            queryWrapper.allEq(params)
                    .orderByDesc("bae003");
        } else if (StringUtils.isNotBlank(dto.getCjsjc()) && !StringUtils.isNotBlank(dto.getCjsjz())) {
            queryWrapper.allEq(params)
                    .orderByDesc("bae003");
        } else if (!StringUtils.isNotBlank(dto.getCjsjc()) && StringUtils.isNotBlank(dto.getCjsjz())) {
            queryWrapper.allEq(params)
                    .orderByDesc("bae003");
        } 
        PageResult result = new PageResult();
        if (isquery) {
            Page<VSAb01PO> pageResult = (Page) this.vAb01Mapper.selectPage(page1, queryWrapper);
            result = PageUtil.PageResult(pageResult);
        } else {
            throw new AppException("查询条件不能为空");
        }
        return result;
    }

    @Override
    public VSAb01PO getDwxx(JbxxglCommonDTO dto) {
        String flag = dto.getFlag();
        VSAb01PO po = new VSAb01PO();
        if (flag.equals("view")) {
            if (StringUtils.isNotBlank(dto.getId())) {
                po = vAb01Mapper.selectOne(new QueryWrapper<VSAb01PO>().eq("ztid", dto.getId().trim()));
                if (StringUtils.isNotBlank(po.getBae002())) {// && !po.getBae002().equals("数据同步")
                    // 获取创建人的组织机构，行政区划
                    VRsSyOrgAreaPO cjrorgareapo = vRsSyOrgAreaMapper.selectOne(new QueryWrapper<VRsSyOrgAreaPO>()
                            .eq("user_id", po.getBae002().trim()));
                    if (cjrorgareapo!=null){
                        String cjorgname = cjrorgareapo.getOrgname();
                        String cjusername = cjrorgareapo.getUsername();
                        po.setBae002(cjusername);//创建人
                        po.setBae006(cjorgname);//创建系统机构代码
                    }
                }
                if (StringUtils.isNotBlank(po.getBae004())) {// && !po.getBae004().equals("数据同步")
                    // 获取最近修改人的组织机构，行政区划
                    VRsSyOrgAreaPO xgrorgareapo = vRsSyOrgAreaMapper.selectOne(new QueryWrapper<VRsSyOrgAreaPO>()
                            .eq("user_id", po.getBae004().trim()));
                    if (xgrorgareapo!=null){
                        String xgorgname = xgrorgareapo.getOrgname();
                        String xgusername = xgrorgareapo.getUsername();
                        po.setBae004(xgusername);//最近修改人
                        po.setBae007(xgorgname);//最近修改系统机构代码
                    }
                }
            } else {
                throw new AppException("缺少主键参数");
            }
        } else if (flag.equals("add")) {
        } else if (flag.equals("edit")) {
            if (StringUtils.isNotBlank(dto.getId())) {
                po = vAb01Mapper.selectOne(new QueryWrapper<VSAb01PO>().eq("ztid", dto.getId().trim()));
                if (StringUtils.isNotBlank(po.getBae002())) {// && !po.getBae002().equals("数据同步")
                    // 获取创建人的组织机构，行政区划
                    VRsSyOrgAreaPO orgareapo = vRsSyOrgAreaMapper.selectOne(new QueryWrapper<VRsSyOrgAreaPO>()
                            .eq("user_id", po.getBae002().trim()));
                    if (orgareapo!=null){
                        String cjorgname = orgareapo.getOrgname();
                        String cjusername = orgareapo.getUsername();
                        po.setBae002(cjusername);//创建人
                        po.setBae006(cjorgname);//创建系统机构代码
                    }
                }
                if (StringUtils.isNotBlank(po.getBae004())) {// && !po.getBae004().equals("数据同步")
                    // 获取最近修改人的组织机构，行政区划
                    VRsSyOrgAreaPO xgrorgareapo = vRsSyOrgAreaMapper.selectOne(new QueryWrapper<VRsSyOrgAreaPO>()
                            .eq("user_id", po.getBae004().trim()));
                    if (xgrorgareapo!=null){
                        String xgorgname = xgrorgareapo.getOrgname();
                        String xgusername = xgrorgareapo.getUsername();
                        po.setBae004(xgusername);//最近修改人
                        po.setBae007(xgorgname);//最近修改系统机构代码
                    }
                }
            } else {
                throw new AppException("缺少主键参数");
            }
        }
        return po;
    }

    public String getXzqhQc(String id, String title) {
        VSSgAreaPO popr = vSSgAreaMapper.selectOne(new QueryWrapper<VSSgAreaPO>()
                .eq("area_code", id));
        String prname = popr.getAreaname() == null ? "" : popr.getAreaname().trim();
        title = prname + title;
        if (StringUtils.isNotBlank(popr.getParentid())) {
            VSSgAreaPO poprpr = vSSgAreaMapper.selectOne(new QueryWrapper<VSSgAreaPO>()
                    .eq("area_code", popr.getParentid()));
            String prprname = poprpr.getAreaname() == null ? "" : poprpr.getAreaname().trim();
            title = prprname + title;
        }
        return title;
    }

    @Override
    public String saveDwxx(DwxxDTO dto) {
        VSAb01PO po = new VSAb01PO();
        BeanUtils.copyProperties(dto, po);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dataString = dateFormat.format(date);
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUserid();
        String orgid = currentUser.getOrgid();
        po.setBae004(userid);//最近修改人
        po.setLy("2");//来源
        //校验统一社会信用代码是否符合规范
        if (StringUtils.isNotBlank(po.getAab998())) {
            String aab998 = po.getAab998().trim();
        }
        //校验法人证件号码aac058，aab014
        if (StringUtils.isNotBlank(po.getAac058()) && StringUtils.isNotBlank(po.getAab014())) {
            String aac058 = po.getAac058().trim();
            String aab014 = po.getAab014().trim();
        }
        if (StringUtils.isNotBlank(dto.getZtid())) {
            //修改
            //1.修改单位基本信息，不允许对“单位名称、统一社会信用代码、法定代表人、注册地址（描述）、注册地址（行政区划代码）、单位类型、有效状态”进行修改。
            //查询以前的数据
            VSAb01PO oldpo = new VSAb01PO();
            oldpo = vAb01Mapper.selectOne(new QueryWrapper<VSAb01PO>().eq("ztid", dto.getZtid().trim()));
            if (!isequal(po.getAab004(), oldpo.getAab004())
                    || !isequal(po.getAab019(), oldpo.getAab019())
                    || !isequal(po.getBaa120(), oldpo.getBaa120())) {
                throw new AppException("单位名称、统一社会信用代码、法定代表人、注册地址（描述）、注册地址（行政区划代码）、单位类型、有效状态不允许修改");
            }
            String ztid = dto.getZtid().trim();
            vAb01Mapper.update(po, new UpdateWrapper<VSAb01PO>().eq("ztid", ztid));
        } else {
            //新增
            po.setBae001(currentUser.getRegioncode());//行政区划
            po.setBae002(userid);//创建人
            vAb01Mapper.insert(po);
        }
        return po.getZtid();
    }

    @Override
    public String saveDwjbxx(DwjbxxDTO dto) {
        VSAb01PO po = new VSAb01PO();
        BeanUtils.copyProperties(dto, po);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dataString = dateFormat.format(date);
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUserid();
        String orgid = currentUser.getOrgid();
        po.setBae004(userid);//最近修改人
        po.setBae005(dataString);//最近修改时间
        if (StringUtils.isNotBlank(dto.getZtid())) {
            //变更关键信息包括：单位名称、统一社会信用代码、法定代表人、注册地址（描述）、注册地址（行政区划代码）、单位类型、有效状态
            //查询以前的数据
            VSAb01PO oldpo = new VSAb01PO();
            oldpo = vAb01Mapper.selectOne(new QueryWrapper<VSAb01PO>().eq("ztid", dto.getZtid().trim()));
            if (!isequal(po.getAab004(), oldpo.getAab004())) {

                VRsSjxgrzPO logpo = new VRsSjxgrzPO();
                logpo.setSjbm("ab01");//数据表名
                logpo.setXsj(po.getAab004() == null ? "" : po.getAab004().trim());//新数据
                logpo.setYsj(oldpo.getAab004() == null ? "" : oldpo.getAab004().trim());//原数据
                vRsSjxgrzMapper.insert(logpo);
            }
            String ztid = dto.getZtid().trim();
            vAb01Mapper.update(po, new UpdateWrapper<VSAb01PO>().eq("ztid", ztid));
        }
        return po.getZtid();
    }

    @Override
    public PageResult getDwjbxxLog(DwLogQueryDTO dto) {
        Map<String, Object> params = new HashMap<String, Object>();
        boolean isquery = true;
        Page<VRsSjxgrzDwPO> page1 = new Page<>(dto.getPagenum(), dto.getPagesize());
        // 查询条件
        QueryWrapper<VRsSjxgrzDwPO> queryWrapper = new QueryWrapper<VRsSjxgrzDwPO>();
        if (StringUtils.isNotBlank(dto.getBgsjc()) && StringUtils.isNotBlank(dto.getBgsjz())) {
            queryWrapper.allEq(params)
                    .orderByDesc("jbsj");
        } else if (StringUtils.isNotBlank(dto.getBgsjc()) && !StringUtils.isNotBlank(dto.getBgsjz())) {
            queryWrapper.allEq(params)
                    .orderByDesc("jbsj");
        } else if (!StringUtils.isNotBlank(dto.getBgsjc()) && StringUtils.isNotBlank(dto.getBgsjz())) {
            queryWrapper.allEq(params)
                    .orderByDesc("jbsj");
        } else {
            if (params.size() > 0) {
                queryWrapper.allEq(params).orderByDesc("jbsj");
            } else {
                isquery = false;
            }
        }
        PageResult result = new PageResult();
        if (isquery) {
            Page<VRsSjxgrzDwPO> pageResult = (Page) this.vRsSjxgrzDwMapper.selectPage(page1, queryWrapper);
            result = PageUtil.PageResult(pageResult);
        } else {
            throw new AppException("查询条件不能为空");
        }
        return result;
    }

    /**
     * 只用于Long和String的比较
     */
    public boolean isequal(Object newvalue, Object oldvale) {
        boolean flag = false;
        if (newvalue == null && oldvale == null) {
            flag = true;
        } else if (newvalue != null && oldvale == null) {
            if (StringUtils.isNotBlank(String.valueOf(newvalue))) {
                flag = false;
            } else {
                flag = true;
            }
        } else if (newvalue == null && oldvale != null) {
            if (StringUtils.isNotBlank(String.valueOf(oldvale))) {
                flag = false;
            } else {
                flag = true;
            }
        } else if (newvalue != null && oldvale != null) {
            if (String.valueOf(newvalue).equals(String.valueOf(oldvale))) {
                flag = true;
            } else {
                flag = false;
            }
        }
        return flag;
    }
}
