package com.sifang.modules.sys.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.dao.CustomerDao;
import com.sifang.modules.customer.entity.Customer;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.dao.CrmAnnouncementReadInfoDao;
import com.sifang.modules.sys.dao.CrmPlatformAnnouncementDao;
import com.sifang.modules.sys.dao.CustomerNoticeDao;
import com.sifang.modules.sys.entity.CrmAnnouncementReadinfo;
import com.sifang.modules.sys.entity.CrmPlatformAnnouncement;
import com.sifang.modules.sys.entity.CustomerNotice;
import com.sifang.modules.sys.util.*;
import com.sifang.modules.sys.web.form.NotificationForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CrmPlatformAnnouncementService extends BaseService {

    @Autowired
    CrmPlatformAnnouncementDao crmPlatformAnnouncementDao;
    @Autowired
    CrmAnnouncementReadInfoDao crmAnnouncementReadInfoDao;

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CustomerNoticeDao customerNoticeDao;

    @Transactional(rollbackFor = Exception.class)
    public Result<Void> create(NotificationForm form) {
        User user = UserUtils.getUser();
        Map<String,String> map = Maps.newHashMap();
        if(StringUtil.isNotEmpty(form.getCustomerId())){
            map.put("customerId",form.getCustomerId());
        }
        if(StringUtil.isNotEmpty(form.getProvince())){
            map.put("province",form.getProvince());
        }
        if("2".equals(form.getIsMany())&&StringUtil.isNotEmpty(form.getCity())){
            //多市
            map.put("city",form.getCity());
        }
        if(StringUtil.checkParamsValid(form.getStationBuildingStart())){
            map.put("stationBuildingStart", DateUtils.formatDate(form.getStationBuildingStart(),""));
        }
        if(StringUtil.checkParamsValid(form.getStationBuildingEnd())){
            map.put("stationBuildingEnd",DateUtils.formatDate(form.getStationBuildingEnd(),""));
        }
        if (StringUtil.checkParamsValid(form.getLoginNumMin())) {
            map.put("loginNumMin",form.getLoginNumMin());
        }
        if (StringUtil.checkParamsValid(form.getLoginNumMax())) {
            map.put("loginNumMax",form.getLoginNumMax());
        }




        //根据条件查询所有的用户
        CrmPlatformAnnouncement a = new CrmPlatformAnnouncement();
        a.setTitle(form.getTitle());
        a.setHtml(form.getHtml());
        a.setStatus("0");
        a.setCreateTime(new Date());
        a.setCreateBy(user.getId());
        a.setCreator(CrmUtils.getUserXM(user));
        a.setObjType(form.getObjType());
        a.setProvince(form.getProvince());
        a.setCity(form.getCity());
        a.setCustomerId(form.getCustomerId());
        a.setCustomerName(form.getCustomerName());
        a.setIsMany(form.getIsMany());
        a.setLoginNumMin(StringUtil.isNotEmpty(form.getLoginNumMin())?Integer.parseInt(form.getLoginNumMin()):0);
        a.setLoginNumMax(StringUtil.isNotEmpty(form.getLoginNumMax())?Integer.parseInt(form.getLoginNumMax()):0);
        a.setStationBuildingEnd(form.getStationBuildingEnd());
        a.setStationBuildingStart(form.getStationBuildingStart());
        crmPlatformAnnouncementDao.save(a);
        if("1".equals(a.getObjType())){
            List<Record> list = customerDao.getCustomerList(null,map);
            List<CustomerNotice> ices = Lists.newArrayList();
            for(Record rd:list){
                String id = rd.getStr("cuId");
                CustomerNotice notice = new CustomerNotice();
                notice.setCustomerId(id);
                notice.setAnnouncementId(a.getId());
                ices.add(notice);
            }
            customerNoticeDao.save(ices);
        }
        return Result.ok();
    }

    public void listData(TrimStrMap parasMap, LayuiPage<Record> page) {
        crmPlatformAnnouncementDao.listData(parasMap, page);
    }

    public CrmPlatformAnnouncement get(String id) {
        return crmPlatformAnnouncementDao.get(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Void> update(NotificationForm form) {
        CrmPlatformAnnouncement a = crmPlatformAnnouncementDao.get(form.getId());
        a.setHtml(form.getHtml());
        a.setTitle(form.getTitle());
     /*   a.setObjType(form.getObjType());*/
        return Result.ok();
    }

    public Result<Void> delete(String ids) {
        String[] split = ids.split(",");
        Db.update("update crm_platform_announcement set status='1' where id in(" + SqlUtils.inParam(split) + ")");
        return Result.ok();
    }

    public void listMessageData(TrimStrMap parasMap, LayuiPage<Record> page) {
        crmPlatformAnnouncementDao.listMessageData(parasMap, page);
    }

    public Result<Void> markMsgAsRead(String ids) {
        String[] idList = ids.split(",");
        return crmAnnouncementReadInfoDao.markMsgAsRead(idList);
    }

    public boolean hasRead(String announcementId) {
        return crmAnnouncementReadInfoDao.hasRead(announcementId);
    }

    public long unReadMsgCount() {
        return crmPlatformAnnouncementDao.unReadMsgCount();
    }

    public List<Record> getTechnicalData(Map<String, String> params) {
        StringBuilder sb = new StringBuilder("");
        sb.append(" select *,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s') as createTime from crm_technical_data a where a.status = '0' and a.type=? ");
        if (params.containsKey("name") && StrKit.notBlank(params.get("name"))) {
            sb.append(" and a.name like '%" + params.get("name").trim() + "%'");
        }
        sb.append("order by a.create_time desc ");
        sb.append(SqlUtils.generateLimitSqlForMysql(params.get("limit"), params.get("page")));
        return Db.find(sb.toString(),params.get("type"));
    }

    public long countTechnicalData(Map<String, String> params) {
        StringBuilder sb = new StringBuilder("");
        sb.append(" select count(1) from crm_technical_data a where a.status = '0' and a.type=? ");
        if (params.containsKey("name") && StrKit.notBlank(params.get("name"))) {
            sb.append(" and a.name like '%" + params.get("name") + "%' ");

        }
        return Db.queryLong(sb.toString(),params.get("type"));
    }

    public String delTechnicalData(Map<String, String> map) {
        try {
            String[] split = map.get("id").split(",");
            Db.update(" update crm_technical_data set status = '1' where id  in ("+SqlUtils.inParam(split) +")" );
        } catch (Exception e) {
            e.printStackTrace();
            return "err";
        }
        return "ok";
    }
    public String saveTechnicalData(Map<String, String> params) {
        try{
            StringBuilder sb = new StringBuilder("");
            sb.append(" insert into crm_technical_data (id, name, description, href, create_time, create_by, creator, status,type) ");
            sb.append(" values (?, ?, ?, ?, ?, ?, ?, ?,?) ");
            User user = UserUtils.getUser();
            Db.update(sb.toString(), IdGen.uuid(), params.get("title"), params.get("description"), params.get("url"), new Date(),
                    user.getId(), user.getLoginName(),"0",params.get("type"));
        }catch (Exception e){
            e.printStackTrace();
            return "err";
        }
        return "ok";
    }

    /**
     * 将看过的通知公告标记为已读
     */
    public Map<String,Object> markAnnounceById(String id,User user){
        logger.info("markAnnounceByApp : {} ,userId : {} "+ id ,user.getId());
        Map<String,Object> map = Maps.newHashMap();
            SqlBuilder sb = new SqlBuilder()
                    .line("select platform_announcement_id from crm_announcement_readinfo")
                    .line("where read_id=? and platform_announcement_id=? and status='0'");
            Record record=Db.findFirst(sb.build(),user.getId(),id);
            if(record==null){
                CrmAnnouncementReadinfo info = new CrmAnnouncementReadinfo();
                info.setReadId(user.getId());
                info.setReader(user.getUserName());
                info.setPlatformAnnouncementId(id);
                info.setStatus("0");
                info.setCreateTime(new Date());
                info.setReaderType("0");
                info.setParentId(user.getId());
                crmAnnouncementReadInfoDao.save(info);
            }
            map.put("code","200");
            map.put("data",id);

        return  map;
    }


    public Record findAnnouncementOne(String userId){
        return crmPlatformAnnouncementDao.findAnnouncementOne(userId);
    }

    public List<Record> indexGetAnnounceList(String userId){
        List<Record> list= crmPlatformAnnouncementDao.indexGetAnnounceList(userId);
        return list;
    }

}
