package com.zehong.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zehong.common.exception.CustomException;
import com.zehong.common.utils.GovernmentDataCopyUtil;
import com.zehong.common.utils.GovernmentDataUtil;
import com.zehong.common.utils.StringUtils;
import com.zehong.system.domain.SysSetting;
import com.zehong.system.domain.TInsHazRef;
import com.zehong.system.domain.TInsRecInfor;
import com.zehong.system.domain.vo.TInsRecInforVo;
import com.zehong.system.mapper.TInsHazRefMapper;
import com.zehong.system.mapper.TInsRecInforMapper;
import com.zehong.system.service.ISysSettingService;
import com.zehong.system.service.ITInsRecInforService;
import com.zehong.system.service.ITSerialNumberInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 监督检查-检查记录Service业务层处理
 * 
 * @author zehong
 * @date 2024-05-20
 */
@Service
public class TInsRecInforServiceImpl implements ITInsRecInforService 
{
    private static final Logger log = LoggerFactory.getLogger(TInsRecInforServiceImpl.class);

    @Autowired
    private TInsRecInforMapper tInsRecInforMapper;

    @Resource
    private GovernmentDataUtil governmentDataUtil;

    @Resource
    private ISysSettingService sysSettingService;

    @Resource
    private ITSerialNumberInfoService itSerialNumberInfoService;

    @Resource
    private TInsHazRefMapper tInsHazRefMapper;

    /**
     * 查询监督检查-检查记录
     * 
     * @param fInsRecInforId 监督检查-检查记录ID
     * @return 监督检查-检查记录
     */
    @Override
    public TInsRecInfor selectTInsRecInforById(Long fInsRecInforId)
    {
        return tInsRecInforMapper.selectTInsRecInforById(fInsRecInforId);
    }

    /**
     * 查询监督检查-检查记录列表
     * 
     * @param tInsRecInfor 监督检查-检查记录
     * @return 监督检查-检查记录
     */
    @Override
    public List<TInsRecInfor> selectTInsRecInforList(TInsRecInfor tInsRecInfor)
    {
        return tInsRecInforMapper.selectTInsRecInforList(tInsRecInfor);
    }

    /**
     * 新增监督检查-检查记录
     * 
     * @param tInsRecInfor 监督检查-检查记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTInsRecInfor(TInsRecInfor tInsRecInfor)
    {
        tInsRecInfor.setfLastUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        SysSetting code = sysSettingService.getSystemValueByKey("city_id");
        if(null == code || StringUtils.isEmpty(code.getSystemValue())) throw new CustomException("行政编码未配置！");
        Map<String,String> num = itSerialNumberInfoService.getSerialNumberByTableType("t_ins_rec_infor");
        if(null == num || StringUtils.isEmpty(num.get("f_check_code"))) throw new CustomException("检查记录编码未配置！");
        tInsRecInfor.setfCheckCode(code.getSystemValue()+ Year.now().getValue() + num.get("f_check_code"));
        if(!CollectionUtils.isEmpty(tInsRecInfor.getRectificationList())){
            for(TInsHazRef ref : tInsRecInfor.getRectificationList()){
                ref.setfCheckCode(tInsRecInfor.getfCheckCode());
                addInsHazRef(ref);
            }
        }
        return tInsRecInforMapper.insertTInsRecInfor(tInsRecInfor);
    }

    /**
     * 修改监督检查-检查记录
     * 
     * @param tInsRecInfor 监督检查-检查记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTInsRecInfor(TInsRecInfor tInsRecInfor){
        tInsRecInfor.setfLastUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if(!CollectionUtils.isEmpty(tInsRecInfor.getRectificationList())){
            tInsHazRefMapper.deleteTInsHazRefByCheckCode(tInsRecInfor.getfCheckCode());
            for(TInsHazRef ref : tInsRecInfor.getRectificationList()){
                ref.setfObjType(tInsRecInfor.getfObjectType());
                ref.setfObjCode(tInsRecInfor.getfObjectCode());
                ref.setfCheckCode(tInsRecInfor.getfCheckCode());
                addInsHazRef(ref);
            }
        }
        return tInsRecInforMapper.updateTInsRecInfor(tInsRecInfor);
    }

    /**
     * 新增隐患
     * @param ref
     */
    private void addInsHazRef(TInsHazRef ref){
        try{
            ref.setfLastTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            tInsHazRefMapper.insertTInsHazRef(ref);
        }catch (Exception  e){
            Throwable cause = e.getCause();
            if (cause instanceof SQLIntegrityConstraintViolationException){
                String errMsg = cause.getMessage();
                if (StringUtils.isNotEmpty(errMsg) && errMsg.contains("index_hazard_unique_code")){
                    throw new CustomException("隐患唯一编码不唯一");
                }
            }
            throw new CustomException("隐患新增失败");
        }
    }


    /**
     * 批量删除监督检查-检查记录
     * 
     * @param fInsRecInforIds 需要删除的监督检查-检查记录ID
     * @return 结果
     */
    @Override
    public int deleteTInsRecInforByIds(Long[] fInsRecInforIds)
    {
        return tInsRecInforMapper.deleteTInsRecInforByIds(fInsRecInforIds);
    }

    /**
     * 删除监督检查-检查记录信息
     * 
     * @param fInsRecInforId 监督检查-检查记录ID
     * @return 结果
     */
    @Override
    public int deleteTInsRecInforById(Long fInsRecInforId)
    {
        return tInsRecInforMapper.deleteTInsRecInforById(fInsRecInforId);
    }

    /**
     * 上传检查记录
     * @param fInsRecInforId 检查记录id
     * @return
     */
    @Override
    public int reportRecInfo(Long fInsRecInforId) throws Exception {
        TInsRecInfor recInfor = tInsRecInforMapper.selectTInsRecInforById(fInsRecInforId);
        TInsRecInforVo insRecInforVo = new TInsRecInforVo();
        GovernmentDataCopyUtil.copyToGovernData(recInfor,insRecInforVo);
        List<TInsRecInforVo> data = new ArrayList<>();
        data.add(insRecInforVo);
        JSONObject reportResult = governmentDataUtil.setInfo("inspection/record/information","WRITE",data);
        log.info("上传检查记录结果===================" + reportResult.toJSONString());
        if(!"0".equals(reportResult.getString("resultCode"))) throw new CustomException("上传检查记录市局接口失败");
        recInfor.setGovUploadState("1");
        recInfor.setGovUploadTime(new Date());
        int i = tInsRecInforMapper.updateTInsRecInfor(recInfor);
        if(i == 0) throw new CustomException("检查记录上传状态更新失败");
        return 1;
    }
}
