package org.dromara.system.controller;

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

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.system.domain.bo.SysDictDataBo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.service.ISysDictDataService;
import org.dromara.util.SPlatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.TblBagVo;
import org.dromara.system.domain.bo.TblBagBo;
import org.dromara.system.service.ITblBagService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 【请填写功能名称】
 *
 * @author Lion Li
 * @date 2025-09-06
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/upsystem/bag")
public class TblBagController extends BaseController {

    private final ITblBagService tblBagService;


    @GetMapping("/list")
    public TableDataInfo<TblBagVo> list(TblBagBo bo, PageQuery pageQuery) {
        return tblBagService.queryPageList(bo, pageQuery);
    }


    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TblBagBo bo, HttpServletResponse response) {
        List<TblBagVo> list = tblBagService.queryList(bo);
        ExcelUtil.exportExcel(list, "【请填写功能名称】", TblBagVo.class, response);
    }


    @GetMapping("/{id}")
    public R<TblBagVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(tblBagService.queryById(id));
    }


    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TblBagBo bo) {
        return toAjax(tblBagService.insertByBo(bo));
    }


    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TblBagBo bo) {
        return toAjax(tblBagService.updateByBo(bo));
    }


    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(tblBagService.deleteWithValidByIds(List.of(ids), true));
    }


    @PostMapping("/sysc/{ids}")
    public R<Void> sysc(@NotEmpty(message = "主键不能为空")
                            @PathVariable Long[] ids) {
        Map<String, JSONObject> cabinetMap2 = new HashMap<>();
        //获取所有快递柜的快递信息
        Map<String, JSONObject> cabinetMap = new HashMap<>();
        SysDictDataBo bo =new SysDictDataBo();
        bo.setDictType("tbl_sites");
        List<SysDictDataVo> list = SpringUtils.getBean(ISysDictDataService.class).selectDictDataList(bo);
        try {
            list.forEach(item->{
                if(StrUtil.isNotEmpty(item.getRemark())){
                    JSONArray jsonArray = JSONUtil.parseArray(item.getRemark());
                    jsonArray.forEach(item2->{
                        if(((JSONObject)item2).getStr("type").equals("cabinet")){
                            ((JSONObject) item2).put("location",item.getDictValue());
                            cabinetMap.put( item.getDictLabel(),(JSONObject)item2);
                            cabinetMap2.put(((JSONObject) item2).getStr("wdcode"),(JSONObject)item2);
                        }
                    });
                }
            });
        }catch (Exception e){

        }
        TblBagBo bo1 =new TblBagBo();
        bo1.getParams().put("remark","");



        if(cabinetMap!=null && cabinetMap.size()>0) {
            ThreadUtil.execAsync(()->{
                try {
                    List<JSONObject> cabinetList = new ArrayList<>();
                    cabinetMap.keySet().forEach(i->{
                        JSONObject c = cabinetMap.get(i);
                        if(c.getStr("location")!=null&&c.getStr("wdcode")!=null){
                            c.put("deviceId", c.getStr("code"));
                            c.put("stationId", c.getStr("wdcode"));
                            c.put("deviceType", "cabinet");
                            cabinetList.add(c);
                        }
                    } );

                    SPlatUtils.SysDevice(cabinetList);
                }catch (Exception e){
                }
            });
        }

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("remark","");
        queryWrapper.in("id", ids);
        List<TblBagVo> bagList =  tblBagService.queryList(queryWrapper);
        List<JSONObject> jsonObjectList1 = new ArrayList<>();
        List<TblBagVo> sysd = new ArrayList<>();
        if(bagList!=null && bagList.size()>0) {
            bagList.forEach(item->{
                if(cabinetMap2.containsKey(item.getDeviceId().toString())){
                    JSONObject json = new JSONObject();
                    json.put("deviceId" ,cabinetMap2.get(item.getDeviceId()).getStr("code"));
                    json.put("cpCode",item.getCpCode());
                    json.put("waybillNo",item.getWaybillNo());
                    json.put("scTime",item.getScTime());
                    json.put("scType",item.getScType());
                    jsonObjectList1.add(json);
                    sysd.add(item);
                }

            });

            SPlatUtils.pushExpressInfo(jsonObjectList1);
            if(sysd!=null && sysd.size()>0) {
                sysd.forEach(item -> {
                    item.setRemark("已同步");
                    TblBagBo item1 = new TblBagBo();
                    BeanUtils.copyProperties(item, item1);
                    SpringUtils.getBean(ITblBagService.class).updateByBo(item1);
                });
                return R.ok();
            }
        }
        return R.fail("同步失败");
    }
}
