package com.mortals.xhx.busiz;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.util.FileUtil;
import com.mortals.xhx.base.framework.config.InterceptorConfig;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.busiz.login.DatumDataReq;
import com.mortals.xhx.busiz.matters.MyMattersReq;
import com.mortals.xhx.busiz.onethinglist.OneThingReq;
import com.mortals.xhx.busiz.question.QuestionInfo;
import com.mortals.xhx.busiz.question.AnswerReq;
import com.mortals.xhx.busiz.uploadfile.DeleteFileReq;
import com.mortals.xhx.busiz.uploadfile.SubmitDatumReq;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.common.code.OneThingRespCodeEnum;
import com.mortals.xhx.feign.flowable.IApiFlowInstanceFeign;
import com.mortals.xhx.feign.rsp.ApiResp;
import com.mortals.xhx.module.member.model.MemberEntity;
import com.mortals.xhx.module.member.model.MemberQuery;
import com.mortals.xhx.module.member.service.MemberService;
import com.mortals.xhx.module.one.service.OneClassifyService;
import com.mortals.xhx.module.one.service.OneClassifyTopicalService;
import com.mortals.xhx.module.one.service.OneTopicalService;
import com.mortals.xhx.module.yth.model.YthOnethingEntity;
import com.mortals.xhx.module.yth.model.YthOnethingQuery;
import com.mortals.xhx.module.yth.service.YthOnethingService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 一件事微信对外服务接口
 *
 * @author: zxfei
 * @date: 2021/8/24 20:28
 */
@RestController
@CommonsLog
@RequestMapping("/zwfw/proced/")
public class WxOneThingApiController {

    @Autowired
    private YthOnethingService onethingService;

    @Autowired
    private ParamService paramService;
    @Autowired
    private IApiFlowInstanceFeign apiFlowInstanceFeign;
    @Autowired
    private MemberService memberService;
    @Autowired
    private InterceptorConfig config;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private OneTopicalService oneTopicalService;
    @Autowired
    private OneClassifyService oneClassifyService;
    @Autowired
    private OneClassifyTopicalService oneClassifyTopicalService;


    /**
     * 一件事主题列表(包含主题包)
     *
     * @param req
     * @return
     */
    @PostMapping("thing/oneTopiclist")
    public ApiResp<List<Map<String, Object>>> oneThingList(OneThingReq req) {
        ApiResp<List<Map<String, Object>>> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        try {
            List<Map<String, Object>> treeList = oneTopicalService.getTreeList(req.getType());
            rsp.setData(treeList);
        } catch (Exception e) {
            log.error("一件事列表失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        log.info("响应【一件事列表】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }


    /**
     * 问答答案提交后返回的详细结果
     *
     * @param req
     * @return
     */
    @PostMapping("thing/ansResults")
    public ApiResp<QuestionInfo> ansResults(AnswerReq req) {
        ApiResp<QuestionInfo> rsp = new ApiResp<>();
        rsp.setMsg(OneThingRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(OneThingRespCodeEnum.SUCCESS.getValue());
        try {

            QuestionInfo mattersByAnswers = oneClassifyTopicalService.getMattersByAnswers(req);
            rsp.setData(mattersByAnswers);
        } catch (Exception e) {
            log.error("问答基础信息失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        log.info("响应【问答基础信息】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }

    /**
     * 提交后请求返回数据
     *
     * @param req
     * @return
     */
    @PostMapping("thing/datum_data")
    public ApiResp<QuestionInfo> datumData(DatumDataReq req) {
        ApiResp<QuestionInfo> rsp = new ApiResp<>();
        rsp.setMsg(OneThingRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(OneThingRespCodeEnum.SUCCESS.getValue());
        try {

            //todo  改用户需要的材料
            // QuestionInfo questionInfo = classifyOptionService.conditionQuestion(req.getOption_id(), req.getKey());
            //rsp.setData(questionInfo);
        } catch (Exception e) {
            log.error("问答基础信息失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        log.info("响应【登录后返回数据】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }

    /**
     * 上传附件
     *
     * @param file
     * @return
     */
    @PostMapping("thing/uploadFile")
    public ApiResp<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        ApiResp<Map<String, String>> rsp = new ApiResp<>();
        rsp.setMsg(OneThingRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(OneThingRespCodeEnum.SUCCESS.getValue());
        try {
            String path = uploadService.saveFileUpload(file, config.getPrepath(), null);
            Map<String, String> map = new HashMap<>();
            map.put("path", path);
            rsp.setData(map);
        } catch (Exception e) {
            log.error("上传文件", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        log.info("响应【上传文件】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }


    /**
     * 删除附件
     *
     * @param req
     * @return
     */
    @PostMapping("thing/delFile")
    public ApiResp<String> deleteFile(DeleteFileReq req) {
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(OneThingRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(OneThingRespCodeEnum.SUCCESS.getValue());
        try {

           String filePath = uploadService.getFilePath(req.getFilePath());

            boolean delete = FileUtil.delete(filePath);
            if (!delete) {
                rsp.setMsg("未找到文件");
                rsp.setCode(OneThingRespCodeEnum.FAILED.getValue());
            }

        } catch (Exception e) {
            log.error("删除文件", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        log.info("响应【删除文件】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }


    /**
     * 查询用户信息
     *
     * @param req
     * @return
     */
    @PostMapping("thing/searchMember")
    public ApiResp<MemberEntity> searchMember(BaseReq req) {
        ApiResp<MemberEntity> rsp = new ApiResp<>();
        rsp.setMsg(OneThingRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(OneThingRespCodeEnum.SUCCESS.getValue());
        try {

            MemberEntity memberEntity = memberService.selectOne(new MemberQuery().openId(req.getOpenId()), null);
            if (ObjectUtils.isEmpty(memberEntity)) {
                throw new AppException("查询用户不存在");
            }
            rsp.setData(memberEntity);
        } catch (Exception e) {
            log.error("查询用户信息失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        log.info("响应【查询用户信息】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }

    /**
     * 一件事办理资料提交
     *
     * @param req
     * @return
     */
    @PostMapping("thing/submitDatum")
    public ApiResp<String> submitDatum(SubmitDatumReq req) {
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(OneThingRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(OneThingRespCodeEnum.SUCCESS.getValue());
        try {
            onethingService.datumUploadAndStartFlow(req);
        } catch (Exception e) {
            log.error("一件事办理资料提交失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        log.info("响应【一件事办理资料提交】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }

    /**
     * 我的办理
     *
     * @param req
     * @return
     */
    @PostMapping("thing/myHandle")
    public ApiResp<List<YthOnethingEntity>> myHandle(MyMattersReq req) {
        ApiResp<List<YthOnethingEntity>> rsp = new ApiResp<>();
        rsp.setMsg(OneThingRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(OneThingRespCodeEnum.SUCCESS.getValue());
        try {
            //todo 我的办理信息
            List<YthOnethingEntity> list = onethingService.find(new YthOnethingQuery().openId(req.getOpenId()));
            rsp.setData(list);
        } catch (Exception e) {
            log.error("我的办理失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        log.info("响应【我的办理】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }

    /**
     * 微信用户提交材料
     *
     * @param entity
     * @return
     */
//    @PostMapping("thing/create")
//    public ApiResp<String> createThing(OnethingEntity entity) {
//        ApiResp rsp = new ApiResp<>();
//        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
//        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
//        try {
//            entity.setType(OneThingTypeEnum.UNSUBMIT.getValue());
//            entity.setStatus(ApproveStateEnum.UN_AUDIT.getValue());
//            entity.setCreateUser("admin");
//            entity.setCreateTime(new Date());
//            OnethingEntity save = onethingService.save(entity);
//            rsp.setData(save.getId());
//        } catch (Exception e) {
//            log.error("流程实例化终止失败", e);
//            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
//            rsp.setMsg(e.getMessage());
//            return rsp;
//        }
//
//        log.info("响应【材料创建】【响应体】-->  " + JSONObject.toJSONString(rsp));
//        return rsp;
//    }


    /**
     * 发起流程
     *
     * @param req
     * @return
     */
   /* @PostMapping("thing/start")
    public ApiResp<String> startProcess(StartOneThingReq req) {
        ApiResp rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            OnethingEntity onethingEntity = onethingService.get(req.getOneThingId());
            MemberEntity memberEntity = memberService.get(onethingEntity.getMemberId());

            //获取流程定义key 发起流程 当前通过param参数固定获取
            String oneThingKey = paramService.getValueByKey(BusizParams.SYS_PARAM_FLOW_KEY);
            //通过流程key获取基础提交参数
            String vars = paramService.getValueByKey(oneThingKey);

            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> variables = mapper.readValue(vars, Map.class);

            StartProcessInstanceReq startProcessInstanceReq = new StartProcessInstanceReq();
            startProcessInstanceReq.setProcessDefinitionKey(oneThingKey);
            startProcessInstanceReq.setBusinessKey(onethingEntity.getId().toString());
            startProcessInstanceReq.setFormName("一件事一次办");
            startProcessInstanceReq.setUserCode(memberEntity.getOpenId());
            startProcessInstanceReq.setPlatformSn(config.getTenantId());
            startProcessInstanceReq.setVariables(variables);

            ApiResp<String> resp = apiFlowInstanceFeign.processStart(startProcessInstanceReq);
            onethingEntity.setProcessInstanceId(resp.getData());
            onethingEntity.setType(OneThingTypeEnum.SUBMIT.getValue());
            onethingEntity.setStatus(ApproveStateEnum.AUDITING.getValue());

            onethingService.update(onethingEntity);

            rsp.setData(resp.getData());

        } catch (Exception e) {
            log.error("发起审批流程", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return rsp;
        }
        log.info("响应【材料创建】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return rsp;
    }*/


}
