package com.cftech.questionnaire.core.paper.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.core.generic.GenericDao;
import com.cftech.core.generic.GenericServiceImpl;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.questionnaire.core.paper.dao.PaperMapper;
import com.cftech.questionnaire.core.paper.model.*;
import com.cftech.questionnaire.core.paper.service.PaperService;
import com.cftech.sys.security.UserUtils;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

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

/**
* 问卷ServiceImpl
*
* @author wxf
* @date: 2017-05-25 13:48
*/
@Service("paperService")
public class PaperServiceImpl extends GenericServiceImpl<PaperBaseEntity> implements PaperService {

@Autowired
@Qualifier("paperMapper")
private PaperMapper paperMapper;

@Override
public GenericDao<PaperBaseEntity> getGenericMapper() {
return paperMapper;
}

    @Override
    public List<PaperBaseEntity> fetchSearchVOByPage(Long pId, Conds conds, Sort sort, int page, int pageSize) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("pId", pId);
        params.put("conds", conds);
        params.put("offset", page > 0 ? page : 0);
        params.put("limit", pageSize > 0 ? pageSize : 0);
        params.put("sort", sort);
        return paperMapper.fetchSearchVOByPage(params);
    }

    @Override
    public int count(Long pId, Conds conds) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        params.put("pId",pId);
        return paperMapper.count(params);
    }

    @Override
    public boolean saveBatch(PaperBaseEntity t) {
        JSONArray array = JSONArray.parseArray(t.getQuestions());
        Long userId = UserUtils.getUser().getId();
        paperMapper.save(t);
        for(int i =0;i<array.size();i++){
            JSONObject subjectJson = array.getJSONObject(i);
            PaperSubject paperSubject = new PaperSubject();
            paperSubject.setSubjectName(subjectJson.getString("title"));
            paperSubject.setSubjectNameEn(subjectJson.getString("titleEn"));
            paperSubject.setPaperId(t.getId());
            paperSubject.setType(subjectJson.getString("type"));
            paperSubject.setMax(subjectJson.getString("max"));
            paperSubject.setMin(subjectJson.getString("min"));
            paperSubject.setCreateBy(userId);
            paperSubject.setUpdateBy(userId);
            paperMapper.saveSubject(paperSubject);
            subjectJson.put("sid",paperSubject.getId());
            JSONArray arrayOption = subjectJson.getJSONArray("options");
            for(int k =0;k<arrayOption.size();k++){
                JSONObject optionJson = arrayOption.getJSONObject(k);
                PaperOption paperOption = new PaperOption();
                paperOption.setPaperId(t.getId());
                paperOption.setSubjectId(paperSubject.getId());
                paperOption.setPaperId(t.getId());
                paperOption.setCreateBy(userId);
                paperOption.setUpdateBy(userId);
                paperOption.setLabel(optionJson.getString("label"));
                paperOption.setOptionName(optionJson.getString("name"));
                paperOption.setOptionNameEn(optionJson.getString("nameEn"));
                paperMapper.saveOption(paperOption);
                optionJson.put("oid",paperOption.getId());
            }
        }
        t.setQuestions(array.toJSONString());
        paperMapper.update(t);
        return true;
    }

    @Override
    public boolean updateBatch(PaperBaseEntity t) {
        JSONArray array = JSONArray.parseArray(t.getQuestions());
        Long userId = UserUtils.getUser().getId();
        //首先将分表的问题，选项数据全部删除
        paperMapper.updateClearOption(t.getId());
        paperMapper.updateClearPaperSubject(t.getId());

        //然后根据前端传来的数据，去更新
        for(int i =0;i<array.size();i++){
            JSONObject subjectJson = array.getJSONObject(i);
            Long sid = subjectJson.getLong("sid");
            PaperSubject paperSubject = new PaperSubject();
            paperSubject.setSubjectName(subjectJson.getString("title"));
            paperSubject.setSubjectNameEn(subjectJson.getString("titleEn"));
            paperSubject.setPaperId(t.getId());
            paperSubject.setType(subjectJson.getString("type"));
            paperSubject.setMax(subjectJson.getString("max"));
            paperSubject.setDelFlag(false);
            paperSubject.setMin(subjectJson.getString("min"));
            paperSubject.setUpdateBy(userId);
            if(sid==null){
                paperMapper.saveSubject(paperSubject);
                subjectJson.put("sid",paperSubject.getId());
            }else{
                paperSubject.setId(sid);
                paperMapper.updatePaperSubject(paperSubject);
            }
            JSONArray arrayOption = subjectJson.getJSONArray("options");
            for(int k =0;k<arrayOption.size();k++){
                JSONObject optionJson = arrayOption.getJSONObject(k);
                Long oid =optionJson.getLong("oid");
                PaperOption paperOption = new PaperOption();
                paperOption.setPaperId(t.getId());
                paperOption.setSubjectId(paperSubject.getId());
                paperOption.setPaperId(t.getId());
                paperOption.setCreateBy(userId);
                paperOption.setDelFlag(false);
                paperOption.setUpdateBy(userId);
                paperOption.setLabel(optionJson.getString("label"));
                paperOption.setOptionName(optionJson.getString("name"));
                paperOption.setOptionNameEn(optionJson.getString("nameEn"));
                if(oid==null){
                    paperMapper.saveOption(paperOption);
                    optionJson.put("oid",paperOption.getId());
                }else{
                    paperOption.setId(oid);
                    paperMapper.updatePaperOption(paperOption);
                }
            }
        }
        t.setQuestions(array.toJSONString());
        paperMapper.update(t);
        return true;
    }

    /**
     * 选择活动
     * @param conds
     * @param sort
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public List<SelectActivity> searchActivity(Conds conds, Sort sort, int page, int pageSize){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        params.put("offset", page > 0 ? page : 0);
        params.put("limit", pageSize > 0 ? pageSize : 0);
        params.put("sort", sort);
        return paperMapper.searchActivity(params);
    };

    /**
     * 活动个数
     * @param conds
     * @return
     */
    @Override
    public int countActivity(Conds conds){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        return paperMapper.countActivity(params);
    }

    @Override
    public List<PaperSubject> selectPaperSubject(Conds conds) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        return paperMapper.selectPaperSubject(params);
    }

    ;
}