package com.sptg.gateway.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.util.Base64DecodeMultipartFileUtils;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.estate.api.dto.ApplyUserDto;
import com.sptg.estate.api.entity.ApplyUser;
import com.sptg.estate.api.feigns.ApplyUserFeign;
import com.sptg.gateway.entity.ApplyUserApi;
import com.sptg.gateway.util.DataCheck;
import com.sptg.gateway.util.PojoToApi;
import com.sptg.permissions.api.entity.ApiLog;
import com.sptg.permissions.api.feigns.ApiDockingConfFeign;
import com.sptg.permissions.api.feigns.ConfFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
import com.sptg.permissions.api.feigns.SysApiLogFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * title: ApplyUserController
 * package: com.sptg.estate.biz.security
 * description: 申请住户列表管理控制器
 *
 *
 *
 */

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/app/applyUser")
public class ApplyUserController {

    private final OrgFeign orgFeign;
    private final ApplyUserFeign applyUserFeign;
    private final ConfFeign confFeign;
    private final FastFileStorageClient fastFileStorageClient;
    private final ApiDockingConfFeign apiDockingConfFeign;

    /**
     * 功能描述: 获取会员的申请认证的列表ApplyUser By  memberId
     * @param map {
     *            member_id     :   会员id
     *            pageNum       :   分页页数
     *            pageSize      :   分页大小
     *            check_states  :   0,1,2  逗号隔开，申请记录审核状态：0-待审核 1-审核通过 2-审核不通过
     *            org_id        :   机构授权org_id，机构id,
     *            token        :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     *
     *
     */
    @PostMapping(value = "/getAllApplyUserByMemberId")
    public Map<String,Object> getAllApplyUserByMemberId(@RequestBody Map<String,String> map){
        log.warn("============================APP通过会员ID获取认证列表(/app/applyUser/getAllApplyUserByMemberId)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String,Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取列表失败");
        String org_id = map.get("org_id");
        String check_states = map.get("check_states");
        String member_id = map.get("member_id");
        String pageNum = map.get("pageNum");
        String pageSize = map.get("pageSize");
        String token = map.get("token");
        String roomId = map.get("roomId");
        try {
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if(DataCheck.checkToken(hashMap, org_id, token,apiDockingConfFeign)){
                return hashMap;
            }
            if(StringUtils.isBlank(member_id)){
                hashMap.put("result_msg", "member_id不能为空");
                return hashMap;
            }
            if (StringUtils.isEmpty(pageNum)) {
                hashMap.put("result_msg", "分页页码不能为空");
                return hashMap;
            }
            if (StringUtils.isEmpty(pageSize)) {
                hashMap.put("result_msg", "分页大小不能为空");
                return hashMap;
            }
            ApplyUserDto applyUserDto = new ApplyUserDto();
            applyUserDto.setMemberId(Long.valueOf(member_id));
            if(StringUtils.isNotBlank(check_states)){
                //字符串数组
                String[] checkStateStr = check_states.split(",");
                //字符串数组转Long数组
                Long[] checkState = (Long[]) ConvertUtils.convert(checkStateStr,Long.class);
                applyUserDto.setCheckStates(checkState);
            }
            Page<ApplyUser> page = new Page<>();
            page.setCurrent(Integer.parseInt(pageNum));
            page.setSize(Integer.parseInt(pageSize));
            applyUserDto.setPage(page);
            if(null != roomId){
                applyUserDto.setRoomId(Long.valueOf(roomId));
            }
            Page<ApplyUser> applyUserPage = this.applyUserFeign.pagingByMemberId(applyUserDto);
            Long totalPageNum = (applyUserPage.getTotal() + applyUserPage.getSize() -1) / applyUserPage.getSize();
            List<ApplyUser> list = applyUserPage.getRecords();
            hashMap.put("result_code",1);
            List<ApplyUserApi> apis = new ArrayList<>();
            String fastDfsServer = this.confFeign.getFileServerHost();
            for(ApplyUser applyUser:list){
                if(StringUtils.isNotBlank(applyUser.getImageUri())){
                    applyUser.setImageUri(fastDfsServer+ applyUser.getImageUri());
                }
                if(StringUtils.isNotBlank(applyUser.getPassportImgUri())){
                    applyUser.setPassportImgUri(fastDfsServer + applyUser.getPassportImgUri());
                }
                if(StringUtils.isNotBlank(applyUser.getEntryImgUri())){
                    applyUser.setEntryImgUri(fastDfsServer + applyUser.getEntryImgUri());
                }
                apis.add(PojoToApi.applyUserToApi(applyUser));
            }
            hashMap.put("list",apis);
            hashMap.put("pages",totalPageNum);
            if(apis.size()==0){
                hashMap.put("result_msg", "没有查询到相关数据");
            }else{
                hashMap.put("result_msg", "查询数据成功");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

   /**
     * 功能描述: 获取会员的申请认证的列表ApplyUser By  RoomIds
     * @param map {
     *            room_ids     :   房间ids
     *            check_states  :   0,1,2  逗号隔开，申请记录审核状态：0-待审核 1-审核通过 2-审核不通过
     *            org_id        :   机构授权org_id，机构id,
     *            token        :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     *
     *
     */
    @PostMapping(value = "/getAllApplyUserByRoomIds")
    public Map<String,Object> getAllApplyUserByRoomIds(@RequestBody Map<String,Object> map){
        log.warn("============================APP通过房间IDs获取认证列表(/app/applyUser/getAllApplyUserByRoomIds)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String,Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取列表失败");
        String org_id = map.get("org_id").toString();
        String check_states = map.get("check_states").toString();
        List<String> room_ids = (List<String>) map.get("room_ids");
        String token = map.get("token").toString();
        String pageNum = (String) map.get("pageNum");
        String pageSize = (String) map.get("pageSize");
//        String roomId = map.get("roomId");
        try {
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if(DataCheck.checkToken(hashMap, org_id, token,apiDockingConfFeign)){
                return hashMap;
            }
            if(room_ids.size() == 0){
                hashMap.put("result_msg", "room_id不能为空");
                return hashMap;
            }
            if (StringUtils.isEmpty(pageNum)) {
                hashMap.put("result_msg", "分页页码不能为空");
                return hashMap;
            }
            if (StringUtils.isEmpty(pageSize)) {
                hashMap.put("result_msg", "分页大小不能为空");
                return hashMap;
            }

            ApplyUserDto applyUserDto = new ApplyUserDto();
            if(StringUtils.isNotBlank(check_states)){
                //字符串数组
                String[] checkStateStr = check_states.split(",");
                //字符串数组转Long数组
                Long[] checkState = (Long[]) ConvertUtils.convert(checkStateStr,Long.class);
                applyUserDto.setCheckStates(checkState);
            }
            List<ApplyUser> list = new ArrayList<>();
            room_ids.forEach(item ->{
                applyUserDto.setRoomId(Long.valueOf(item));
                applyUserDto.setPage(new Page<>(Integer.parseInt(pageNum),Integer.parseInt(pageSize)));
                Page<ApplyUser> page = this.applyUserFeign.pagingByRoomId(applyUserDto);
                List<ApplyUser> itemList = page.getRecords();
                list.addAll(itemList);
            });
//            List<ApplyUser> list = this.applyUserFeign.getAllApplyUserByRoomId(applyUserDto);
            hashMap.put("result_code",1);
            List<ApplyUserApi> apis = new ArrayList<>();
            String fastDfsServer = this.confFeign.getFileServerHost();
            for(ApplyUser applyUser:list){
                if(StringUtils.isNotBlank(applyUser.getImageUri())){
                    applyUser.setImageUri(fastDfsServer+ applyUser.getImageUri());
                }
                if(StringUtils.isNotBlank(applyUser.getPassportImgUri())){
                    applyUser.setPassportImgUri(fastDfsServer + applyUser.getPassportImgUri());
                }
                if(StringUtils.isNotBlank(applyUser.getEntryImgUri())){
                    applyUser.setEntryImgUri(fastDfsServer + applyUser.getEntryImgUri());
                }
                apis.add(PojoToApi.applyUserToApi(applyUser));
            }
            hashMap.put("list",apis);
            Long totalPageNum = (list.size() + Long.parseLong(pageSize) -1) / Long.parseLong(pageSize);
            hashMap.put("pages",totalPageNum);
            if(apis.size()==0){
                hashMap.put("result_msg", "没有查询到相关数据");
            }else{
                hashMap.put("result_msg", "查询数据成功");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 修改申请的住户记录（只能修改审核不通过的记录）
     * @param map {
     *            member_id             :   会员id
     *            org_id                :   机构授权org_id，机构id,
     *            token                 :   对接令牌
     *            apply_user_id         :   修改的记录id
     *            type                  :   住户类型,['业主','成员','租户'],
     *            id_card               :   身份证号，
     *            sex                   :   性别，
     *            nationality           :  国籍， 0 中国大陆 1 中国香港/澳门 2 中国台湾 3 海外
     *            image_uri             :  脸部照片url（没有域名）
     *            faceCode              :  根据图片生成的faceId--图片的md5
     *            passport_img_uri      :  护照照片url（没有域名，nationality = 3时,国籍为海外）
     *            entry_img_uri         :  入境证明url（没有域名，nationality = 3时,国籍为海外）
     *            tel                   :   电话，
     *            }
     * @return ResultBean<hashMap> 返回结果
     *
     *
     */
    @PostMapping(value = "/editApplyUser")
    public Map<String,Object> editApplyUser(@RequestBody Map<String,String> map){
        log.warn("============================APP编辑住户认证申请信息(/app/applyUser/editApplyUser)请求数据===============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String,Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "提交修改失败");
        String member_id = map.get("member_id");
        String org_id = map.get("org_id");
        String token = map.get("token");
        String apply_user_id = map.get("apply_user_id");
        String type = map.get("type");
        String nationality = map.get("nationality");
        String image_uri = map.get("image_uri");
        String face_code = map.get("face_code");
        String passport_img_uri = map.get("passport_img_uri");
        String entry_img_uri = map.get("entry_img_uri");
        String id_card = map.get("id_card");
        String sex = map.get("sex");
        String tel = map.get("tel");
        try {
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if(DataCheck.checkToken(hashMap, org_id, token,apiDockingConfFeign)){
                return hashMap;
            }
            if(StringUtils.isBlank(member_id)){
                hashMap.put("result_msg", "会员id不能为空");
                return hashMap;
            }
            if(StringUtils.isBlank(apply_user_id)){
                hashMap.put("result_msg", "apply_user_id不能为空");
                return hashMap;
            }
            if(StringUtils.isBlank(type)){
                hashMap.put("result_msg", "type不能为空");
                return hashMap;
            }
            if(Long.valueOf(type)==0 && StringUtils.isBlank(id_card)){
                hashMap.put("result_msg", "住户身份是业主时身份证不能为空");
                return hashMap;
            }
            if(StringUtils.isBlank(sex)){
                hashMap.put("result_msg", "住户性别（sex）不能为空");
                return hashMap;
            }
            if(StringUtils.isBlank(tel)){
                hashMap.put("result_msg", "电话（tel）不能为空");
                return hashMap;
            }
            ApplyUser oldApplyUser = this.applyUserFeign.getApplyUserById(Long.valueOf(apply_user_id));
            if(oldApplyUser==null){
                hashMap.put("result_msg", "提交修改的记录不存在");
                return hashMap;
            }
            //申请记录审核状态：0-待审核 1-审核通过 2-审核不通过
            if(oldApplyUser.getCheckState()!=2){
                hashMap.put("result_msg", "被修改的记录只能是审核不通过的记录");
                return hashMap;
            }
            if(!oldApplyUser.getMemberId().equals(Long.valueOf(member_id))){
                hashMap.put("result_msg", "该会员没有修改此记录的权限");
                return hashMap;
            }
            ApplyUser applyUser = new ApplyUser();
            applyUser.setId(oldApplyUser.getId());
            applyUser.setRecordType(OperationConstant.THREE);
            //修改状态---待审核状态
            applyUser.setCheckState(OperationConstant.ZERO);
            //住户类型
            if(!Integer.valueOf(type).equals(oldApplyUser.getType())){
                applyUser.setType(Integer.valueOf(type));
            }
            //身份证
            if(StringUtils.isNotBlank(id_card) && !id_card.equals(oldApplyUser.getIdCard())){
                applyUser.setIdCard(id_card);
            }
            //性别
            if(!Integer.valueOf(sex).equals(oldApplyUser.getSex())){
                applyUser.setSex(Integer.valueOf(sex));
            }
            //电话
            if(!tel.equals(oldApplyUser.getTel())){
                applyUser.setTel(tel);
            }
            //国际
            if(StringUtils.isNotBlank(nationality)){
                applyUser.setNationality(Integer.valueOf(nationality));
            }
            //人脸
            if(StringUtils.isNotBlank(image_uri) && StringUtils.isNotBlank(face_code)){
                applyUser.setImageUri(image_uri);
                applyUser.setFaceCode(face_code);
            }
            //护照
            if(StringUtils.isNotBlank(passport_img_uri)){
                applyUser.setPassportImgUri(passport_img_uri);
            }
            //护照
            if(StringUtils.isNotBlank(entry_img_uri)){
                applyUser.setEntryImgUri(entry_img_uri);
            }
            ResultBean<Boolean> resultBean = this.applyUserFeign.updateApplyUserById(applyUser);
            if(resultBean.getData()){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "提交修改成功，请等待物业审核");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: base64文件上传
     * @param map {
     *            base_64_str           :   文件的base64字符串
     *            is_need_md5           :   是否需要md5值
     *            org_id                :   机构授权org_id，机构id,
     *            token                 :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     *
     *
     */
    @PostMapping(value = "/uploadBase64File")
    public Map<String,Object> uploadBase64File(@RequestBody Map<String,String> map){
//        ApiLog apiLog = new ApiLog("/app/applyUser/uploadBase64File", "上传图片", JsonUtils.objectToJson(map), "app");
////        sysApiLogFeign.create(apiLog);

//        HashMap<Object, Object> mapTemp = new HashMap<>();
//        BeanUtil.copyProperties(map, mapTemp);
//        mapTemp.remove("base_64_str");
//        log.warn("============================APP上传图片(/app/applyUser/uploadBase64File)请求数据===============================");
//        log.warn(JsonUtils.objectToJson(mapTemp));

        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "文件上传失败");
        try {
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if(DataCheck.checkToken(hashMap, org_id, token,apiDockingConfFeign)){
                return hashMap;
            }
            String is_need_md5 = map.get("is_need_md5");
            if(StringUtils.isBlank(is_need_md5)){
                hashMap.put("result_msg", "is_need_md5不能为空");
                return hashMap;
            }
            String base_64_str = map.get("base_64_str");
            if(StringUtils.isBlank(base_64_str)){
                hashMap.put("result_msg", "base_64_str不能为空");
                return hashMap;
            }
            MultipartFile multipartFile  = Base64DecodeMultipartFileUtils.base64ToMultipart(base_64_str);
            /*
             * 返回的对象storePath
             *  storePath.fullPath = "group1/M00/00/00/wKgAYlvpNveAQ9jgAACQxvfzaOY198.jpg"
             *  storePath.group = "group1"
             *  storePath.path = "M00/00/00/wKgAYlvpNveAQ9jgAACQxvfzaOY198.jpg"
             */
            StorePath storePath = fastFileStorageClient.uploadFile(
                    multipartFile.getInputStream(),multipartFile.getSize(),
                    FilenameUtils.getExtension(multipartFile.getOriginalFilename()),null);
            if(storePath!=null){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "文件上传成功");
                hashMap.put("uri", storePath.getFullPath());
                hashMap.put("showUri", confFeign.getFileServerHost() + storePath.getFullPath());
                if(Boolean.valueOf(is_need_md5)){
                    String md5Hex = DigestUtils.md5Hex(multipartFile.getInputStream());
                    hashMap.put("md5Hex", md5Hex);
                }

//                ResultBean resultBean1 = DataCheck.uploadFace(base_64_str, new ApplyUser(), this.fastFileStorageClient, confFeign);
                ResultBean resultBean1 = null;
                if (resultBean1 != null){
                    hashMap.put("result_code", 0);
                    hashMap.put("result_msg", resultBean1.getMsg());
                }
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:审核
     * @param applyUser{
     *                 id : 1  记录id,
     *                 checkState : 1  审核状态,
     *                 checkOpinion :  审核意见--审核不通过时有值
     *          }
     * @return ModelAndView
     *
     *
     */
    @PostMapping("/updateCheckState")
//    @Security(token = EstateSecurityToken.APPLY_USER_AUDIT,format = DataFormatEnum.JSON)
    public Map<String, Object> updateCheckState(@RequestBody ApplyUser applyUser){
        log.warn("============================APP住户认证审核APP上传图片(/app/applyUser/updateCheckState)请求数据===============================");
        log.warn(JsonUtils.objectToJson(applyUser));
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "审核失败");
        //审核人类型：1-业主，2-后台
        applyUser.setOperatorType(OperationConstant.ONE);
        ResultBean<Boolean> resultBean = this.applyUserFeign.updateCheckState(applyUser);
        if(resultBean.getData()){
            hashMap.put("result_code", 1);
            hashMap.put("result_msg", "审核成功");
        }
        return hashMap;
    }

}
