package cn.api.atv.app;

import cn.facade.abs.IService;
import cn.common.annotation.Log;
import cn.common.enums.BizOpType;
import cn.common.enums.ResultCode;
import cn.common.page.response.Result;
import cn.constant.CommonConst;
import cn.orm.sqltoy.model.Page;
import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import cn.pojo.atv.*;
import cn.pojo.atv.vo.AtvBoardCardFaultDetails;
import cn.pojo.atv.vo.AtvBoardCardFaultPage;
import cn.pojo.entity.TSysUser;
import cn.service.atv.IAtvAppService;
import cn.service.atv.IAtvBoardCardFaultService;
import cn.util.core.IsKit;
import cn.util.core.TypeKit;

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

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * app端业务逻辑
 */
@RestController
@RequestMapping("/app/atvFault")
public class FaultCtrl extends IService {
    @Autowired
    protected IAtvAppService appService;
    @PostMapping(value = "/unable")
    @Log(title = "故障详情-无法处理提交", businessType = BizOpType.DELETE)
    public Result<?> faultUnable(
            @RequestParam(name = "boardCardFaultId") String boardCardFaultId,
            @RequestParam(name = "remarks") String remarks) {
        QueryWrapper<AtvBoardCardFault> queryWrapper = Wrappers.wrapper(AtvBoardCardFault.class)
                .eq("id", boardCardFaultId);
        AtvBoardCardFault atvBoardCardFault = daoService.findOne(queryWrapper);
        if (IsKit.isNull(atvBoardCardFault)) {
            return Result.warnMsg("无此故障单");
        }

        if (atvBoardCardFault.getFaultStatus() == 2 || //处理中
                atvBoardCardFault.getFaultStatus() == 1 ||//新报单
                atvBoardCardFault.getFaultStatus() == 4) //已派单
        {
            TSysUser sysUser = appService.getCurrentUser();
            atvBoardCardFault.setWorkerUserId(sysUser.getUserName());
            atvBoardCardFault.setWorkerUserName(sysUser.getNickName());
            atvBoardCardFault.setFaultStatus(3);//已上报
            daoService.update(atvBoardCardFault);

            AtvBoardCardFaultHandle atvBoardCardFaultHandle = new AtvBoardCardFaultHandle();
            atvBoardCardFaultHandle.setFaultStatus(3);
            atvBoardCardFaultHandle.setHandleUserId(sysUser.getUserName());
            atvBoardCardFaultHandle.setHandleUserName(sysUser.getNickName());
            atvBoardCardFaultHandle.setHandleUserPhone(sysUser.getPhonenumber());
            atvBoardCardFaultHandle.setRemarks(remarks);
            daoService.save(atvBoardCardFaultHandle);
            return Result.okMsg("添加成功！");
        } else {
            return Result.warnMsg("故障单状态不正确");
        }
    }

    @PostMapping(value = "/start")
    @Log(title = "故障详情-开始处理提交", businessType = BizOpType.DELETE)
    public Result<?> faultStart(@RequestBody JSONObject body) {
        String boardCardFaultId = body.getString("boardCardFaultId");
        String gps = body.getString("gps");
        QueryWrapper<AtvBoardCardFault> queryWrapper = Wrappers.wrapper(AtvBoardCardFault.class)
                .eq("id", boardCardFaultId);
        AtvBoardCardFault atvBoardCardFault = daoService.findOne(queryWrapper);
        if (IsKit.isNull(atvBoardCardFault)) {
            return Result.warnMsg("无此故障单");
        }
        if (atvBoardCardFault.getFaultStatus() == 1 ||
                atvBoardCardFault.getFaultStatus() == 4) {
            TSysUser sysUser = appService.getCurrentUser();
            atvBoardCardFault.setWorkerUserId(sysUser.getUserName());
            atvBoardCardFault.setWorkerUserName(sysUser.getNickName());
            atvBoardCardFault.setFaultStatus(2);
            daoService.update(atvBoardCardFault);

            AtvBoardCardFaultHandle atvBoardCardFaultHandle = new AtvBoardCardFaultHandle();
            atvBoardCardFaultHandle.setFaultStatus(2);
            atvBoardCardFaultHandle.setBoardCardFaultId(boardCardFaultId);
            atvBoardCardFaultHandle.setHandleUserId(sysUser.getUserName());
            atvBoardCardFaultHandle.setHandleUserName(sysUser.getNickName());
            atvBoardCardFaultHandle.setHandleUserPhone(sysUser.getPhonenumber());
            atvBoardCardFaultHandle.setGps(gps);
            daoService.save(atvBoardCardFaultHandle);
            return Result.okMsg("添加成功！");
        } else {
            return Result.warnMsg("故障单状态不正确");
        }
    }

    @GetMapping(value = "/queryById")
    @Log(title = "处理故障单详情查询接口-通过id查询", businessType = BizOpType.SELECT)
    public Result<?> faultQueryById(@RequestParam(name = "id") String id)
    {
        QueryWrapper<AtvBoardCardFault> queryWrapper = Wrappers.wrapper(AtvBoardCardFault.class)
                .eq("id", id);
        AtvBoardCardFault atvBoardCardFault = daoService.findOne(queryWrapper);

        if (IsKit.isNull(atvBoardCardFault)) {
            return Result.warnMsg("未找到对应数据");
        }
        if (atvBoardCardFault.getIsRead() == 0) {
            atvBoardCardFault.setIsRead(1);
            daoService.update(atvBoardCardFault);
        }

        AtvBoardCardFaultDetails atvBoardCardFaultDetails = new AtvBoardCardFaultDetails();
        BeanUtils.copyProperties(atvBoardCardFault, atvBoardCardFaultDetails);
        QueryWrapper<AtvLine> queryWrapper2 = Wrappers.wrapper(AtvLine.class)
                .eq("id", atvBoardCardFault.getLineId());
        AtvLine atvLine = daoService.findOne(queryWrapper2);
        if (IsKit.isNotNull(atvLine.getWorkers())) {
            String workers = atvLine.getWorkers();
            atvBoardCardFaultDetails.setWorkers(workers);
            atvBoardCardFaultDetails.setPhones(workers);
        }
        TSysUser sysUser = appService.getCurrentUser();
        atvBoardCardFaultDetails.getAtvBoardCardFaultFileList().addAll(
                this._selectByAfId_File(atvBoardCardFault.getId()));
        atvBoardCardFaultDetails.getAtvBoardCardFaultHandleList().addAll(
                this._selectByAfId_Handle(atvBoardCardFault.getId(), sysUser.getUserName()));
        atvBoardCardFaultDetails.getAtvBoardCardFaultAnalyseList().addAll(
                this._selectByAfId_Analyse(atvBoardCardFault.getId()));
        //原来的return Result.ok(new DictObject(atvBoardCardFaultDetails));
        // 国家
        QueryWrapper<AtvCountry> queryCountry = Wrappers.wrapper(AtvCountry.class);
        queryCountry.eq("id", atvBoardCardFaultDetails.getCountryId());
        atvBoardCardFaultDetails.setCountryId(atvBoardCardFaultDetails.getCountryId() + "_" + daoService.findOne(queryCountry).getName());

        // 区域
        QueryWrapper<AtvArea> queryArea = Wrappers.wrapper(AtvArea.class);
        queryArea.eq("id", atvBoardCardFaultDetails.getAreaId());
        atvBoardCardFaultDetails.setAreaId(atvBoardCardFaultDetails.getAreaId() + "_" + daoService.findOne(queryArea).getName());

        // 线路
        QueryWrapper<AtvLine> queryLine = Wrappers.wrapper(AtvLine.class);
        queryLine.eq("id", atvBoardCardFaultDetails.getLineId());
        atvBoardCardFaultDetails.setLineId(atvBoardCardFaultDetails.getLineId() + "_" + daoService.findOne(queryLine).getName());

        // 线路
        QueryWrapper<AtvTrain> queryTrain = Wrappers.wrapper(AtvTrain.class);
        queryTrain.eq("id", atvBoardCardFaultDetails.getTrainId());
        atvBoardCardFaultDetails.setTrainId(atvBoardCardFaultDetails.getTrainId() + "_" + daoService.findOne(queryTrain).getSysOrgCode());
        System.out.println("w--1:"+Result.ok(atvBoardCardFaultDetails));
        return Result.ok(atvBoardCardFaultDetails);
    }

    private List<AtvBoardCardFaultFile> _selectByAfId_File(String afId) {
        QueryWrapper<AtvBoardCardFaultFile> queryWrapper = Wrappers.wrapper(AtvBoardCardFaultFile.class)
                .eq("boardCardFaultId", afId);
        return daoService.findList(queryWrapper);
    }

    private List<AtvBoardCardFaultHandle> _selectByAfId_Handle(String afId, String userId) {
        QueryWrapper<AtvBoardCardFaultHandle> queryWrapper = Wrappers.wrapper(AtvBoardCardFaultHandle.class)
                .eq("boardCardFaultId", afId)
                .and(wrapper1 -> wrapper1.eq("handleUserId", userId)
                        .or().eq("sendUserId", userId))
                .orderByAsc("faultStatus")
                .orderByDesc("createTime");
        return daoService.findList(queryWrapper);
    }

    private List<AtvBoardCardFaultAnalyse> _selectByAfId_Analyse(String afId) {
        QueryWrapper<AtvBoardCardFaultAnalyse> queryWrapper = Wrappers.wrapper(AtvBoardCardFaultAnalyse.class)
                .eq("boardCardFaultId", afId);
        return daoService.findList(queryWrapper);
    }

    /**
     * 故障单完成处理操作
     *
     * @param atvBoardCardFaultDetails（包含故障单id,处理结果，处理措施，完成图片集合，故障分析单集合）
     */
    @PostMapping(value = "/completed")
    @Log(title = "故障详情-完成提交", businessType = BizOpType.DELETE)
    public Result<?> completed(@RequestBody AtvBoardCardFaultDetails atvBoardCardFaultDetails) {
        QueryWrapper<AtvBoardCardFault> queryWrapper = Wrappers.wrapper(AtvBoardCardFault.class)
                .eq("id", atvBoardCardFaultDetails.getId());
        AtvBoardCardFault atvBoardCardFault = daoService.findOne(queryWrapper);

        if (IsKit.isNull(atvBoardCardFault)) {
            return Result.warnMsg("无此故障单");
        }
        if (atvBoardCardFault.getFaultStatus() == 2) {
            //存入完成状态和处理结果和处理措施
            atvBoardCardFault.setFaultStatus(5);
            atvBoardCardFault.setHandleMode(atvBoardCardFaultDetails.getHandleMode());
            atvBoardCardFault.setHandleOutcome(atvBoardCardFaultDetails.getHandleOutcome());
            daoService.update(atvBoardCardFault);
            //存图片
            List<AtvBoardCardFaultFile> atvBoardCardFaultFileList = atvBoardCardFaultDetails.getAtvBoardCardFaultFileList();
            if (atvBoardCardFaultFileList.size() > 0) {
                for (AtvBoardCardFaultFile abcf : atvBoardCardFaultFileList) {
                    AtvBoardCardFaultFile atvBoardCardFaultFile = new AtvBoardCardFaultFile();
                    BeanUtils.copyProperties(abcf, atvBoardCardFaultFile);
                    atvBoardCardFaultFile.setBoardCardFaultId(atvBoardCardFaultDetails.getId());
                    atvBoardCardFaultFile.setFaultStatus(5);
                    daoService.save(atvBoardCardFaultFile);
                }
            }
            //存故障分析单
            List<AtvBoardCardFaultAnalyse> atvBoardCardFaultAnalyseList = atvBoardCardFaultDetails.getAtvBoardCardFaultAnalyseList();
            if (atvBoardCardFaultAnalyseList.size() > 0) {
                for (AtvBoardCardFaultAnalyse abcfa : atvBoardCardFaultAnalyseList) {
                    AtvBoardCardFaultAnalyse atvBoardCardFaultAnalyse = new AtvBoardCardFaultAnalyse();
                    BeanUtils.copyProperties(abcfa, atvBoardCardFaultAnalyse);

                    QueryWrapper<AtvCarriage> queryCountry = Wrappers.wrapper(AtvCarriage.class)
                            .eq("id", abcfa.getCarriageId());
                    AtvCarriage atvCarriage = daoService.findOne(queryCountry);
                    atvBoardCardFaultAnalyse.setCarriageSn(atvCarriage.getSn());

                    atvBoardCardFaultAnalyse.setBoardCardFaultId(atvBoardCardFaultDetails.getId());
                    daoService.save(atvBoardCardFaultAnalyse);
                }
            }
            List<AtvBoardCardFaultHandle> atvBoardCardFaultHandleList = atvBoardCardFaultDetails.getAtvBoardCardFaultHandleList();
            if (atvBoardCardFaultHandleList.size() > 0) {
                TSysUser sysUser = appService.getCurrentUser();
                //存故障处理单
                for (AtvBoardCardFaultHandle atvBoardCardFaultHandle : atvBoardCardFaultHandleList) {
                    atvBoardCardFaultHandle.setHandleUserName(sysUser.getNickName());
                    atvBoardCardFaultHandle.setHandleUserId(sysUser.getUserName());
                    atvBoardCardFaultHandle.setHandleUserPhone(sysUser.getPhonenumber());
                    atvBoardCardFaultHandle.setBoardCardFaultId(atvBoardCardFaultDetails.getId());
                    atvBoardCardFaultHandle.setFaultStatus(5);
                    daoService.save(atvBoardCardFaultHandle);
                }
            }
        } else {
            return Result.okMsg("状态不正确无法完成");
        }
        return Result.okMsg("操作成功");
    }

    @GetMapping(value = "/queryById1")
    //@Log(title = "上传故障单详情查询接口-通过id查询", businessType = BizOpType.DELETE)
    public Result<?> queryById1(@RequestParam(name = "id") String id) {
        QueryWrapper<AtvBoardCardFault> queryWrapper = Wrappers.wrapper(AtvBoardCardFault.class)
                .eq("id", id);
        AtvBoardCardFault atvBoardCardFault = daoService.findOne(queryWrapper);
        if (IsKit.isNull(atvBoardCardFault)) {
            return Result.warnMsg("未找到对应数据");
        }
        // 国家
        QueryWrapper<AtvCountry> queryCountry = Wrappers.wrapper(AtvCountry.class);
        queryCountry.eq("id", atvBoardCardFault.getCountryId());
        atvBoardCardFault.setCountryId(atvBoardCardFault.getCountryId() + "_" + daoService.findOne(queryCountry).getName());

        // 区域
        QueryWrapper<AtvArea> queryArea = Wrappers.wrapper(AtvArea.class);
        queryArea.eq("id", atvBoardCardFault.getAreaId());
        atvBoardCardFault.setAreaId(atvBoardCardFault.getAreaId() + "_" + daoService.findOne(queryArea).getName());

        // 线路
        QueryWrapper<AtvLine> queryLine = Wrappers.wrapper(AtvLine.class);
        queryLine.eq("id", atvBoardCardFault.getLineId());
        AtvLine atvLine = daoService.findOne(queryLine);
        atvBoardCardFault.setLineId(atvBoardCardFault.getLineId() + "_" + atvLine.getName());

        // 线路
        QueryWrapper<AtvTrain> queryTrain = Wrappers.wrapper(AtvTrain.class);
        queryTrain.eq("id", atvBoardCardFault.getTrainId());
        atvBoardCardFault.setTrainId(atvBoardCardFault.getTrainId() + "_" + daoService.findOne(queryTrain).getSysOrgCode());

        AtvBoardCardFaultDetails atvBoardCardFaultDetails = new AtvBoardCardFaultDetails();
        BeanUtils.copyProperties(atvBoardCardFault, atvBoardCardFaultDetails);

        if (IsKit.isNotNull(atvLine.getWorkers())) {
            String workers = atvLine.getWorkers();
            atvBoardCardFaultDetails.setWorkers(workers);
            atvBoardCardFaultDetails.setPhones(workers);
        }
        atvBoardCardFaultDetails.getAtvBoardCardFaultFileList().addAll(
                this._selectByAfId_File(atvBoardCardFault.getId()));
        atvBoardCardFaultDetails.getAtvBoardCardFaultHandleList().addAll(
                this._selectByAfId1(atvBoardCardFault.getId()));
        atvBoardCardFaultDetails.getAtvBoardCardFaultAnalyseList().addAll(
                this._selectByAfId_Analyse(atvBoardCardFault.getId()));
        //return Result.ok(new DictObject(atvBoardCardFaultDetails));
        return Result.ok(atvBoardCardFaultDetails);
    }

    private List<AtvBoardCardFaultHandle> _selectByAfId1(String afId) {
        QueryWrapper<AtvBoardCardFaultHandle> queryWrapper = Wrappers.wrapper(AtvBoardCardFaultHandle.class)
                .eq("boardCardFaultId", afId)
                .orderByAsc("faultStatus")
                .orderByDesc("createTime");
        return daoService.findList(queryWrapper);
    }

    @PostMapping(value = "/add")
    @Log(title = "板卡故障表-添加", businessType = BizOpType.DELETE)
    public Result<?> add(@RequestBody AtvBoardCardFaultPage atvBoardCardFaultPage) {
        System.out.println("w-1:" + atvBoardCardFaultPage);
        TSysUser sysUser = appService.getCurrentUser();
        System.out.println("w-2:" + sysUser);
        AtvBoardCardFault atvBoardCardFault = new AtvBoardCardFault();
        BeanUtils.copyProperties(atvBoardCardFaultPage, atvBoardCardFault);
        atvBoardCardFault.setSubmitUserId(sysUser.getUserName());
        atvBoardCardFault.setSubmitUserName(sysUser.getNickName());

        atvBoardCardFault.setFaultStatus(CommonConst.INT_NUM_1);
        atvBoardCardFault.setFaultSource(CommonConst.INT_NUM_1);
        iAtvBoardCardFaultService.saveMain(atvBoardCardFault, atvBoardCardFaultPage.getAtvBoardCardFaultFileList());

        return Result.okMsg("添加成功！");
    }

    /**status 对应app页面上的不同按钮选项（不同条件的）*/
    @GetMapping(value = "/dealList")
    @Log(title = "处理故障列表查询", businessType = BizOpType.SELECT)
    public Result<?> dealList(
            @RequestParam(name = "status", defaultValue = "0") Integer status,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize)
    {
        TSysUser sysUser = appService.getCurrentUser();
        String userName = sysUser.getUserName();
        //获取当前用户所负责的线路ID
        QueryWrapper<AtvLine> queryWrapper = Wrappers.wrapper(AtvLine.class)
                .select("id")
                .like("workers", userName);
        List<AtvLine> atvLine = daoService.findList(queryWrapper);
        List<String> atvLineIds = new ArrayList<>();
        for (AtvLine entity : atvLine) {
            String value = entity.getId();
            if (IsKit.isNotNullOrEmpty(value)) {
                atvLineIds.add(value);
            }
        }
        //app需要调试此返回值
        if (IsKit.isNullOrEmpty(atvLineIds)) {
            return Result.warnMsg("出错了");
        }
        System.out.println("dealList-4:");
        //获取故障详细信息
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", userName);
        paramMap.put("atvLineIds", atvLineIds);
        paramMap.put("pageNo", pageNo);
        paramMap.put("pageSize", pageSize);
        Page<?> pageResult = daoService.getPageBySql("atv_getDetailList4BoardCardFault", paramMap);
        if (IsKit.isNullOrEmpty(pageResult)) {
            return Result.warnMsg(ResultCode.SQL_RUN.getMsg());
        }
        List<Map<String, Object>> resultList = TypeKit.cast(pageResult.getRows());

        if (IsKit.isNullOrEmpty(resultList)) {
            return Result.warnMsg(ResultCode.SQL_RUN.getMsg());
        }
        for(int i = 0; i < resultList.size(); i++) {
            Map<String, Object> atvBoardCardFault = resultList.get(i);
            // 国家
            QueryWrapper<AtvCountry> queryCountry = Wrappers.wrapper(AtvCountry.class);
            queryCountry.eq("id", atvBoardCardFault.get("countryId"));
            atvBoardCardFault.put("countryId", atvBoardCardFault.get("countryId") + "_" + daoService.findOne(queryCountry).getName());

            // 区域
            QueryWrapper<AtvArea> queryArea = Wrappers.wrapper(AtvArea.class);
            queryArea.eq("id", atvBoardCardFault.get("areaId"));
            atvBoardCardFault.put("areaId", atvBoardCardFault.get("areaId") + "_" + daoService.findOne(queryArea).getName());

            // 线路
            QueryWrapper<AtvLine> queryLine = Wrappers.wrapper(AtvLine.class);
            queryLine.eq("id", atvBoardCardFault.get("lineId"));
            atvBoardCardFault.put("lineId", atvBoardCardFault.get("lineId") + "_" + daoService.findOne(queryLine).getName());

            // 线路
            QueryWrapper<AtvTrain> queryTrain = Wrappers.wrapper(AtvTrain.class);
            queryTrain.eq("id", atvBoardCardFault.get("trainId"));
            atvBoardCardFault.put("trainId", atvBoardCardFault.get("trainId") + "_" + daoService.findOne(queryTrain).getSysOrgCode());
        }
        for (Map<String, Object> ab : resultList) {
            QueryWrapper<AtvBoardCardFaultHandle> queryWrapper2 = Wrappers.wrapper(AtvBoardCardFaultHandle.class)
                    .eq("boardCardFaultId", ab.get("id"))
                    .eq("sendUserId", userName)
                    .eq("faultStatus", status);
            List<AtvBoardCardFaultHandle> list = daoService.findList(queryWrapper2);
            if (list.size() > 0) {
                ab.put("is_send", 1);//ab.setIsSend(true);
            } else {
                ab.put("is_send", 0);//ab.setIsSend(false);
            }
        }
        return Result.ok_ePlus(pageResult.getRecordCount(), resultList);
    }

    @GetMapping(value = "/myList")
    @Log(title = "上报故障列表查询", businessType = BizOpType.DELETE)
    public Result<?> faultMyList(@RequestParam Map<String, Object> pageMap) {
        Result<Map<String,Object>> rs = (Result<Map<String,Object>>)appService.queryMyFaultList(pageMap);
        List<AtvBoardCardFault> list = (List<AtvBoardCardFault>)rs.getData().get("records");
        for(int i = 0 ; i < list.size(); i++) {
            AtvBoardCardFault atvBoardCardFault = (AtvBoardCardFault)list.get(i);
            // 国家
            QueryWrapper<AtvCountry> queryCountry = Wrappers.wrapper(AtvCountry.class);
            queryCountry.eq("id", atvBoardCardFault.getCountryId());
            atvBoardCardFault.setCountryId(atvBoardCardFault.getCountryId() + "_" + daoService.findOne(queryCountry).getName());

            // 区域
            QueryWrapper<AtvArea> queryArea = Wrappers.wrapper(AtvArea.class);
            queryArea.eq("id", atvBoardCardFault.getAreaId());
            atvBoardCardFault.setAreaId(atvBoardCardFault.getAreaId() + "_" + daoService.findOne(queryArea).getName());

            // 线路
            QueryWrapper<AtvLine> queryLine = Wrappers.wrapper(AtvLine.class);
            queryLine.eq("id", atvBoardCardFault.getLineId());
            AtvLine atvLine = daoService.findOne(queryLine);
            atvBoardCardFault.setLineId(atvBoardCardFault.getLineId() + "_" + atvLine.getName());

            // 线路
            QueryWrapper<AtvTrain> queryTrain = Wrappers.wrapper(AtvTrain.class);
            queryTrain.eq("id", atvBoardCardFault.getTrainId());
            atvBoardCardFault.setTrainId(atvBoardCardFault.getTrainId() + "_" + daoService.findOne(queryTrain).getSysOrgCode());
        }

        return rs;
    }

    @Autowired
    private IAtvBoardCardFaultService iAtvBoardCardFaultService;
}
