package com.chinaweal.aiccs.aiccs.abnormal.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.dto.PYRequestDTO;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AicodsClueDto;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 拟列异主体表 前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-07-30
 */
@RestController
@RequestMapping("/toincludeabn")
public class ToincludeabnController extends BaseController {

    @Value("${forest.variables.gzAicodsDownload}")
    private String downLoadPath;
    @Autowired
    private ToincludeabnService toincludeabnService;
    @Autowired
    private TSBizSpeListService tsBizSpeListService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSAttachmentService tsAttachmentService;
    @Autowired
    private TSAbnListService tsAbnListService;

    // 供双随机检查结果数据推送接口
    @PostMapping("saveClue_SSJ")
    public RestResult<?> saveClue(AicodsClueDto clueDto, String files) {
        AssertUtils.isNotNull(clueDto);
        String type = clueDto.getType();
        String dataFromId = clueDto.getDataFromId();
        if (StringUtils.isEmpty(type)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "type为空");
        }
        if (StringUtils.isEmpty(dataFromId)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "数据主键为空");
        }
        if ("save".equals(type)) {
            // 保存线索
            String regno = clueDto.getRegno();
            String includeType = clueDto.getIncludeType();
            String regEntryUserId = clueDto.getRegEntryUserId();
            String regEntryUserName = clueDto.getRegEntryUserName();
            String entOrgDer = clueDto.getEntOrgDer();
            String inspectobjid = clueDto.getPripid(); // 检查对象id

            // 判断是否需要保存
            LambdaQueryWrapper toincludeabnWrapper = new LambdaQueryWrapper<Toincludeabn>()
                    .eq(Toincludeabn::getInspectobjid, inspectobjid).eq(Toincludeabn::getIncludeType, includeType)
                    .in(Toincludeabn::getState, new String[]{"0", "1"}) // 未发起线索或审核审批线索
                    .eq(Toincludeabn::getDataState, "0"); // 正常状态
            List<Toincludeabn> toincludeabns = toincludeabnService.list(toincludeabnWrapper);
            if (toincludeabns.size() > 0) {
                return RestResult.ok(true);
            }

            AssertUtils.isNotEmpty(regno, dataFromId, includeType);
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isUscc(regno)) {
                wrapper.eq(EBaseinfo::getUniscid, regno);
            } else {
                wrapper.eq(EBaseinfo::getRegno, regno);
            }
            wrapper.eq(EBaseinfo::getRegstate, "1");
            EBaseinfo one = eBaseinfoService.getOne(wrapper);
            if (one == null) {
                return RestResult.error(ResultCode.DATA_NONE, "注册号参数有误，找不到主体");
            }
            String pripid = one.getPripid();
            String uniscid = one.getUniscid();

            //地址的，列异中和已列异不生成线索
            if ("4".equals(includeType)) {
                LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
                abnWrapper.eq(TSAbnList::getPripid, pripid)
                        .eq(TSAbnList::getSpecause, "4")
                        .eq(TSAbnList::getOperatestatus, "1");
                List<TSAbnList> abnList = tsAbnListService.list(abnWrapper);
                if (abnList.size() > 0) {
                    return RestResult.ok(true);
                }

                LambdaQueryWrapper<TSBizSpeList> bizwrapper = new LambdaQueryWrapper<>();
                bizwrapper.eq(TSBizSpeList::getPripid, pripid)
                        .eq(TSBizSpeList::getIsRemove, "0")
                        .eq(TSBizSpeList::getSpecause, "4")
                        .notIn(TSBizSpeList::getStatus, "2", "3", "4");
                List<TSBizSpeList> list = tsBizSpeListService.list(bizwrapper);
                if (list.size() > 0) {
                    return RestResult.ok(true);
                }
            }

            regno = one.getRegno();
            Toincludeabn toincludeabn = new Toincludeabn();
            toincludeabn.setPripid(pripid);
            toincludeabn.setUniscid(uniscid);
            toincludeabn.setRegno(regno);
            toincludeabn.setIncludeType(includeType);
            toincludeabn.setDataFromId(dataFromId);
            toincludeabn.setDataFrom("2");
            toincludeabn.setState("0");
            toincludeabn.setRegEntryUserName(regEntryUserName);
            toincludeabn.setRegEntryUserId(regEntryUserId);
            toincludeabn.setDataState("0");
            toincludeabn.setInsertTime(LocalDateTime.now());
            toincludeabn.setEntOrgDer(entOrgDer);
            toincludeabn.setInspectobjid(inspectobjid);
            boolean save = toincludeabnService.saveClueAndFile(files, toincludeabn);
            if (save) {
                return RestResult.ok(save);
            }
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "保存失败");
        } else if ("delete".equals(type)) {
            // 废弃线索，结束流程
            boolean updateClue = tsBizSpeListService.updateAicodsClue(type, dataFromId, null);
            if (updateClue) {
                return RestResult.ok(updateClue);
            }
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "更新流程失败");
        } else if ("update".equals(type)) {
            // 更新流程
            boolean updateClue = tsBizSpeListService.updateAicodsClue(type, dataFromId, files);
            if (updateClue) {
                return RestResult.ok(updateClue);
            }
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "更新流程失败");
        } else {
            return RestResult.error(ResultCode.PARAM_IS_INVALID);
        }
    }

    @PostMapping("updateClue_SSJ")
    public RestResult<?> updateClue(@RequestBody Map<String, Object> params) {
        AssertUtils.isNotNull(params);
        String type = StringUtils.tranObject(params.get("type"));
        String dataFromId = StringUtils.tranObject(params.get("dataFromId"));
        if (StringUtils.isEmpty(type)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "type为空");
        }
        if (StringUtils.isEmpty(dataFromId)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "数据主键为空");
        }
        boolean updateClue = tsBizSpeListService.updateAicodsClue(type, dataFromId, null);
        if (updateClue) {
            return RestResult.ok(updateClue);
        }
        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "更新流程失败");
    }

    /**
     * 未开启待办，废弃线索
     *
     * @param request
     * @param toIncludeId 线索主键
     * @return
     */
    @PostMapping("deleteClue")
    public RestResult<?> deleteClue(HttpServletRequest request, String toIncludeId) {
        AssertUtils.isNotEmpty(toIncludeId);
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        boolean delete = toincludeabnService.deleteById(user.getPrimaryKey(), toIncludeId);
        return RestResult.ok(delete);
    }

    @RequestMapping("downLoad")
    public void downLoad(String attachmentid, HttpServletResponse responsewb) {
        TSAttachment tsAttachment = tsAttachmentService.getById(attachmentid);
        // 转换特殊数据
        String fileUrl = tsAttachment.getFileurl();
        if (!fileUrl.startsWith("date")) {
            String fileLast = fileUrl.substring(22);
            String date = fileUrl.substring(11, 21);
            fileUrl = "date=" + date + "&fileLast=" + fileLast;
        }

        String uir = downLoadPath + "?" + fileUrl;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(uir);
        HttpResponse response = null;
        String showName = tsAttachment.getFilename();
        BufferedOutputStream bout = null;
        InputStream in = null;
        try {
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            in = entity.getContent();
            showName = new String(showName.getBytes("gb2312"), "ISO8859-1");
            responsewb.setContentType("application/msword");
            responsewb.setCharacterEncoding("UTF-8");
            responsewb.setHeader("Content-Disposition", "attachment; filename=" + showName);
            bout = new BufferedOutputStream(responsewb.getOutputStream());
            int l = -1;
            byte[] tmp = new byte[1024];
            while ((l = in.read(tmp)) != -1) {
                bout.write(tmp, 0, l);
            }
            bout.flush();
            bout.close();
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                bout.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    // 供接收品毅一码联查的日常检查列异线索数据推送接口
    @PostMapping("registration")
    public RestResult<?> registration(@RequestBody PYRequestDTO request) {
        HashMap data = new HashMap();
        if (StringUtils.isEmpty(request.getType())) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "type为空", data);
        }
        if (StringUtils.isEmpty(request.getDataFromId())) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "数据主键为空", data);
        }
        if ("save".equals(request.getType())) {
            // 保存线索
            String regno = request.getRegno();
            String includeType = request.getIncludeType();
            String regEntryUserId = request.getRegEntryUserId();
            String regEntryUserName = request.getRegEntryUserName();
            String entOrgDer = request.getEntOrgDer();
            String inspectobjid = request.getPripid();
            String dataFromId = request.getDataFromId();
            data.put("dataFromId", dataFromId);
            // 判断是否需要保存
            LambdaQueryWrapper toincludeabnWrapper = new LambdaQueryWrapper<Toincludeabn>()
                    .eq(Toincludeabn::getInspectobjid, inspectobjid).eq(Toincludeabn::getIncludeType, includeType)
                    .in(Toincludeabn::getState, new String[]{"0", "1"}) // 未发起线索或审核审批线索
                    .eq(Toincludeabn::getDataState, "0"); // 正常状态
            List<Toincludeabn> toincludeabns = toincludeabnService.list(toincludeabnWrapper);
            if (toincludeabns.size() > 0) {
                return RestResult.ok(data);
            }

            AssertUtils.isNotEmpty(regno, dataFromId, includeType);
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isUscc(regno)) {
                wrapper.eq(EBaseinfo::getUniscid, regno);
            } else {
                wrapper.eq(EBaseinfo::getRegno, regno);
            }
            wrapper.eq(EBaseinfo::getRegstate, "1");
            EBaseinfo one = eBaseinfoService.getOne(wrapper);
            if (one == null) {
                return RestResult.error(ResultCode.DATA_NONE, "注册号参数有误，找不到主体", data);
            }
            String pripid = one.getPripid();
            String uniscid = one.getUniscid();

            //地址的，列异中和已列异不生成线索
            if ("4".equals(includeType)) {
                LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
                abnWrapper.eq(TSAbnList::getPripid, pripid)
                        .eq(TSAbnList::getSpecause, "4")
                        .eq(TSAbnList::getOperatestatus, "1");
                List<TSAbnList> abnList = tsAbnListService.list(abnWrapper);
                if (abnList.size() > 0) {
                    return RestResult.ok(data);
                }

                LambdaQueryWrapper<TSBizSpeList> bizwrapper = new LambdaQueryWrapper<>();
                bizwrapper.eq(TSBizSpeList::getPripid, pripid)
                        .eq(TSBizSpeList::getIsRemove, "0")
                        .eq(TSBizSpeList::getSpecause, "4")
                        .notIn(TSBizSpeList::getStatus, "2", "3", "4");
                List<TSBizSpeList> list = tsBizSpeListService.list(bizwrapper);
                if (list.size() > 0) {
                    return RestResult.ok(data);
                }
            }
            regno = one.getRegno();
            Toincludeabn toincludeabn = new Toincludeabn();
            toincludeabn.setPripid(pripid);
            toincludeabn.setUniscid(uniscid);
            toincludeabn.setRegno(regno);
            toincludeabn.setIncludeType(includeType);
            toincludeabn.setDataFromId(dataFromId);
            toincludeabn.setDataFrom("2");
            toincludeabn.setState("0");
            toincludeabn.setRegEntryUserName(regEntryUserName);
            toincludeabn.setRegEntryUserId(regEntryUserId);
            toincludeabn.setDataState("0");
            toincludeabn.setInsertTime(LocalDateTime.now());
            toincludeabn.setEntOrgDer(entOrgDer);
            toincludeabn.setInspectobjid(inspectobjid);
            boolean save = toincludeabnService.saveYMLCClueAndFile(request.getFiles(), toincludeabn);
            if (save) {
                return RestResult.ok(data);
            }
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "保存失败", data);
        } else {
            return RestResult.error(ResultCode.PARAM_IS_INVALID, data);
        }
    }

}

