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.GrxxglBLO;
import com.zjrs.zwnw.jbxxgl.dto.*;
import com.zjrs.zwnw.jbxxgl.entity.VAc01Mapper;
import com.zjrs.zwnw.jbxxgl.entity.VRsSjxgrzGrMapper;
import com.zjrs.zwnw.jbxxgl.entity.VRsSjxgrzMapper;
import com.zjrs.zwnw.jbxxgl.entity.VSSgAreaMapper;
import com.zjrs.zwnw.jbxxgl.po.*;
import com.zjrs.zwnw.portal.entity.VRsSyOrgAreaMapper;
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 GrxxglBLOimpl extends BPOImpl implements GrxxglBLO {
    private static final Logger LOG = LoggerFactory.getLogger(GrxxglBLOimpl.class);

    @Resource
    private VAc01Mapper vAc01Mapper;

    @Resource
    private VRsSyOrgAreaMapper vRsSyOrgAreaMapper;

    @Resource
    private VRsSjxgrzMapper vRsSjxgrzMapper;

    @Resource
    private VRsSjxgrzGrMapper vRsSjxgrzGrMapper;

    @Resource
    private VSSgAreaMapper vSSgAreaMapper;


    @Override
    public PageResult getGrxxList(GrxxQueryDTO dto) {
        Map<String, Object> params = new HashMap<String, Object>();
        boolean isquery = true;
        Page<VSAc01PO> page1 = new Page<>(dto.getPagenum(), dto.getPagesize());
        QueryWrapper<VSAc01PO> queryWrapper = new QueryWrapper<VSAc01PO>();

        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");
        } else {
            if (params.size() > 0) {
                queryWrapper.allEq(params).orderByDesc("bae003");
            } else {
                isquery = false;
            }
        }
        PageResult result = new PageResult();
        if (isquery) {
            Page<VSAc01PO> pageResult = (Page) this.vAc01Mapper.selectPage(page1, queryWrapper);
            result = PageUtil.PageResult(pageResult);
        } else {
            throw new AppException("查询条件不能为空");
        }
        return result;
    }

    @Override
    public VSAc01PO getGrxx(JbxxglCommonDTO dto) {
        String flag = dto.getFlag();
        VSAc01PO po = new VSAc01PO();
        if (flag.equals("view")) {
            if (StringUtils.isNotBlank(dto.getId())) {
                po = vAc01Mapper.selectOne(new QueryWrapper<VSAc01PO>().eq("ztid", dto.getId().trim()));
            } 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 saveGrxx(GrxxDTO dto) {
        VSAc01PO po = new VSAc01PO();
        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);//最近修改时间
        po.setBae007(orgid);//修改系统机构代码
        po.setLy("2");//来源
        if (StringUtils.isNotBlank(po.getZtid())) {
            //修改
            //3、查询页面的修改按钮提供修改功能只能修改除身份证类型、身份证号码、国籍、社会保障号码、姓名、性别、民族、出身日期、户口性质、户籍地址之外的其他字段
            //查询数据
            VSAc01PO oldpo = vAc01Mapper.selectOne(new QueryWrapper<VSAc01PO>().eq("ztid", dto.getZtid().trim()));
            if (!isequal(po.getAac058(), oldpo.getAac058())
                    || !isequal(po.getAac147(), oldpo.getAac147())
                    || !isequal(po.getAac009(), oldpo.getAac009())
                    || !isequal(po.getAac300(), oldpo.getAac300())) {
                throw new AppException("身份证类型、身份证号码、国籍、社会保障号码、姓名、性别、民族、出身日期、户口性质、户籍地址不允许修改");
            }
            String ztid = po.getZtid().trim();
            vAc01Mapper.update(po, new UpdateWrapper<VSAc01PO>().eq("ztid", ztid));
        } else {
            po.setBae001(currentUser.getRegioncode());//行政区划
            po.setBae002(userid);//创建人
            po.setBae003(dataString);//创建时间
            po.setBae006(orgid);//创建系统机构代码
            vAc01Mapper.insert(po);
        }
        return po.getZtid();
    }

    @Override
    public String saveGrjbxx(GrjbxxDTO dto) {
        VSAc01PO po = new VSAc01PO();
        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);//最近修改时间
        po.setBae007(orgid);//修改系统机构代码
        po.setLy("2");//来源
        if (StringUtils.isNotBlank(po.getZtid())) {
            // 变更关键信息包括：身份证类型、身份证号码、社会保障号码、国籍、姓名、性别、民族、户籍地址（行政区划代码）
            VSAc01PO oldpo = vAc01Mapper.selectOne(new QueryWrapper<VSAc01PO>().eq("ztid", dto.getZtid().trim()));
            if (!isequal(po.getAac058(), oldpo.getAac058())) {
                String aac058 = po.getAac058().trim();
                String aac147 = po.getAac147().trim();
                int cnt = vAc01Mapper.selectCount(new QueryWrapper<VSAc01PO>()
                        .eq("aac058",aac058));
                if (cnt > 0) {
                    throw new AppException("证件号码为" + aac147 + "的个人已存在");
                }
                

                VRsSjxgrzPO logpo = new VRsSjxgrzPO();
                logpo.setSjbm("ac01");//数据表名
                logpo.setYsj(oldpo.getAac058()==null?"":oldpo.getAac058().trim());//原数据
                vRsSjxgrzMapper.insert(logpo);
            }
            String ztid = dto.getZtid().trim();
            vAc01Mapper.update(po, new UpdateWrapper<VSAc01PO>().eq("ztid", ztid));
        }
        return po.getZtid();
    }

    @Override
    public PageResult getGrjbxxLog(GrLogQueryDTO dto) {
        Map<String, Object> params = new HashMap<String, Object>();
        boolean isquery = true;
        Page<VRsSjxgrzGrPO> page1 = new Page<>(dto.getPagenum(), dto.getPagesize());
        // 查询条件
        QueryWrapper<VRsSjxgrzGrPO> queryWrapper = new QueryWrapper<VRsSjxgrzGrPO>();

        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<VRsSjxgrzGrPO> pageResult = (Page) this.vRsSjxgrzGrMapper.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;
    }
}
