package com.ruoyi.system.service.grid.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.ext.GridCompanyExt;
import com.ruoyi.system.domain.system.SysOtherappAttachment;
import com.ruoyi.system.domain.system.SysOtherappAttachmentExample;
import com.ruoyi.system.domain.system.enums.AttachEnums;
import com.ruoyi.system.domain.visit.enums.VisitTypeEnum;
import com.ruoyi.system.domain.visit.ext.VisitFreeInterviewExt;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.grid.*;
import com.ruoyi.system.mapper.system.SysOtherappAttachmentMapper;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.grid.*;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.system.service.visit.VisitFreeInterviewService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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 java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Cesar
 * @date ${cTime}
 * @desc GridInterviewService实现
 */
@Service
@MyBaseService
public class GridInterviewServiceImpl extends BaseServiceImpl<GridInterviewMapper, GridInterview, GridInterviewExample> implements GridInterviewService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GridInterviewServiceImpl.class);

    @Autowired
    private SysOtherappAttachmentMapper sysOtherappAttachmentMapper;
    @Autowired
    private GridCompanyService gridCompanyService;
    @Autowired
    private GridShopService gridShopService;
    @Autowired
    private VisitFreeInterviewService visitFreeInterviewService;
    @Autowired
    private GridRegionUserService gridRegionUserService;
    @Autowired
    private GridHousePeopleMapper gridHousePeopleMapper;
    @Autowired
    private GridCompanyPeopleMapper gridCompanyPeopleMapper;
    @Autowired
    private GridShopStaffMapper gridShopStaffMapper;
    @Autowired
    private GridPublicOpinionsMapper gridPublicOpinionsMapper;
    @Autowired
    private GridHouseInterviewMapper gridHouseInterviewMapper;
    @Autowired
    private GridInterviewMapper gridInterviewMapper;
    @Autowired
    private GridWgLogService gridWgLogService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public List<GridInterview> interviewPage(String cid) {
        GridInterviewExample ex = new GridInterviewExample();
        GridInterviewExample.Criteria ca = ex.createCriteria();
        ca.andCidEqualTo(cid);
        ex.setOrderByClause(" interview_time desc, create_time desc ");
        List<GridInterview> list = this.selectByExample(ex);
        for (GridInterview wsInterview : list) {
            SysOtherappAttachmentExample ex1 = new SysOtherappAttachmentExample();
            SysOtherappAttachmentExample.Criteria ca1 = ex1.createCriteria();
            ca1.andAttachTypeEqualTo(AttachEnums.AttachType.PLAN_TASK.name());
            ca1.andBusinessIdEqualTo(wsInterview.getId());
            List<SysOtherappAttachment> attachmentList = sysOtherappAttachmentMapper.selectByExample(ex1);
            wsInterview.setAttachmentList(attachmentList);
        }
        return list;
    }

    @Override
    @Transactional
    public String interviewAdd(GridInterview wsInterview) {
        VisitFreeInterviewExt visitFreeInterviewExt = new VisitFreeInterviewExt();
        wsInterview.setId(IdUtil.fastSimpleUUID());
        wsInterview.setCreateTime(DateUtil.formatDateTime(new Date()));
        if (CollectionUtils.isNotEmpty(wsInterview.getAttachmentList())) {
            for (SysOtherappAttachment at : wsInterview.getAttachmentList()) {
                at.setAttachType(AttachEnums.AttachType.PLAN_TASK.name());
                at.setBusinessId(wsInterview.getId());
                sysOtherappAttachmentMapper.insertSelective(at);
            }
            visitFreeInterviewExt.setOtherappAttachments(wsInterview.getAttachmentList());
        }
        this.insertSelective(wsInterview);

        // 调用新增自由走访数据
        visitFreeInterviewExt.setWgCode(wsInterview.getWgCode());
        visitFreeInterviewExt.setWgValue(wsInterview.getWgValue());
        GridRegionUser regionUser = gridRegionUserService.selectByUserId(wsInterview.getCreateId());
        visitFreeInterviewExt.setWgyCode(regionUser != null ? regionUser.getWgId() : "");
        visitFreeInterviewExt.setWgyName(wsInterview.getCreateName());
        visitFreeInterviewExt.setInterviewTime(wsInterview.getInterviewTime());
        visitFreeInterviewExt.setObjId(wsInterview.getCid());
        visitFreeInterviewExt.setContent(wsInterview.getContent());
        visitFreeInterviewExt.setLongitude(wsInterview.getLongitude());
        visitFreeInterviewExt.setLatitude(wsInterview.getLatitude());
        visitFreeInterviewExt.setAddress(wsInterview.getAddress());
        visitFreeInterviewExt.setActualTime(wsInterview.getCreateTime());

        // type字段没有传值,这里根据cid长度区分企业和商铺
        if (wsInterview.getCid().length() == 32) {
            visitFreeInterviewExt.setType("1");
            GridCompanyExt wsCompanyExt = (GridCompanyExt) gridCompanyService.detail(wsInterview.getCid()).get("data");
            if (wsCompanyExt != null) {
                visitFreeInterviewExt.setObjName(wsCompanyExt.getCompanyName());
                visitFreeInterviewExt.setObjType(wsCompanyExt.getQylxCode());
                visitFreeInterviewExt.setObjTypeName(wsCompanyExt.getQylxValue());
                visitFreeInterviewExt.setObjUserName(wsCompanyExt.getLawPerson());
                visitFreeInterviewExt.setObjNumber(wsCompanyExt.getCreditCode());
            }
        } else {
            visitFreeInterviewExt.setType("2");
            GridShop wsShop = gridShopService.getGridShopById(Long.valueOf(wsInterview.getCid()));
            if (wsShop != null) {
                visitFreeInterviewExt.setObjName(wsShop.getShopName());
                visitFreeInterviewExt.setObjType(wsShop.getShopType());
                visitFreeInterviewExt.setObjTypeName(wsShop.getShopTypeName());
                visitFreeInterviewExt.setObjUserName(wsShop.getShopOwner());
                visitFreeInterviewExt.setObjNumber(wsShop.getLicenseCode());
            }
        }
        visitFreeInterviewExt.setVisitType(VisitTypeEnum.FREE_VISIT.getCode());
        visitFreeInterviewService.addVisitFreeInterview(visitFreeInterviewExt);

        // 日志
        SysUser sysUser = sysUserService.selectUserById(wsInterview.getCreateId());
        GridWgLog wsWgLog = new GridWgLog();
        wsWgLog.setCreateId(wsInterview.getCreateId());
        wsWgLog.setCreateName(sysUser != null ? sysUser.getNickName() : "");
        wsWgLog.setCreateWgCode(wsInterview.getWgCode());
        wsWgLog.setObjectName(wsInterview.getCidName());
        // type字段没有传值,这里根据cid长度区分企业和商铺
        if (wsInterview.getCid().length() == 32) {
            wsWgLog.setType("3");
        } else {
            wsWgLog.setType("4");
        }
        wsWgLog.setOperate("interview");
        wsWgLog.setObjectId(wsInterview.getId());
        gridWgLogService.add(wsWgLog);

        return wsInterview.getId();
    }

    @Override
    public void edit(GridInterview wsInterview) {
        Validator.validateNotEmpty(wsInterview.getId(), "id is empty");
        this.updateByPrimaryKeySelective(wsInterview);
    }

    @Override
    public GridInterview detail(String id) {
        GridInterview wsInterview = this.selectByPrimaryKey(id);
        if (wsInterview != null) {
            SysOtherappAttachmentExample ex = new SysOtherappAttachmentExample();
            SysOtherappAttachmentExample.Criteria ca = ex.createCriteria();
            ca.andBusinessIdEqualTo(id);
            List<SysOtherappAttachment> attachmentList = sysOtherappAttachmentMapper.selectByExample(ex);
            wsInterview.setAttachmentList(attachmentList);
            return wsInterview;
        }
        return null;
    }

    @Override
    @Transactional
    public void delete(String ids) {
        String[] idArray = ids.split(",");
        for (String idStr : idArray) {
            if (StringUtils.isBlank(idStr)) {
                continue;
            }
            SysOtherappAttachmentExample ex = new SysOtherappAttachmentExample();
            SysOtherappAttachmentExample.Criteria ca = ex.createCriteria();
            ca.andBusinessIdEqualTo(idStr);
            sysOtherappAttachmentMapper.deleteByExample(ex);
            gridInterviewMapper.deleteByPrimaryKey(idStr);
        }
    }

    @Override
    public long count(String type, String id) {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, -30);
        String prev = DateUtil.formatDateTime(cal.getTime());
        String today = DateUtil.formatDateTime(date);
        if ("1".equals(type)) {
            GridPublicOpinionsExample ex = new GridPublicOpinionsExample();
            GridPublicOpinionsExample.Criteria ca = ex.createCriteria();
            ca.andPeopleIdEqualTo(id);
            ca.andCreateTimeBetween(prev, today);
            return gridPublicOpinionsMapper.countByExample(ex);
        } else if ("2".equals(type)) {
            GridHouseInterviewExample ex = new GridHouseInterviewExample();
            GridHouseInterviewExample.Criteria ca = ex.createCriteria();
            ca.andHouseIdEqualTo(id);
            ca.andCreateTimeBetween(prev, today);
            return gridHouseInterviewMapper.countByExample(ex);
        } else if ("3".equals(type) || "4".equals(type)) {
            GridInterviewExample ex = new GridInterviewExample();
            GridInterviewExample.Criteria ca = ex.createCriteria();
            ca.andCidEqualTo(id);
            ca.andCreateTimeBetween(prev, today);
            return gridInterviewMapper.countByExample(ex);
        }
        return 0;
    }

    @Override
    public long pending(String type, String id) {
        long a = 0;
        if ("1".equals(type)) {
            // 人口是否存在关联
            // 是否存在关联住宅
            GridHousePeopleExample ex = new GridHousePeopleExample();
            GridHousePeopleExample.Criteria ca = ex.createCriteria();
            ca.andPeopleIdEqualTo(id);
            a = gridHousePeopleMapper.countByExample(ex);
            if (a == 0) {
                // 是否存在关联企业
                GridCompanyPeopleExample ex1 = new GridCompanyPeopleExample();
                GridCompanyPeopleExample.Criteria ca1 = ex1.createCriteria();
                ca1.andPeopleIdEqualTo(id);
                a = gridCompanyPeopleMapper.countByExample(ex1);
            }
            if (a == 0) {
                // 是否存在关联商铺
                GridShopStaffExample ex2 = new GridShopStaffExample();
                GridShopStaffExample.Criteria ca2 = ex2.createCriteria();
                ca2.andPeopleIdEqualTo(id);
                ca2.andValidEqualTo(Byte.valueOf("1"));
                a = gridShopStaffMapper.countByExample(ex2);
            }
        } else if ("2".equals(type)) {
            // 住宅是否存在关联人口
            GridHousePeopleExample ex = new GridHousePeopleExample();
            GridHousePeopleExample.Criteria ca = ex.createCriteria();
            ca.andHouseIdEqualTo(id);
            a = gridHousePeopleMapper.countByExample(ex);
        } else if ("3".equals(type)) {
            // 企业是否存在关联人口
            GridCompanyPeopleExample ex = new GridCompanyPeopleExample();
            GridCompanyPeopleExample.Criteria ca = ex.createCriteria();
            ca.andCompanyIdEqualTo(id);
            a = gridCompanyPeopleMapper.countByExample(ex);
        } else if ("4".equals(type)) {
            // 商铺是否存在关联人口
            GridShopStaffExample ex = new GridShopStaffExample();
            GridShopStaffExample.Criteria ca = ex.createCriteria();
            ca.andShopIdEqualTo(Long.valueOf(id));
            ca.andValidEqualTo(Byte.valueOf("1"));
            a = gridShopStaffMapper.countByExample(ex);
        }
        return a;
    }
}
