package com.sptg.gateway.controller;

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.beans.ResultEnum;
import com.sptg.common.core.constant.SysLogConstant;
import com.sptg.common.core.util.Base64DecodeMultipartFileUtils;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.common.core.util.WebUtils;
import com.sptg.estate.api.dto.EstateRepairDto;
import com.sptg.estate.api.entity.EstateRepair;
import com.sptg.estate.api.entity.Member;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.feigns.EstateRepairFeign;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.gateway.util.DataCheck;
import com.sptg.permissions.api.entity.ApiLog;
import com.sptg.permissions.api.feigns.ConfFeign;
import com.sptg.permissions.api.feigns.SysApiLogFeign;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import com.sptg.third.api.feigns.grid.GridEstateFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * title: EstateRepairController
 * package: com.sptg.estate.biz.security
 * description: 物业报修管理控制器
 *
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/app/estateRepair")
public class EstateRepairController {

    private final EstateRepairFeign estateRepairFeign;
    private final ResidentialFeign residentialFeign;
    private final FastFileStorageClient fastFileStorageClient;
    private final ConfFeign confFeign;
    private final GridEstateFeign gridEstateFeign;

    @PostMapping(value = "/estateRepairList")
    private Map<String,Object> getEstateRepairList(@RequestBody EstateRepairDto estateRepairDto){
        Map<String,Object> map = new HashMap<>();
//        EstateRepairDto
        ResultBean<Page<EstateRepair>> pageResultBean = this.estateRepairFeign.showEstateRepairList(estateRepairDto);
        if(pageResultBean != null){
            map.put("estateRepairList",pageResultBean.getData());
        }
        return map;
    }

    @PostMapping(value = "/addEstateRepair")
    private Map<String,Object> addEstateRepair(@RequestBody EstateRepairDto estateRepairDto){
        log.warn("============================APP新增物业报修请求数据===============================");
        log.warn(JsonUtils.objectToJson(estateRepairDto));
        String fastDfsServer = this.confFeign.getFileServerHost();
        Map<String,Object> map = new HashMap<>();
        estateRepairDto.setRepairNo(generateRepairNO());
        Long residentialId = estateRepairDto.getResidentialId();
        Residential residentialById = residentialFeign.findResidentialById(residentialId);
        if(residentialById != null){
            estateRepairDto.setOrgPosition(residentialById.getOrgPosition());
            String image_base64 = estateRepairDto.getPic();
            estateRepairDto.setPic(null);
            try {
                if (StringUtils.isNotBlank(image_base64)&&!image_base64.equals("[]")){
                    List<String> image_base64List = Arrays.asList(image_base64);
                    if(image_base64List != null){
                        for (String imgBase64 : image_base64List){
                            String imgUrl = uploadImage(imgBase64, this.fastFileStorageClient);
                            String pic = estateRepairDto.getPic();
                            if(pic == null){
                                estateRepairDto.setPic(fastDfsServer + imgUrl);
                            }else{
                                estateRepairDto.setPic(pic + "," + (fastDfsServer + imgUrl));
                            }
                        }
                    }
                }
            } catch (IOException e) {
                log.error("异常", e);
                map.put("add_result", "上传图片失败");
            }
            ResultBean<EstateRepair> booleanResultBean = this.estateRepairFeign.addOrEditEstateRepair(estateRepairDto);

            if(booleanResultBean != null){
                map.put("add_result",booleanResultBean.getData()!=null?true:false);

                /*---------------------------------------------------推送物业报修到网格--------------------------------------------------------*/
                ResultBean<String> stringResultBean = this.gridEstateFeign.gridEstateRepairPush(booleanResultBean.getData());
                if(stringResultBean.getData().equals("操作成功")){
                    log.warn("============================小程序物业报修推送网格成功==============================");
                    log.warn(JsonUtils.objectToJson(estateRepairDto));
                }else{
                    log.warn("============================物业报修推送网格失败==============================");
                    log.warn(JsonUtils.objectToJson(booleanResultBean.getData()));
                }
            }else{
                map.put("add_result", "后台程序异常");
            }

        }else{
            map.put("add_result", "小区不存在");
        }
        return map;
    }

    @PostMapping(value = "/estateRepairDetail")
    public Map<String,Object> estateDetail(@RequestBody EstateRepair estateRepair1){
        Map<String,Object> map = new HashMap<>();
        ResultBean<EstateRepair> estateRepairById = this.estateRepairFeign.findEstateRepairById(estateRepair1.getId());
        if(estateRepairById != null){
            EstateRepair estateRepair = estateRepairById.getData();
            map.put("estateRepairDetail",estateRepair);
        }else{
            map.put("estateRepairDetail", "报修记录不存在");
        }

        return map;
    }



    private static final AtomicInteger SEQ = new AtomicInteger();
    private static final DateTimeFormatter DF_FMT_PREFIX = DateTimeFormatter.ofPattern("yyMMddHHmmssSS");
    private static ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");

    public static String generateRepairNO(){
        LocalDateTime dateTime = LocalDateTime.now(ZONE_ID);
        if(SEQ.intValue()>9990){
            SEQ.getAndSet(1000);
        }

        return dateTime.format(DF_FMT_PREFIX)+SEQ.getAndIncrement();
    }

    //上传头像
    public static String uploadImage(String face_image_base64, FastFileStorageClient fastFileStorageClient) throws IOException {
        if(StringUtils.isNotBlank(face_image_base64)){
            MultipartFile multipartFile  = Base64DecodeMultipartFileUtils.base64ToMultipart(Base64DecodeMultipartFileUtils.imageFormatToPng(face_image_base64));
            //图片上传
            StorePath storePath = fastFileStorageClient.uploadFile(
                    multipartFile.getInputStream(),multipartFile.getSize(),
                    FilenameUtils.getExtension(multipartFile.getOriginalFilename()),null);
            return storePath.getFullPath();
        }else{
            return null;
        }
    }
}
