package com.jeeplus.test.wdt.disposeRubbish.controller;

import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.service.dto.OfficeDTO;
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.LookOverService;
import com.jeeplus.test.garbageClearance.utils.SnowFlake;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.service.OssService;
import com.jeeplus.test.wdt.disposeRubbish.domain.DisposeRubbish;
import com.jeeplus.test.wdt.disposeRubbish.service.DisposeRubbishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * 清运处理
 * @author: 徐滕
 * @version: 2024-09-02 09:50
 */
@Api(tags ="清运处理")
@RestController
@RequestMapping(value = "/app/dispose/rubbish")
public class DisposeRubbishController {
    @Autowired
    private DisposeRubbishService disposeRubbishService;
    @Autowired
    private LookOverService overService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private OssService ossService;

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

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

        return ResponseEntity.ok ( post );
    }

    /**
     * 查询巡视工单
     *
     * @param procInsIds
     * @return
     */
    @GetMapping("getByProcInsId")
    public ResponseEntity getByProcInsId(String procInsIds) {
        // 转换为数组
        String[] array = procInsIds.split(",");
        // 再转换为集合（ArrayList）
        List<String> procInsIdList = Arrays.asList(array);
        // 还需要处理单位  清运专员  联系方式  及  附件信息
        List<DisposeRubbish> getByProcInsId = disposeRubbishService.getByProcInsId ( procInsIdList );
        return ResponseEntity.ok ( getByProcInsId );
    }

    /**
     * 保存巡视信息
     */
    @ApiLog("保存巡视信息")
    @ApiOperation(value = "保存巡视信息")
    @PostMapping("save")
    public  ResponseEntity <String> save(@Valid @RequestBody DisposeRubbish disposeRubbish) {
        synchronized (SYN_BYTE) {
            //新增或编辑表单保存
            if (StringUtils.isBlank(disposeRubbish.getId())) {

                // 获取第一条记录
                DisposeRubbish noDisposeRubbish = disposeRubbishService.selectOne();
                if (null != noDisposeRubbish) {
                    disposeRubbish.setYear(noDisposeRubbish.getYear());
                    Integer number = noDisposeRubbish.getNumber() + 1;
                    disposeRubbish.setNumber(number);
                    // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                    String formattedNo = number < 10000 ? String.format("%d%04d", noDisposeRubbish.getYear(), number) : String.format("%d%d", noDisposeRubbish.getYear(), number);
                    disposeRubbish.setNo(formattedNo);
                }else{
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    disposeRubbish.setYear(year);
                    Integer number = 1;
                    disposeRubbish.setNumber(number);
                    // 将年份和流水号拼接成 4 位数字的格式，不足 4 位补 0
                    String formattedNo = String.format("%d%04d", year, number);
                    disposeRubbish.setNo(formattedNo);
                }
            }
            if (disposeRubbish.getProgramIds().size() > 0) {
                String programIds = String.join(",", disposeRubbish.getProgramId());
                disposeRubbish.setProgramId(programIds);
            }


            disposeRubbishService.saveOrUpdate(disposeRubbish);


            //对过磅数据进行处理
            if (null != disposeRubbish.getFileList4() && disposeRubbish.getFileList4().size() > 0 ) {
                UserDTO userDTO = UserUtils.getCurrentUserDTO();
                // 进行附件保存操作，保存到work_attachment 表中
                for (WorkAttachment attachment : disposeRubbish.getFileList4()) {
                    // 生成id
                    String detailId = SnowFlake.getId();
                    attachment.setId(detailId);
                    attachment.setAttachmentId(disposeRubbish.getId());
                    attachment.setCreateTime(new Date());
                    attachment.setUpdateTime(new Date());
                    attachment.setDelFlag(0);
                    attachment.setAttachmentFlag("weigh");
                    ossService.insertWorkAttachment(attachment,userDTO);
                }
            }

            for (String workOverId : disposeRubbish.getProgramIds()) {
                LookOver lookOver = overService.getById(workOverId);
                //处理巡查单的状态信息，将巡查单的status调整为处理中
                if("2".equals(disposeRubbish.getStatus()) || "5".equals(disposeRubbish.getStatus())){
                    lookOver.setDisposeStatus(disposeRubbish.getStatus());
                }else{
                    lookOver.setDisposeStatus("1");
                }
                overService.updateDisposeStatus(lookOver);
            }

            if("5".equals(disposeRubbish.getStatus())){
                //处理完给村负责人发送短信通知
                try {
                    //根据手机号进行发送短信
                    //发送短信通知
                    ALiYunSmsUtil.transferInformSendSms(disposeRubbish.getClearUserMobile(),disposeRubbish.getNo());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseUtil.newInstance ( ).add("businessTable", "dispose_rubbish").add("businessId", disposeRubbish.getId()).ok ("保存成功");
    }

    /**
     * 查询最大的巡视工单
     */
    @ApiLog("查询最大的巡视工单")
    @ApiOperation(value = "查询最大的巡视工单")
    @GetMapping("getMaxNo")
    public ResponseEntity<String> getMaxNo() {
        String maxNo = disposeRubbishService.getMaxNo();
        return ResponseEntity.ok( maxNo );
    }

    /**
     * 查询最大的巡视工单
     */
    @ApiLog("查询垃圾站点")
    @ApiOperation(value = "查询垃圾站点")
    @GetMapping("getRubbishStation")
    public ResponseEntity<String> getRubbishStation() {
        //String maxNo = disposeRubbishService.getMaxNo();
        String rubbishStation = "头灶镇垃圾处理点";
        return ResponseEntity.ok( rubbishStation );
    }

    /**
     * 查询处理单位
     */
    @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> getUserInfo(String officeId ) {
        UserDTO userDTO = disposeRubbishService.getUserInfoByOffId(officeId);
        return ResponseEntity.ok( userDTO );
    }


    /**
     * 查询巡视工单
     *
     * @param programIds
     * @return
     */
    @GetMapping("getByWorkOverId")
    public ResponseEntity getByWorkOverId(String programIds) {
        // 转换为数组
        String[] array = programIds.split(",");
        // 再转换为集合（ArrayList）
        List<String> programIdList = Arrays.asList(array);
        // 还需要处理单位  清运专员  联系方式  及  附件信息
        List<WorkAttachment> workAttachmentList = disposeRubbishService.getByWorkOverId ( programIdList );
        return ResponseEntity.ok ( workAttachmentList );
    }
}
