package com.jpsoft.shinestar.modules.business.service.impl;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.dao.FillAttendanceDAO;
import com.jpsoft.shinestar.modules.business.dao.FillAttendanceFilesDAO;
import com.jpsoft.shinestar.modules.business.dao.WorkAttendanceDAO;
import com.jpsoft.shinestar.modules.business.entity.FillAttendance;
import com.jpsoft.shinestar.modules.business.entity.FillAttendanceFiles;
import com.jpsoft.shinestar.modules.business.entity.WorkAttendance;
import com.jpsoft.shinestar.modules.business.service.FillAttendanceService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil2;
import com.jpsoft.shinestar.modules.common.utils.StringUtils;
import com.jpsoft.shinestar.modules.common.utils.WechatMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Transactional
@Component(value = "fillAttendanceService")
public class FillAttendanceServiceImpl implements FillAttendanceService {
    @Resource(name = "fillAttendanceDAO")
    private FillAttendanceDAO fillAttendanceDAO;

    @Value("${jwt.secret}")
    private String jwtSecret;

	@Resource(name = "workAttendanceDAO")
	private WorkAttendanceDAO workAttendanceDAO;

    @Autowired
    private WxConfig wxConfig;

	@Autowired
    private AlarmConfigService alarmConfigService;

	@Autowired
    private ApprovalConfigService approvalConfigService;

	@Autowired
    private CompanyInfoService companyInfoService;

	@Autowired
    private PersonPopedomService personPopedomService;

	@Resource(name = "fillAttendanceFilesDAO")
	private FillAttendanceFilesDAO fillAttendanceFilesDAO;

	@Autowired
	private PersonInfoService personInfoService;

    @Override
    public FillAttendance get(String id) {
        // TODO Auto-generated method stub
        return fillAttendanceDAO.get(id);
    }

    @Override
    public int insert(FillAttendance model) {
        // TODO Auto-generated method stub
        //model.setId(UUID.randomUUID().toString());

        return fillAttendanceDAO.insert(model);
    }

    @Override
    public int update(FillAttendance model) {
        // TODO Auto-generated method stub
        return fillAttendanceDAO.update(model);
    }

    @Override
    public int delete(String id) {
        // TODO Auto-generated method stub
        return fillAttendanceDAO.delete(id);
    }

    @Override
    public boolean exist(String id) {
        // TODO Auto-generated method stub
        int count = fillAttendanceDAO.exist(id);

        return count > 0 ? true : false;
    }

    @Override
    public List<FillAttendance> list() {
        // TODO Auto-generated method stub
        return fillAttendanceDAO.list();
    }

    @Override
    public Page<FillAttendance> pageSearch(Map<String, Object> searchParams, int pageNumber, int pageSize, List<Sort> sortList) {
        Page<FillAttendance> page = PageHelper.startPage(pageNumber, pageSize).doSelectPage(() -> {
            fillAttendanceDAO.search(searchParams, sortList);
        });

        return page;
    }

    @Override
    public FillAttendance insertAndfile(String workAttendanceId, String workAttendanceDate, String workAttendanceTime,
                                        String content, String type, String photoFile,String longitude,String latitude,
                                        String approvalPersonId,Long personId,String alarmConfigId,String address,String attendanceType) throws Exception{
        WorkAttendance workAttendance = null;

        if (StringUtils.isNotBlank(workAttendanceId)){
            workAttendance = workAttendanceDAO.get(workAttendanceId);
//            workAttendance.setSources("2");

            if(workAttendance!=null) {
                log.warn("{}补卡",personId);

                workAttendance.setType("2");
                workAttendanceDAO.update(workAttendance);
            }
            else{
                log.warn("补卡考勤段不存在:{}",workAttendanceId);
            }
        }

        if (workAttendance==null) {
            log.warn("{}外勤打卡",personId);

            //外勤打卡人
            PersonInfo personInfo = personInfoService.get(personId);

            //查看考勤时间段
            AlarmConfig alarmConfig = alarmConfigService.get(alarmConfigId);

            //应考勤时间点
            Date time = DateUtil.parse(alarmConfig.getAttendanceTime());

            //实际考勤时间点
            String recordTimeStr = DateUtil.format(new Date(),"HH:mm");
            Date recordTime = DateUtil.parse(recordTimeStr);

            //考勤状态
            String result = null;

            //区分上班下班
            //上班
            if (alarmConfig.getClassifier() == 1){
                if (time.compareTo(recordTime)>=0){
                    result = "1";
                }
                if (time.compareTo(recordTime)<0){
                    result = "2";
                }
            }
            //下班
            if (alarmConfig.getClassifier() == 2){
                if (time.compareTo(recordTime)>0){
                    result = "3";
                }
                if (time.compareTo(recordTime)<=0){
                    result = "1";
                }
            }

            //无考勤记录则为外勤打卡
			workAttendance = new WorkAttendance();
			workAttendance.setId(UUID.randomUUID().toString());
			workAttendance.setAlarmConfigId(alarmConfigId);
			workAttendance.setPersonId(personId);
			workAttendance.setResult(result);
			workAttendance.setTemperature(BigDecimal.ZERO);
			workAttendance.setRecordTime(new Date());
			workAttendance.setCreateTime(new Date());
			workAttendance.setDelFlag(false);
			workAttendance.setSources("2");
			workAttendance.setType("1");
			workAttendance.setWorkStatus(personInfo.getWorkStatus());

			workAttendanceDAO.insert(workAttendance);

			log.warn("新增外勤考勤记录:{}",workAttendance.getId());

			workAttendanceId = workAttendance.getId();
        }

        //新增外勤打卡、补卡申请记录
        FillAttendance fillAttendance = fillAttendanceDAO.findByBusinessWorkAttendanceId(workAttendanceId);

        if (fillAttendance !=null){
            fillAttendance.setContent(content);
            fillAttendance.setStatus("0");
            fillAttendance.setUpdateTime(new Date());
            fillAttendanceDAO.update(fillAttendance);

            if (StringUtils.isNotBlank(photoFile)) {
                FillAttendanceFiles fillAttendanceFiles = fillAttendanceFilesDAO.findByFillAttendanceId(fillAttendance.getId());
                if (fillAttendanceFiles != null){
                    fillAttendanceFiles.setFileUrl(photoFile);
                    fillAttendanceFiles.setUpdateTime(new Date());
                    fillAttendanceFilesDAO.update(fillAttendanceFiles);
                }else {
                    FillAttendanceFiles fillAttendanceFiles1 = new FillAttendanceFiles();
                    fillAttendanceFiles1.setId(UUID.randomUUID().toString());
                    fillAttendanceFiles1.setFillAttendanceId(fillAttendance.getId());
                    fillAttendanceFiles1.setFileUrl(photoFile);
                    fillAttendanceFiles1.setCreateTime(new Date());
                    fillAttendanceFiles1.setDelFlag(false);
                    fillAttendanceFilesDAO.insert(fillAttendanceFiles1);
                }
//                fillAttendanceFiles.setFillAttendanceId(fillAttendance.getId());
//                fillAttendanceFiles.setFileUrl(photoFile);
//                fillAttendanceFiles.setCreateTime(new Date());
//                fillAttendanceFiles.setDelFlag(false);
//                fillAttendanceFilesDAO.insert(fillAttendanceFiles);
            }
        }else {
            fillAttendance = new FillAttendance();
            fillAttendance.setId(UUID.randomUUID().toString());
            fillAttendance.setPersonId(personId);
            fillAttendance.setContent(content);
            fillAttendance.setType(type);
            fillAttendance.setFillDay(workAttendanceDate);
            fillAttendance.setFillAttendanceTime(workAttendanceTime);
            fillAttendance.setLongitude(longitude);
            fillAttendance.setLatitude(latitude);
            fillAttendance.setAddress(address);
            fillAttendance.setWorkStatus(attendanceType);



            if (org.apache.commons.lang3.StringUtils.isBlank(approvalPersonId)){
                fillAttendance.setApprovalContent("自动审核");
                fillAttendance.setUpdateTime(new Date());
                fillAttendance.setApprovalTime(new Date());
                fillAttendance.setApprovalPersonName("自动审核");
                fillAttendance.setStatus("1");
            }else {
                PersonPopedom personPopedom = personPopedomService.get(approvalPersonId);
                fillAttendance.setApprovalPersonPopedomId(approvalPersonId);
                fillAttendance.setApprovalPersonId(personPopedom.getPersonId());
                fillAttendance.setStatus("0");
            }

            fillAttendance.setBusinessWorkAttendanceId(workAttendanceId);
            String approvalNo = com.jpsoft.shinestar.modules.common.utils.StringUtils.getApprovalNo();
            fillAttendance.setApprovalNo(approvalNo);
            fillAttendance.setCreateTime(new Date());
            fillAttendance.setDelFlag(false);

            fillAttendanceDAO.insert(fillAttendance);

            if (StringUtils.isNotBlank(photoFile)) {
                FillAttendanceFiles fillAttendanceFiles = new FillAttendanceFiles();
                fillAttendanceFiles.setId(UUID.randomUUID().toString());
                fillAttendanceFiles.setFillAttendanceId(fillAttendance.getId());
                fillAttendanceFiles.setFileUrl(photoFile);
                fillAttendanceFiles.setCreateTime(new Date());
                fillAttendanceFiles.setDelFlag(false);
                fillAttendanceFilesDAO.insert(fillAttendanceFiles);
            }
        }

        return fillAttendance;
    }

    @Override
    public void updateAndWorkAtten(PersonInfo personInfo, String content, FillAttendance fillAttendance) {
        fillAttendance.setStatus("1");
        fillAttendance.setApprovalContent(content);
        fillAttendance.setUpdateTime(new Date());
        fillAttendance.setUpdateBy(personInfo.getName());
        fillAttendance.setApprovalTime(new Date());
        fillAttendanceDAO.update(fillAttendance);

        if (org.apache.commons.lang3.StringUtils.isNotBlank(fillAttendance.getWorkStatus())){
            //申请人
            PersonInfo personInfo1 = personInfoService.get(fillAttendance.getPersonId());
            personInfo1.setWorkStatus(fillAttendance.getWorkStatus());
            personInfoService.update(personInfo1);
        }

        WorkAttendance workAttendance = workAttendanceDAO.get(fillAttendance.getBusinessWorkAttendanceId());

        if (workAttendance!=null) {
            //补卡
            if (workAttendance.getResult().equals("0")) {
                workAttendance.setResult("1");
                workAttendanceDAO.update(workAttendance);
            }
        }
    }

    @Override
    public FillAttendance findByBusinessWorkAttendanceId(String businessWorkAttendanceId) {
        return fillAttendanceDAO.findByBusinessWorkAttendanceId(businessWorkAttendanceId);
    }

    @Override
    public void approvalFillAttendance(PersonInfo personInfo, String ids, String content, String status) throws Exception {


        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            FillAttendance fillAttendance = get(id);

            if (fillAttendance != null) {

                //申请人
                PersonInfo applyPerson = personInfoService.get(fillAttendance.getPersonId());

                if (!fillAttendance.getApprovalPersonPopedomId().equals(personInfo.getPopedom())) {
                    throw new Exception("无权审核");
                }
                String approvalPersonIdStr = fillAttendance.getApprovalPersonIdStr();
                String approvalStatusStr = fillAttendance.getApprovalStatusStr();
                String approvalTimeStr = fillAttendance.getApprovalTimeStr();
                String approvalContentStr = fillAttendance.getApprovalContentStr();

                if ("1".equals(status)) {
                    List<PersonPopedom> personPopedomList = new ArrayList<>();

                    String companyId = "";
                    //申请人的公司
                    CompanyInfo companyInfo = companyInfoService.get(applyPerson.getCompanyId());

                    if (!"1".equals(companyInfo.getUnitType())) {
                        CompanyInfo parent = null;
                        int loopNum = 10;
                        int zIndex = 0;
                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(companyInfo.getParentId())) {
                            parent = companyInfoService.get(companyInfo.getParentId());
                        }
                        while (parent != null && zIndex < loopNum) {
                            ApprovalConfig approvalConfig = approvalConfigService.findByCompanyIdAndType(companyInfo.getId(), "1");
                            if (approvalConfig != null){
                                companyId = companyInfo.getId();
                                break;
                            }else if (org.apache.commons.lang3.StringUtils.isBlank(companyInfo.getParentId())) {
                                break;
                            }else {
                                parent = companyInfoService.get(parent.getParentId());
                                companyInfo = companyInfoService.get(companyInfo.getParentId());
                                zIndex++;
                            }
                        }


                       /* CompanyInfo parent = null;
                        int loopNum = 10;
                        int zIndex = 0;

                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(companyInfo.getParentId())) {
                            parent = companyInfoService.get(companyInfo.getParentId());
                        }
                        while (parent != null && zIndex < loopNum) {

                            if ("1".equals(parent.getUnitType())) {
                                //如果是单位类型是公司或没有上级单位，则不再往上级查找
                                companyId = parent.getId();
                                break;
                            } else if (org.apache.commons.lang3.StringUtils.isEmpty(companyInfo.getParentId())) {
                                break;
                            } else {
                                parent = companyInfoService.get(parent.getParentId());
                                zIndex++;
                            }
                        }*/


                    } else {
                        companyId = companyInfo.getId();
                    }

                    //默认审核层级
                    int level = 2;

                    if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId)) {

                        ApprovalConfig approvalConfig = approvalConfigService.findByCompanyIdAndType(companyId, "1");
                        if (approvalConfig != null) {
                            level = Integer.valueOf(approvalConfig.getLevel());
                        }

                    }

                    //计算当前审核的是第几级审批
                    int nowLevel = 1;
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(approvalPersonIdStr)) {
                        nowLevel = nowLevel + Arrays.asList(approvalPersonIdStr.split(",")).size();
                    }
                    //判断已审核人总数和需要审核级数
                    if (nowLevel < level) {
                        List<PersonPopedom> dataList = personPopedomService.findApprovalList(personInfo, null, null, null);
                        if (dataList.size() > 0) {
                            personPopedomList.add(dataList.get(0));
                        }
                    }

                    //   }

                    //判断审批人数量,审批人数据为0，审批流程走完
                    if (personPopedomList.size() == 0) {
                        updateAndWorkAtten(personInfo, content, fillAttendance);
                        /*fillAttendance.setApprovalTime(new Date());
                        fillAttendance.setStatus(status);
                        fillAttendance.setApprovalContent(content);
                        fillAttendance.setUpdateBy(personInfo.getPopedom());
                        fillAttendance.setUpdateTime(new Date());
                        update(fillAttendance);*/
                    }
                    //审批人数据不为0
                    else {
                        PersonPopedom personPopedom1 = personPopedomList.get(0);
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(approvalPersonIdStr)) {
                            fillAttendance.setApprovalPersonIdStr(approvalPersonIdStr + "," + fillAttendance.getApprovalPersonPopedomId());
                            fillAttendance.setApprovalStatusStr(approvalStatusStr + "," + status);
                            fillAttendance.setApprovalTimeStr(approvalTimeStr + "," + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"));
                            fillAttendance.setApprovalContentStr(approvalContentStr + "," + content);
                        } else {
                            fillAttendance.setApprovalPersonIdStr(fillAttendance.getApprovalPersonPopedomId());
                            fillAttendance.setApprovalStatusStr(status);
                            fillAttendance.setApprovalTimeStr(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"));
                            fillAttendance.setApprovalContentStr(content);
                        }

                        fillAttendance.setApprovalPersonPopedomId(personPopedom1.getId());
                        fillAttendance.setApprovalPersonId(personPopedom1.getPersonId());
                        fillAttendance.setStatus("0");
                        fillAttendance.setApprovalContent("");
                        fillAttendance.setApprovalTime(null);
                        update(fillAttendance);



                        new Thread(() -> {
                            PersonInfo approvalPerson = personInfoService.get(personPopedom1.getPersonId());

                            String typeN = "补卡";
                            String url = "master/attendance/verifyInfo?id=";

                            String accessToken = JwtUtil2.createToken(jwtSecret, approvalPerson.getId() + "", DateTime.now().plusHours(30*24).toDate());
                            WechatMessageUtil.sendEvenMessage(approvalPerson.getOpenId(), "有一条新的" + typeN + "信息待审核", applyPerson.getName(), fillAttendance.getApprovalNo(), "前往处理", wxConfig.getPortalUrl() + url + fillAttendance.getId() + "&exchange=1&role_id=" + personPopedom1.getId() + "&token=" + accessToken, wxConfig.getAppId(), wxConfig.getAppSecret());

                        }).start();

                    }

                }


                if ("2".equals(status)) {
                    fillAttendance.setStatus(status);
                    fillAttendance.setUpdateTime(new Date());
                    fillAttendance.setUpdateBy(personInfo.getName());
                    fillAttendance.setApprovalTime(new Date());
                    fillAttendance.setApprovalContent(content);
                    update(fillAttendance);
                } /*else {
                    updateAndWorkAtten(personInfo, content, fillAttendance);
                }*/
            }
        }

    }


}