package com.tofly.feesapi.flowdb;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.bmgl.entity.BmCbb;
import com.tofly.feesapi.bmgl.service.BmCbbService;
import com.tofly.feesapi.cbgl.entity.YyCblr;
import com.tofly.feesapi.cbgl.service.YyCblrService;
import com.tofly.feesapi.common.BaseController;
import com.tofly.feesapi.common.constant.CbbzEnum;
import com.tofly.feesapi.common.constant.JsbzEnum;
import com.tofly.feesapi.common.constant.ShbzEnum;
import com.tofly.feesapi.common.core.ResultRespone;
import com.tofly.feesapi.common.util.ToolsUtils;
import com.tofly.feesapi.flowdb.entity.WflowPushJson;
import com.tofly.feesapi.flowdb.entity.dto.FlowDto;
import com.tofly.feesapi.flowdb.entity.vo.FlowComponentVo;
import com.tofly.feesapi.flowdb.mapper.FlowMapper;
import com.tofly.feesapi.flowdb.service.IFlowService;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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 java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Author  Administrator
 *
 * @Date 2025-08-14 14:06 （创建时间）
 * @Version 1.0 （版本号）
 */
@RestController
@AllArgsConstructor
@RequestMapping("/api/common/flow")
@Api(tags = "流程")
@Slf4j
public class FlowController extends BaseController {

    @Autowired
    private FlowMapper flowMapper;
    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YhCbkxxService cbkxxService;
    @Autowired
    private BmCbbService bmCbbService;
    @Autowired
    private IFlowService iFlowService;
    @Autowired
    private YyCblrService cblrService;


    /**
     * 获取所有抄表员数据
     */
    @PostMapping("/sendflowids")
    @ApiOperation(value = "报装流程推送")
    public ResultRespone<List<String>> Sendflowids(@RequestBody FlowDto flowDto) {
        List<WflowPushJson> dataList = flowMapper.getWfFlow(flowDto.getIds());
        if (CollUtil.isEmpty(dataList)) {
            return ResultRespone.success(new ArrayList<>());
        }

        List<BmCbb> bmCbbs = bmCbbService.list();

        List<String> suceesIds = new ArrayList<>();
        List<String> failedIds = new ArrayList<>();

        for (WflowPushJson wflowPushJson : dataList) {
            String pushJson = wflowPushJson.getPushJson().replace("\\", "");
            String extendJson = wflowPushJson.getExtendJson().replace("\\", "");
            List<FlowComponentVo> flowVo = JSONObject.parseArray(pushJson, FlowComponentVo.class);
            List<FlowComponentVo> extendVo = null;
            if (StringUtils.isNotEmpty(extendJson)) {
                extendVo = JSONObject.parseArray(extendJson, FlowComponentVo.class);
            }

            boolean isCreate = createInfo(flowVo, extendVo, bmCbbs);
            if (isCreate) {
                flowMapper.updateById(wflowPushJson.getId(), "2");
                suceesIds.add(wflowPushJson.getId());
            } else {
                flowMapper.updateById(wflowPushJson.getId(), "3");
                failedIds.add(wflowPushJson.getId());
            }
        }
        log.warn("报装信息推送失败列表 =================> {}", failedIds);
        return ResultRespone.success(suceesIds);
    }


    /**
     * 创建用户信息
     * @return
     */
    @Transactional
    public boolean createInfo(List<FlowComponentVo>  flowVo ,List<FlowComponentVo> extendVo ,List<BmCbb> cbb){
        YhKhjbxx khjbxx=new YhKhjbxx();
        YhCbkxx yhCbkxx=new YhCbkxx();
        YyCblr cblr=new YyCblr();
        Map<String,FlowComponentVo> componentVoMap=flowVo.stream().collect(Collectors.toMap(FlowComponentVo::getKey, vo->vo));

        String yhbh= StringUtil.EMPTY;
        if(!StringUtil.isNull(componentVoMap.get("yhbh"))){
            khjbxx.setYhbh(componentVoMap.get("yhbh").getValue());
            khjbxx.setSscbb("DH006");
            khjbxx.setYhxm(componentVoMap.get("yhxm").getValue());
            khjbxx.setSscbpq("1");
            khjbxx.setSsgs("1");
            if (khjbxx.getYhbh().toUpperCase().contains("D"))
                khjbxx.setDxh(0);
            else
                khjbxx.setDxh(1);

            khjbxx.setJdrq(new Date());
            if(!StringUtil.isEmpty(khjbxx.getYhxm())) {
                khjbxx.setPyjm(ToolsUtils.getFirstLetters(khjbxx.getYhxm()));
            }
        }      yhCbkxx.setYhbh(khjbxx.getYhbh());
        yhCbkxx.setCbkh("1");
        yhCbkxx.setCbkid(khjbxx.getYhbh()+"1");
        if(!StringUtil.isNull(componentVoMap.get("bjbh"))){
            yhCbkxx.setSbbh(componentVoMap.get("bjbh").getValue());
        }
        yhCbkxx.setJfzt("1");
        yhCbkxx.setCbpl("5");
        yhCbkxx.setSjbm("1");
        yhCbkxx.setSblb("1");
        yhCbkxx.setSbsccj("1");
        yhCbkxx.setSbkj("1");
        yhCbkxx.setSblc("1");
        if(!StringUtil.isNull(extendVo)){
             //if(com)
            Map<String,FlowComponentVo> componentExptMap=extendVo.stream().collect(Collectors.toMap(FlowComponentVo::getKey, vo->vo));
            String yhzt=getJsonValue(componentExptMap,"yhzt"); //获取用户状态
        }

        //设置抄表录入
        BeanUtil.copyProperties(khjbxx,cblr);
        BeanUtil.copyProperties(yhCbkxx,cblr);
        cblr.setScds(BigDecimal.ZERO);
        cblr.setBcds(BigDecimal.ZERO);
        cblr.setCbbz(CbbzEnum.未抄表);
        cblr.setShbz(ShbzEnum.未审核);
        cblr.setJsbz(JsbzEnum.未算费);
        cblr.setCblx("0");
        cblr.setJfzt("1");

       YhKhjbxx jbxx=yhKhjbxxService.lambdaQuery().eq(YhKhjbxx::getYhbh,khjbxx.getYhbh()).one();
        if(!StringUtil.isNull(jbxx)){
            return  false;
        }

        /**
         * 保存成功
         */
         if(yhKhjbxxService.save(khjbxx)&&cbkxxService.save(yhCbkxx)&&cblrService.save(cblr)){
             return  true;
         }
         return  false;
    }
    private  String getJsonValue(Map<String,FlowComponentVo> componentExptMap,String kye){
        if(componentExptMap.containsKey(kye)) {
            String values = componentExptMap.get(kye).getValue().toString();
            if (StringUtils.isNotEmpty(values) && values.contains("{")) {
                FlowComponentVo vo = JSONObject.parseObject(values, FlowComponentVo.class);
                return vo.getValue();
            } else {
                return values;
            }
        }else {
            return  "";
        }
    }

}
