package com.xueyi.system.digitalmans.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xueyi.common.core.web.result.AjaxResult;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.core.web.validate.V_A;
import com.xueyi.common.core.web.validate.V_E;
import com.xueyi.common.log.annotation.Log;
import com.xueyi.common.log.enums.BusinessType;
import com.xueyi.common.security.annotation.Logical;
import com.xueyi.common.security.annotation.RequiresPermissions;
import com.xueyi.common.security.utils.SecurityUtils;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.nlt.api.nlt.domain.vo.TaskKnowledgeVo;
import com.xueyi.system.api.digitalmans.domain.vo.DmBatchQuestionsVo;
import com.xueyi.system.api.digitalmans.domain.vo.DmReceptionVo;
import com.xueyi.system.digitalmans.domain.dto.DmQAndADto;
import com.xueyi.system.digitalmans.domain.query.DmQAndAQuery;
import com.xueyi.system.digitalmans.service.IDmQAndAService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 企业知识库问答管理 业务处理
 *
 * @author yinruoxi
 */
@RestController
@RequestMapping("/questionanswers")
public class DmQAndAController extends BaseController<DmQAndAQuery, DmQAndADto, IDmQAndAService> {

    private static final Logger log = LoggerFactory.getLogger(DmQAndAController.class);
    @Autowired
    RedisTemplate redisTemplate;

    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "企业知识库问答" ;
    }


    @PostMapping("/inner/batch_insert")
    @ResponseBody
    public R<Integer> batchInsertInner(@RequestBody DmBatchQuestionsVo dmBatchQuestionsVo) {
        log.info("knowledgeId:{},questions:{}", dmBatchQuestionsVo.getKnowledgeId(), dmBatchQuestionsVo.getQuestions().toJSONString());
        List<DmQAndADto> queries = new ArrayList<>();
        // JsonArray转换为对象
        for (int i =0 ; i < dmBatchQuestionsVo.getQuestions().size();i++) {
            DmQAndADto query = new DmQAndADto();
            JSONObject jsonObject = dmBatchQuestionsVo.getQuestions().getJSONObject(i);
            query.setName(jsonObject.getString("question"));
            query.setAnswer(jsonObject.getString("answer"));
            query.setKnowledgeId(dmBatchQuestionsVo.getKnowledgeId());
            query.setStatus("0");
            query.setType(0);
            query.setCreateBy(dmBatchQuestionsVo.getCreateId());
            queries.add(query);
        }
//        dmBatchQuestionsVo.getQuestions().forEach(item -> {
//            DmQAndADto query = new DmQAndADto();
//            JSONObject jsonObject = (JSONObject)item;
//            query.setName(jsonObject.getString("question"));
//            query.setAnswer(jsonObject.getString("answer"));
//            query.setKnowledgeId(dmBatchQuestionsVo.getKnowledgeId());
//            queries.add(query);
//        });
        baseService.batchInsert(queries);
        return R.ok();
    }
    /**
     * 查询企业知识库问答列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.DM_Q_AND_A_LIST)
    public AjaxResult list(DmQAndAQuery qAndA) {
        return super.list(qAndA);
    }

    /**
     * 查询企业知识库问答详细
     */
    @Override
    @GetMapping(value = "/{id}")
    @RequiresPermissions(Auth.DM_Q_AND_A_SINGLE)
    public AjaxResult getInfo(@PathVariable Serializable id) {
        return super.getInfo(id);
    }

    /**
     * 企业知识库问答新增
     */
    @Override
    @PostMapping
    @RequiresPermissions(Auth.DM_Q_AND_A_ADD)
    @Log(title = "企业知识库问答管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated({V_A.class}) @RequestBody DmQAndADto qAndA) {

        return super.add(qAndA);
    }

    /**
     * 企业知识库元文本
     */
    @PostMapping("/upload")
    @Log(title = "企业知识库问答管理", businessType = BusinessType.INSERT)
    public AjaxResult upload(@RequestBody DmQAndADto qAndA) {
        //将数据缓存到redis队列中
        TaskKnowledgeVo taskKnowledgeVo = new TaskKnowledgeVo();
        taskKnowledgeVo.setContent(qAndA.getMetaText());
        taskKnowledgeVo.setCount(qAndA.getMetaText().length());
        taskKnowledgeVo.setManId(qAndA.getManId());
        taskKnowledgeVo.setKnowledgeId(qAndA.getKnowledgeId());
        taskKnowledgeVo.setTenantId(SecurityUtils.getEnterpriseId());
        taskKnowledgeVo.setSplit(0);
        taskKnowledgeVo.setCreateBy(SecurityUtils.getLoginUser().getUserId());
        redisTemplate.opsForList().rightPush("group:task",taskKnowledgeVo);
        return super.success();
    }

    /**
     * 企业知识库问答修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.DM_Q_AND_A_EDIT)
    @Log(title = "企业知识库问答管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody DmQAndADto qAndA) {
        return super.edit(qAndA);
    }

    /**
     * 企业知识库问答修改状态
     */
    @Override
    @PutMapping("/status")
    @RequiresPermissions(value = {Auth.DM_Q_AND_A_EDIT, Auth.DM_Q_AND_A_ES}, logical = Logical.OR)
    @Log(title = "企业知识库问答管理", businessType = BusinessType.UPDATE_STATUS)
    public AjaxResult editStatus(@RequestBody DmQAndADto qAndA) {
        return super.editStatus(qAndA);
    }

    /**
     * 企业知识库问答批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.DM_Q_AND_A_DEL)
    @Log(title = "企业知识库问答管理", businessType = BusinessType.DELETE)
    public AjaxResult batchRemove(@PathVariable List<Long> idList) {
        return super.batchRemove(idList);
    }

    /**
     * 获取企业知识库问答选择框列表
     */
    @Override
    @GetMapping("/option")
    public AjaxResult option() {
        return super.option();
    }

    interface Auth {
        /** 系统 - 企业知识库问答管理 - 列表 */
        String DM_Q_AND_A_LIST = "digitalmans:questionanswers:list";
        /** 系统 - 企业知识库问答管理 - 详情 */
        String DM_Q_AND_A_SINGLE = "digitalmans:questionanswers:single";
        /** 系统 - 企业知识库问答管理 - 新增 */
        String DM_Q_AND_A_ADD = "digitalmans:questionanswers:add";
        /** 系统 - 企业知识库问答管理 - 修改 */
        String DM_Q_AND_A_EDIT = "digitalmans:questionanswers:edit";
        /** 系统 - 企业知识库问答管理 - 修改状态 */
        String DM_Q_AND_A_ES = "digitalmans:questionanswers:es";
        /** 系统 - 企业知识库问答管理 - 删除 */
        String DM_Q_AND_A_DEL = "digitalmans:questionanswers:delete";
    }
}
