package com.bcxin.ars.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.dto.PersonStudyDTO;
import com.bcxin.ars.dto.PersonStudySearchDTO;
import com.bcxin.ars.dto.SecurityPersonDTO;
import com.bcxin.ars.exception.ArsException;
import com.bcxin.ars.model.PersonBaseInfo;
import com.bcxin.ars.model.SecurityPerson;
import com.bcxin.ars.model.certificate.SecurityCertificate;
import com.bcxin.ars.model.task.TaskTrack;
import com.bcxin.ars.rest.dto.AppAjaxResult;
import com.bcxin.ars.rest.util.ArsRestUtil;
import com.bcxin.ars.service.PersonBaseInfoService;
import com.bcxin.ars.service.SecurityPersonService;
import com.bcxin.ars.service.UserRoleService;
import com.bcxin.ars.service.certificate.SecurityCertificateService;
import com.bcxin.ars.service.util.ConfigUtils;
import com.bcxin.ars.util.BeanUtils;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.DateUtil;
import com.bcxin.ars.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("person")
public class SecurityPersonController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(SecurityPersonController.class);

    @Autowired
    private SecurityPersonService personService;

    @Autowired
    private ArsRestUtil arsUtil;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private SecurityCertificateService securityCertificateService;

    @Autowired
    private PersonBaseInfoService personBaseInfoService;

    @Autowired
    private ConfigUtils configUtils;


    @Value("${person-download-folder}")
    private String downloadFolder;

    @Value("${base-folder}")
    private String baseFolder;
    /**
     * 更新人员手机(SAAS接口)
     *
     * @param request
     * @return
     */
    @RequestMapping("updatePhone")
    public @ResponseBody
    AjaxResult updatePhone(SecurityPersonDTO personDTO, HttpServletRequest request) {
        AjaxResult result = new AjaxResult();

      try {
            personService.changePersonPhone(personDTO);
            result.setSuccessful(true);
            result.setMsg("操作成功");

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /**
     * 批量更新保安员身份认证状态(SAAS接口)
     * @param persons
     * @return
     */
    @RequestMapping("updateIdentityAuthState")
    public @ResponseBody AjaxResult updateIdentityAuthState(String persons) {
        AjaxResult result = new AjaxResult();
        try {
            List<SecurityPersonDTO> personList = JSONArray.parseArray(persons,SecurityPersonDTO.class);
            //当前时间
            Date d = new Date();
            new Thread(()-> {
                for (SecurityPersonDTO person : personList) {
                    //设置更新时间
                    person.setUpdateTime(d);
                    //获取华为云图片并转换成百保盾
                    if (StringUtil.isNotEmpty(person.getPhoto())) {
                        //更新照片
                        person.setPhoto(getPhotoPath(person.getPhoto()));
                    }
                }
                personService.updatePersonidentityAuthStateBatchForPhoto(personList);
            }).start();
            personService.batchUpdateIdentityAuthStateForSaas(personList);
            result.setSuccessful(true);
            result.setMsg("更新成功！");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setSuccessful(false);
            result.setMsg("更新失败，百保盾异常，异常信息：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新保安员(SAAS接口)
     *
     * @param personDTO
     * @param request
     * @return
     */
    @RequestMapping("update")
    public @ResponseBody
    AjaxResult update(@Valid SecurityPersonDTO personDTO, HttpServletRequest request) {
        AjaxResult result = new AjaxResult();
        SecurityPerson person = new SecurityPerson();
        personDTO.setRealName(personDTO.getRealname());
        if(StringUtil.isNotEmpty(personDTO.getEntrydateStr())) {
            /**
             * 入职日期 字符串形式的
             * 解决 date型 saas那边传过来无法接收报错
             */
            personDTO.setEntrydate(DateUtil.convertStringToDate(personDTO.getEntrydateStr()));
        }
        BeanUtils.copyPropertiesIgnore(personDTO, person);
        try {
            Long nativeCode = arsUtil.getCurrentNatvie();
            if (nativeCode == null) {
                person.setNativeCode(nativeCode);
            }
            //更新人员信息
            personService.saveOrUpdateForSaas(personDTO,null);
            result.setSuccessful(true);
            result.setMsg("操作成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /**
     *更新人员证件照信息(企业上传)
     * @param person
     * @return
     */
    /*@RequestMapping("updateComIdPhoto")
    public @ResponseBody
    AjaxResult updateComIdPhoto(@Valid SecurityPerson person) {
        AjaxResult result = new AjaxResult();
        try {
            //更新人员证件照信息
            if(person.getId() == null){
                throw new ArsException("保安员id不能为空！");
            }
            if(StringUtil.isEmpty(person.getComIdPhoto())){
                throw new ArsException("证件照不能为空！");
            }
            person.setComIdPhoto(getPhotoPath(person.getComIdPhoto()));
            personService.updateComIdPhoto(person);
            result.setSuccessful(true);
            result.setMsg("操作成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }*/

    /**
     *更新人员证件照信息（app上传）
     * @param person
     * @return
     */
    @RequestMapping("updateIdPhoto")
    public @ResponseBody
    AjaxResult updateIdPhoto(@Valid SecurityPerson person) {
        AjaxResult result = new AjaxResult();
        try {
            //更新人员证件照信息
            if(person.getId() == null){
                throw new ArsException("保安员id不能为空！");
            }
            if(StringUtil.isEmpty(person.getIdPhoto())){
                throw new ArsException("证件照不能为空！");
            }
            person.setIdPhoto(getPhotoPath(person.getIdPhoto()));
            personService.updateIdPhoto(person);
            result.setSuccessful(true);
            result.setMsg("操作成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }
    /**
     *删除人员证件照信息
     * @param person
     * @return
     */
    @RequestMapping("delIdPhoto")
    public @ResponseBody
    AjaxResult delIdPhoto(@Valid SecurityPerson person) {
        AjaxResult result = new AjaxResult();
        try {
            //更新人员证件照信息
            if(person.getId() == null){
                throw new ArsException("保安员id不能为空！");
            }
            personService.delIdPhoto(person);
            result.setSuccessful(true);
            result.setMsg("操作成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /****
     * 更新人员投保状态
     * @param dto
     * @return
     */
    @RequestMapping("updatePersonInsuredState")
    public @ResponseBody
    AjaxResult updatePersonInsuredState(SecurityPersonDTO dto) {
        try {
            return personService.updatePersonInsuredState(dto);
        } catch (Exception e) {
            throw e;
        }
    }
    /**
     *
     * @Decription:保安员更新证书信息
     * @author：zhongjianhui
     * @method  updateCertificate
     * @date：2019/1/16 14:51
     * @params： * @param personIds
     * @return com.bcxin.ars.dto.AjaxResult
     */
    @RequestMapping("updateCertificate")
    public @ResponseBody
    AjaxResult updateCertificate(SecurityPerson person) {
        try {
            return personService.updateCertificate(person);
        } catch (Exception e) {
            throw e;
        }
    }
    /**
     *
     * @Decription:保安员批量更新证书信息
     * @author：zhongjianhui
     * @method  updateCertificate
     * @date：2019/1/16 14:51
     * @params： * @param personIds
     * @return com.bcxin.ars.dto.AjaxResult
     */
    @RequestMapping("batchUpdateCertificate")
    public @ResponseBody
    AjaxResult batchUpdateCertificate(String perCerList) {
        AjaxResult result = new AjaxResult();
        try {
            List<SecurityPersonDTO> personDTOList=JSONArray.parseArray(perCerList,SecurityPersonDTO.class);
            personService.batchUpdateCertificate(personDTOList);
            result.setSuccessful(true);
            result.setMsg("操作成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /**
     * 批量离职
     *
     * @param personIds
     * @return
     * @author LinQingLin
     * @date 2017年4月10日 下午4:07:12
     * @注意事项 </b>
     * <b>
     */
    @RequestMapping("batchDelete")
    public @ResponseBody
    AjaxResult batchDelete(String personIds) {
        try {
            String[] perIds = personIds.split(",");
            Long[] longPerIds= new Long[perIds.length];
            for(int i = 0, len = perIds.length; i < len; i++){
                longPerIds[i] = new Long(perIds[i]);
            }
            return personService.batchDelete(longPerIds);
        } catch (Exception e) {
            throw e;
        }
    }
    /**
     * 批量调整部门
     *
     * @return
     * @author zjh
     * @date 2018年11月21日 下午4:07:12
     * @注意事项 </b>
     * <b>
     */
    @RequestMapping("batchAdjDept")
    public @ResponseBody
    AjaxResult batchAdjDept(String perIds,Long newDepartId) {
        try {
            List<String> perIdList = JSON.parseArray(perIds, String.class);
            return personService.batchAdjDeptForSaas(perIdList,newDepartId);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 批量更新保安员(SAAS接口)
     *
     * @param request
     * @return
     */
    @RequestMapping("batchUpdate")
    public @ResponseBody
    AjaxResult betchUpdate(String persons, HttpServletRequest request) {
        AjaxResult result = new AjaxResult();
        try {
            List<SecurityPersonDTO> personDTOList=JSONArray.parseArray(persons,SecurityPersonDTO.class);
             personService.batchSaveOrUpdateForSaas(personDTOList);
            result.setSuccessful(true);
            result.setMsg("操作成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }


    /**
     * 删除保安员
     *
     * @param person
     * @param request
     * @return
     */

    @RequestMapping("delete")
    @Deprecated
    public @ResponseBody
    AjaxResult delete(SecurityPerson person, HttpServletRequest request) {
        AjaxResult result = new AjaxResult();
        try {
            personService.delete(person);
            result.setSuccessful(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }


    /**
     * 解除合同
     * <b>Function </b>
     *
     * @param personId
     * @return
     * @author LinQingLin
     * @date 2017年5月19日 下午7:51:23
     * @注意事项 </b>
     * <b>
     */
    @RequestMapping("relieveHt")
    public @ResponseBody
    AjaxResult relieveHt(Long personId) {
        try {
            return personService.relieveHt(personId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 劳动合同
     *
     * @param person
     * @param request
     * @return
     */
    @RequestMapping("updateHt")
    public @ResponseBody
    AjaxResult updateHt(SecurityPerson person, HttpServletRequest request) {
        AjaxResult result = new AjaxResult();
        try {
            Long nativeCode = arsUtil.getCurrentNatvie();
            if (nativeCode == null) {
                person.setNativeCode(nativeCode);
            }
            personService.saveOrUpdateHt(person);
            result.setSuccessful(true);
            result.setData(person);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }


    /**
     * @return
     * @athour wjb
     * @time 2018年8月21日09:48:48
     * @desc 根据申请ID获取证书明细
     */
    @RequestMapping("findBySecuritypersonid")
    public @ResponseBody
    AjaxResult findBySecuritypersonid(String certificateId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        AjaxResult result = new AjaxResult();
        try {
            //允许跨域访问
            response.setHeader("Access-Control-Allow-Origin", "*");
            //获取路径
            String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            AppAjaxResult appAjaxResult = new AppAjaxResult();

            //生成二维码的时候用URLDecoder.encode加密，所以这里要decode解密
            appAjaxResult.setData(URLDecoder.decode(certificateId, "utf-8"));
            String decodeCertificateId = appAjaxResult.getDecodeData();
            if (null == decodeCertificateId || StringUtil.isEmpty(decodeCertificateId)) {
                appAjaxResult.setData(certificateId);
            }
            //获取APP端传过来的参数信息
            decodeCertificateId = appAjaxResult.getDecodeData();
            if (null == decodeCertificateId || StringUtil.isEmpty(decodeCertificateId)) {
                appAjaxResult.setData(certificateId);
                decodeCertificateId = appAjaxResult.getDecodeData();
            }


            if (null != decodeCertificateId) {
                SecurityCertificate securityCertificate = securityCertificateService.findBySecuritypersonidWithPhotoAndQR(Long.parseLong(decodeCertificateId), certificateId, path);
                if (securityCertificate != null) {
                    result.setSuccessful(true);
                    result.setData(securityCertificate);
                } else {
                    result.setSuccessful(false);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }


    /**
     * 保安员课程学习统计画像  -- liumd 0411
     *
     * @param dto
     * @return
     */
    @RequestMapping("findPersonStudyReport")
    public @ResponseBody
    AjaxResult findPersonStudyReport(PersonStudySearchDTO dto) {
        AjaxResult result = new AjaxResult();
        try {

            SecurityPerson person = personService.findById(dto.getPersonid());
            dto.setCompanyid(person.getRelation().getCompany().getId());
            //获取当前员工的学习时长  用于返回页面展示图表
            PersonStudyDTO data = personService.findPersonStudyReport(dto);
            dto.setPaging(false);
            if (data != null && data.getPersonid() != null && data.getStudylong() != null && data.getStudylong() > 0) {
                List<PersonStudyDTO> reportDatas = personService.getStudyListDesc(dto);
                Long count = 0l;

                for (PersonStudyDTO personStudyReportData : reportDatas) {
                    if (personStudyReportData.getPersonid() != data.getPersonid()) {
                        if (personStudyReportData.getStudyprogress() < data.getStudyprogress()) {
                            count++;
                        }
                    }
                }
                data.setRate(count * 100 / reportDatas.size() + "%");

                if (StringUtil.isNotEmpty(data.getTrainType())) {
                    String[] trainTypes = data.getTrainType().split("#");
                    if (!trainTypes[0].equals(trainTypes[01])) {
                        StringBuffer studyType = new StringBuffer("正在学习课程：");
                        if (trainTypes[0].equals("1")) {
                            studyType.append("初级保安员培训");
                        } else if (trainTypes[0].equals("2")) {
                            studyType.append("继续再教育");
                        }
                        if (trainTypes[1].equals("1")) {
                            studyType.append("、初级保安员培训");
                        } else if (trainTypes[1].equals("2")) {
                            studyType.append("、继续再教育");
                        }
                        data.setTrainType(studyType.toString());
                    } else {
                        if (trainTypes[0].equals("1")) {
                            data.setTrainType("正在学习课程：初级保安员培训");
                        } else if (trainTypes[0].equals("2")) {
                            data.setTrainType("正在学习课程：继续再教育");
                        } else {
                            data.setTrainType("正在学习课程：暂无");
                        }
                    }
                }
            } else {
                data = new PersonStudyDTO();
                data.setValue(0L);
                data.setName("0%");
                data.setRate("0%");
                data.setStudylong(0l);
                data.setVideonum(0);
                data.setStudyday(0);
            }
            result.setData(data);
            result.setSuccessful(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /**
     * 获取指定保安员明细
     * @param request
     * @return
     */
    @RequestMapping("findById")
    public @ResponseBody  AjaxResult findById(Long id, HttpServletRequest request) {
        AjaxResult result = new AjaxResult();
        try {
            SecurityPerson person = personService.findById(id);
            if (person != null) {
                result.setSuccessful(true);
                result.setData(person);
            } else {
                result.setSuccessful(false);
                result.setMsg("未找到指定人员信息。");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }
    /**
     * 更新保安员位置
     * @param track
     * @return
     */
    @RequestMapping("updateLocation")
    public @ResponseBody AppAjaxResult updateLocation(TaskTrack track) throws Exception {
        AppAjaxResult result = new AppAjaxResult();
        try {
            SecurityPerson dbPerson = personService.findById(track.getPersonId());
            if(dbPerson!=null) {
                //经度维度不能是一样的
                if (!track.getLatitude().equals(track.getLongitude())) {
                    dbPerson.setLatitude(track.getLatitude());
                    dbPerson.setLongitude(track.getLongitude());
                    personService.updateLocation(dbPerson);
                    result.setSuccessful(true);
                } else {
                    throw new RuntimeException("经度维度一致，位置有问题:" + dbPerson.getId());
                }
            }else{
                result.setSuccessful(true);
                result.setMsg("人员ID【"+track.getPersonId()+"】信息找不到");
            }
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
            result.setSuccessful(false);
            result.setMsg(e.getMessage());
        }
        return result;
    }


    /**
     * 校验人员是否有人口库照片接口
     * @param idnum
     * @return
     */
    @RequestMapping("checkPersonBaseHeadImg")
    public @ResponseBody  AjaxResult checkPersonBaseHeadImg(String idnum) {
        AjaxResult result = new AjaxResult();
        try {
            result.setSuccessful(true);
            PersonBaseInfo personBaseInfo = personBaseInfoService.findByIdNum(idnum);
            if (personBaseInfo != null) {
                result.setData(Constants.YES);
            } else {
                result.setData(Constants.NO);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /**
     * 校验人员获得资格证是否满一年
     */
    @RequestMapping("checkAyearAndAday")
    public @ResponseBody  AjaxResult checkyearAndday(String idnum) {
        AjaxResult result = new AjaxResult();
        try {
            result = securityCertificateService.checkyearAndday(idnum);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setSuccessful(false);
            throw e;
        }
        return result;
    }

    /**
     * 获取人员库照片
     */
    @RequestMapping("getPersonImg")
    public @ResponseBody  AjaxResult getPersonImg(String idnum) {
        AjaxResult result = new AjaxResult();
        try {
            result.setSuccessful(true);
            PersonBaseInfo personBaseInfo = personBaseInfoService.findByIdNum(idnum);
            if(personBaseInfo != null && StringUtil.isNotEmpty(personBaseInfo.getImgPath())){
                result.setData(configUtils.getWebHost()+"/"+personBaseInfo.getImgPath());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setSuccessful(false);
            throw e;
        }
        return result;
    }
}
