package com.jeeplus.test.garbageClearance.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.notify.service.NotifyService;
import com.jeeplus.notify.service.dto.NotifyDTO;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.ALiYunSmsUtil;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.garbageClearance.domain.LookOver;
import com.jeeplus.test.garbageClearance.service.DTO.LookOverDTO;
import com.jeeplus.test.garbageClearance.service.LookOverService;
import com.jeeplus.test.garbageClearance.utils.SnowFlake;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.domain.WorkAttachmentInfo;
import com.jeeplus.test.oss.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/**
 * 巡视相关controller
 * @author 王强
 * @version 1.0
 * @date 2024-08-29 10:40
 */
@Api(tags ="巡视")
@RestController
@RequestMapping(value = "/app/look/over")
public class LookOverController {

    @Autowired
    private LookOverService overService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private OssService ossService;

    @Autowired
    private NotifyService notifyService;

    private static final byte[] SYN_BYTE = new byte[0];

    /**
     * 查询巡视工单
     *
     * @param id
     * @return
     */
    @GetMapping("queryById")
    public ResponseEntity queryById(String id) {
        // 还需要处理单位  清运专员  联系方式  及  附件信息
        LookOver post = overService.selectByID ( id );

        return ResponseEntity.ok ( post );
    }

    /**
     * 保存巡视信息
     */
    @ApiLog("保存巡视信息")
    @ApiOperation(value = "保存巡视信息")
    @PostMapping("save")
    public  ResponseEntity <String> save(@Valid @RequestBody LookOver lookOver) {
        synchronized (SYN_BYTE) {
            //新增或编辑表单保存
            UserDTO userDTO = UserUtils.getCurrentUserDTO();
            List<RoleDTO> roleDTOList = userDTO.getRoleDTOList();

            Boolean xzFlag = false;
            for (RoleDTO roleDTO : roleDTOList) {
                if("乡镇巡查员".equals(roleDTO.getName())){
                    xzFlag = true;
                    break;
                }
            }
            String formattedNo = "";
            LookOver noLookOver = overService.selectOne();
            Office office = officeService.getById(userDTO.getOfficeDTO().getId());
            if(StringUtils.isBlank(lookOver.getId())){
                lookOver.setOfficeCode(office.getCode());
            }
            if(xzFlag){
                if (StringUtils.isBlank(lookOver.getId())) {
                    if (null != noLookOver) {
                        lookOver.setYear(noLookOver.getYear());
                        Integer number = noLookOver.getNumber() + 1;
                        lookOver.setNumber(number);
                        // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                        formattedNo = number < 10000 ? String.format("%d%04d", noLookOver.getYear(), number) : String.format("%d%d", noLookOver.getYear(), number);

                    } else {
                        Calendar calendar = Calendar.getInstance();
                        int year = calendar.get(Calendar.YEAR);
                        lookOver.setYear(year);
                        Integer number = 1;
                        lookOver.setNumber(number);
                        // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                        formattedNo = String.format("%d%04d", year, number);
                    }
                    formattedNo = "Z-" + formattedNo;
                    lookOver.setNo(formattedNo);
                }
            }else {
                if (StringUtils.isBlank(lookOver.getId())) {
                    if (null != noLookOver) {
                        lookOver.setYear(noLookOver.getYear());
                        Integer number = noLookOver.getNumber() + 1;
                        lookOver.setNumber(number);
                        // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                        formattedNo = number < 10000 ? String.format("%s%d%04d", office.getCode(), noLookOver.getYear(), number) : String.format("%s%d%d", office.getCode(), noLookOver.getYear(), number);
                    } else {
                        Calendar calendar = Calendar.getInstance();
                        int year = calendar.get(Calendar.YEAR);
                        lookOver.setYear(year);
                        Integer number = 1;
                        lookOver.setNumber(number);
                        // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                        formattedNo = String.format("%s%d%04d", office.getCode(), year, number);
                    }
                    formattedNo = "XS-" + formattedNo;
                    lookOver.setNo(formattedNo);
                }
            }
            if("5".equals(lookOver.getStatus())){
                lookOver.setDisposeStatus("1");
            }
            overService.saveOrUpdate(lookOver);

            if (null != lookOver.getFileList1() && lookOver.getFileList1().size() > 0) {
                List<String> betweenUrlList = Lists.newArrayList();
                // 进行附件保存操作，保存到work_attachment 表中
                for (WorkAttachmentInfo attachment : lookOver.getFileList1()) {
                    if(attachment.getUrl().contains("/attachment-file")){
                        // 查找 "/attachment-file" 在字符串中的位置
                        int startIndex = attachment.getUrl().indexOf("/attachment-file");
                        // 查找 "?" 在字符串中的位置
                        int endIndex = attachment.getUrl().indexOf("?");
                        // 如果找到了 "/attachment-file" 和 "?"
                        if (startIndex != -1 && endIndex != -1) {
                            // 截取从 startIndex 到 endIndex 之间的字符串
                            String result = attachment.getUrl().substring(startIndex+1, endIndex);
                            betweenUrlList.add(result);
                        }
                    }
                }
                //查询除betweenUrlList以外的数据进行删除
                ossService.deleteByUrlListAndFlag(betweenUrlList,"between", lookOver.getId());
                for (WorkAttachmentInfo attachment : lookOver.getFileList1()) {
                    if(StringUtils.isNotBlank(attachment.getAttachmentName())){
                        // 生成id
                        String detailId = SnowFlake.getId();
                        attachment.setId(detailId);
                        attachment.setAttachmentId(lookOver.getId());
                        attachment.setCreateTime(new Date());
                        attachment.setUpdateTime(new Date());
                        attachment.setDelFlag(0);
                        attachment.setAttachmentFlag("before");
                        ossService.insertWorkAttachmentInfo(attachment,userDTO);
                    }
                }
            }

            //如果发起巡查流程，则给村支书发送短信通知
            if("2".equals(lookOver.getStatus())){
                // 发送通知给 当前用户人所在 村庄的 村庄负责人（村支书）
                UserDTO user = UserUtils.get(lookOver.getClearUserId());
                UserDTO dto = overService.getUserInfoByOffId(user.getOfficeDTO().getId());

                NotifyDTO notifyDTO = new NotifyDTO();
                notifyDTO.setContent(lookOver.getRemarks());
                notifyDTO.setNotifyRecordIds(dto.getId());
                notifyDTO.setStatus("1");
                notifyDTO.setType("2");
                notifyDTO.setTitle("垃圾清运通知");
                notifyDTO.setLookOverId(lookOver.getId());

                notifyService.saveOrUpdate(notifyDTO);

                //处理完给村负责人发送短信通知
                try {
                    //获取下一步处理人的手机号
                    String mobile = user.getMobile();
                    //根据手机号进行发送短信
                    //发送短信通知
                    ALiYunSmsUtil.tourInformSendSms(mobile,lookOver.getNo());
                    //ALiYunSmsUtil.tourInformSendSms(mobile,"XS-J" + lookOver.getNo());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseUtil.newInstance ( ).add("businessTable", "garbage_clearance_look_over").add("businessId", lookOver.getId()).ok ("保存成功");
    }

    /**
     * 保存巡视信息
     */
    @ApiLog("保存巡视信息处理中后的图片信息")
    @ApiOperation(value = "保存巡视信息处理中后的图片信息")
    @PostMapping("savePhoto")
    public  ResponseEntity <String> savePhoto(@Valid @RequestBody LookOver lookOver) {
        //新增或编辑表单保存
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> betweenUrlList = Lists.newArrayList();
        if (null != lookOver.getFileList2() && lookOver.getFileList2().size() > 0 ) {
            // 进行附件保存操作，保存到work_attachment 表中
            for (WorkAttachmentInfo attachment : lookOver.getFileList2()) {
                if(attachment.getUrl().contains("/attachment-file")){
                    // 查找 "/attachment-file" 在字符串中的位置
                    int startIndex = attachment.getUrl().indexOf("/attachment-file");
                    // 查找 "?" 在字符串中的位置
                    int endIndex = attachment.getUrl().indexOf("?");
                    // 如果找到了 "/attachment-file" 和 "?"
                    if (startIndex != -1 && endIndex != -1) {
                        // 截取从 startIndex 到 endIndex 之间的字符串
                        String result = attachment.getUrl().substring(startIndex+1, endIndex);
                        betweenUrlList.add(result);
                    }
                }
            }
            //查询除betweenUrlList以外的数据进行删除
            ossService.deleteByUrlListAndFlag(betweenUrlList,"between", lookOver.getId());
            for (WorkAttachmentInfo attachment : lookOver.getFileList2()) {
                if(StringUtils.isNotBlank(attachment.getAttachmentName())){
                    // 生成id
                    String detailId = SnowFlake.getId();
                    attachment.setId(detailId);
                    attachment.setAttachmentId(lookOver.getId());
                    attachment.setCreateTime(new Date());
                    attachment.setUpdateTime(new Date());
                    attachment.setDelFlag(0);
                    attachment.setAttachmentFlag("between");
                    ossService.insertWorkAttachmentInfo(attachment,userDTO);
                }
            }
        }


        if (null != lookOver.getFileList3() && lookOver.getFileList3().size() > 0 ) {
            List<String> afterUrlList = Lists.newArrayList();
            // 进行附件保存操作，保存到work_attachment 表中
            for (WorkAttachmentInfo attachment : lookOver.getFileList3()) {
                if (attachment.getUrl().contains("/attachment-file")) {
                    // 查找 "/attachment-file" 在字符串中的位置
                    int startIndex = attachment.getUrl().indexOf("/attachment-file");
                    // 查找 "?" 在字符串中的位置
                    int endIndex = attachment.getUrl().indexOf("?");
                    // 如果找到了 "/attachment-file" 和 "?"
                    if (startIndex != -1 && endIndex != -1) {
                        // 截取从 startIndex 到 endIndex 之间的字符串
                        String result = attachment.getUrl().substring(startIndex + 1, endIndex);
                        afterUrlList.add(result);
                    }
                }
            }
            //查询除afterUrlList以外的数据进行删除
            ossService.deleteByUrlListAndFlag(afterUrlList, "after", lookOver.getId());

            // 进行附件保存操作，保存到work_attachment 表中
            for (WorkAttachmentInfo attachment : lookOver.getFileList3()) {
                if(StringUtils.isNotBlank(attachment.getAttachmentName())) {
                    // 生成id
                    String detailId = SnowFlake.getId();
                    attachment.setId(detailId);
                    attachment.setAttachmentId(lookOver.getId());
                    attachment.setCreateTime(new Date());
                    attachment.setUpdateTime(new Date());
                    attachment.setDelFlag(0);
                    attachment.setAttachmentFlag("after");
                    ossService.insertWorkAttachmentInfo(attachment, userDTO);
                }
            }
        }
        return ResponseEntity.ok ( "保存成功" );
    }

    /**
     * 查询最大的巡视工单
     */
    @ApiLog("查询最大的巡视工单")
    @ApiOperation(value = "查询最大的巡视工单")
    @GetMapping("getMaxNo")
    public ResponseEntity<String> getMaxNo() {
        //获取当前人所属部门信息
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        List<RoleDTO> roleDTOList = currentUserDTO.getRoleDTOList();
        Boolean xzFlag = false;
        for (RoleDTO roleDTO : roleDTOList) {
            if("乡镇巡查员".equals(roleDTO.getName())){
                xzFlag = true;
                break;
            }
        }
        String formattedNo = "";
        LookOver noLookOver = overService.selectOne();
        if(xzFlag){
            if (null != noLookOver) {
                Integer number = noLookOver.getNumber() + 1;
                // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                formattedNo = number < 10000 ? String.format("%d%04d", noLookOver.getYear(), number) : String.format("%d%d", noLookOver.getYear(), number);
            }else{
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                Integer number = 1;
                // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                formattedNo = String.format("%d%04d", year, number);
            }
            formattedNo = "Z-" + formattedNo;
        }else{
            Office office = officeService.getById(currentUserDTO.getOfficeDTO().getId());
            if (null != noLookOver) {
                Integer number = noLookOver.getNumber() + 1;
                // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                formattedNo = number < 10000 ? String.format("%s%d%04d", office.getCode(), noLookOver.getYear(), number) : String.format("%s%d%d", office.getCode(), noLookOver.getYear(), number);
            }else{
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                Integer number = 1;
                // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                formattedNo = String.format("%s%d%04d", office.getCode(), year, number);
            }
            formattedNo = "XS-" + formattedNo;
        }

        return ResponseEntity.ok( formattedNo );
    }

    /**
     * 查询处理单位
     */
    @ApiLog("查询处理单位")
    @ApiOperation(value = "查询处理单位")
    @GetMapping("getProcessingUnit")
    public ResponseEntity<List<OfficeDTO>> getProcessingUnit() {
        List <OfficeDTO> list = officeService.findList ( "" );
        List <OfficeDTO> rootTree = officeService.getRootTree ( "", list, "", "", "1" );

        rootTree.forEach(ro -> {
            Iterator<OfficeDTO> iterator = ro.getChildren().iterator();
            while (iterator.hasNext()) {
                OfficeDTO ch = iterator.next();
                if (!ch.getName().contains("村")) {
                    iterator.remove();  // 使用迭代器删除子节点
                }
            }
        });

        return ResponseEntity.ok ( rootTree );
    }

    /**
     * 根据组织ID获取角色为村负责人的用户信息
     */
    @ApiLog("根据组织ID获取角色为村负责人的用户信息")
    @ApiOperation(value = "根据组织ID获取角色为村负责人的用户信息")
    @GetMapping("getUserInfoByOffId")
    public ResponseEntity<UserDTO> getUserInfoByOffId( String officeId ) {
        UserDTO userDTO = overService.getUserInfoByOffId(officeId);
        return ResponseEntity.ok( userDTO );
    }

    /**
     * 根据组织ID获取角色为村负责人的用户信息
     */
    @ApiLog("根据组织ID获取角色为村负责人的用户信息")
    @ApiOperation(value = "根据组织ID获取角色为村负责人的用户信息")
    @GetMapping("getOfficeOnHamlet")
    public ResponseEntity<List <UserDTO>> getOfficeOnHamlet( ) {
        List <UserDTO> list = overService.getOfficeOnHamlet ( );
        return ResponseEntity.ok( list );
    }

    /**
     * 查询未处理巡视单
     * @param lookOver
     * @param page
     * @return
     */
    @ApiLog("查询未处理巡视单")
    @GetMapping("getNotDisposeList")
    public ResponseEntity<IPage<LookOver>> getNotDisposeList(LookOverDTO lookOver, Page<LookOverDTO> page) throws Exception {
        IPage<LookOver> result = new Page<LookOver>();
        result = overService.getNotDisposeList (page,lookOver);
        return ResponseEntity.ok (result);
    }

    /**
     * 根据关联id和判定条件查询附件信息
     * @param attachmentId
     * @param attachmentFlag
     * @return
     */
    @ApiLog("根据关联id和判定条件查询附件信息")
    @GetMapping("getPhotoListByAttachmentAndFlag")
    public List<WorkAttachment> getPhotoListByAttachmentAndFlag(String attachmentId,String attachmentFlag){
        Set<String> set = new HashSet<>();
        String[] attachmentIds = attachmentId.split(",");
        for (String id : attachmentIds) {
            set.add(id);
        }
        List<String> attachmentIdList = new ArrayList<>(set);
        List<WorkAttachment> fileList = ossService.findFileList(attachmentIdList, attachmentFlag);
        return fileList;
    }

    /**
     * 根据关联id和判定条件查询附件信息
     * @param ids
     * @param attachmentFlag
     * @return
     */
    @ApiLog("根据关联id和判定条件查询附件信息")
    @GetMapping("getPhotoListByIdAndAttachmentFlag")
    public List<LookOver> getPhotoListByIdAndAttachmentFlag(String ids,String attachmentFlag){
        Set<String> set = new HashSet<>();
        String[] attachmentIds = ids.split(",");
        for (String id : attachmentIds) {
            set.add(id);
        }
        List<String> attachmentIdList = new ArrayList<>(set);
        List<LookOver> fileList = overService.getFileListByIdList(attachmentIdList, attachmentFlag);

        return fileList;
    }

}
