package yangtz.cs.liu.campus.controller.schoolDcwj;

import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import yangtz.cs.liu.campus.domain.schoolDcwj.SchoolDcwj;
import yangtz.cs.liu.campus.domain.schoolDcwj.SchoolDcwjAn;
import yangtz.cs.liu.campus.domain.schoolDcwj.SchoolDcwjNr;
import yangtz.cs.liu.campus.mapper.schoolDcwj.SchoolDcwjNrMapper;
import yangtz.cs.liu.campus.service.schoolDcwj.ISchoolDcwjAnService;
import yangtz.cs.liu.campus.service.schoolDcwj.ISchoolDcwjNrService;
import yangtz.cs.liu.campus.service.schoolDcwj.ISchoolDcwjRyService;
import yangtz.cs.liu.campus.service.schoolDcwj.ISchoolDcwjService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.util.ExcelUtils;
import yangtz.cs.liu.campus.vo.schoolDcwj.DcwjRyExportVo;
import yangtz.cs.liu.campus.vo.schoolDcwj.SchoolDcwjAnVo;
import yangtz.cs.liu.campus.vo.schoolDcwj.ViewDataVo;
import yangtz.cs.liu.campus.vo.schoolDcwj.ViewTitlesVo;

import static yangtz.cs.liu.campus.constant.DcwjType.*;

/**
 * 回答结果Controller
 *
 * @author wengxiulin
 * @date 2023-03-01
 */
@RestController
@RequestMapping("/dcwjAn")
public class SchoolDcwjAnController extends BaseController {
    @Autowired
    private ISchoolDcwjAnService schoolDcwjAnService;

    @Autowired
    private ISchoolDcwjNrService nrService;

    @Autowired
    private ISchoolDcwjRyService ryService;

    @Autowired
    private ISchoolDcwjService dcwjService;

    @Autowired
    private ISchoolStudentService schoolStudentService;

    @Autowired
    private ISchoolDcwjNrService schoolDcwjNrService;

    @Value("${server.port}")
    private String p;

    /**
     *  TODO 级部-问卷结果-明细数据-列表
     */
    @GetMapping("/list/{dcwjId}")
    public AjaxResult list(@PathVariable("dcwjId") Long dcwjId, SchoolDcwjAnVo vo) {
        AjaxResult ajax = AjaxResult.success();
        //获取标题(班级、学生姓名、填写状态、填写时间等是固定的，所以只获取后面的题目1。。。。等)
        List<SchoolDcwjNr> titles = nrService.getNrBtByDcwjId(dcwjId);
        ViewTitlesVo titlesVo = nrService.turnTitles(titles);
        ajax.put("titles", titlesVo);

        //获取内容
//        List<SchoolDcwjAnVo> list = ryService.getAnData(dcwjId, vo);


        //获取固定列的值,,获取到的list的id为ry表的id
        startPage();
        List<SchoolDcwjAnVo> list = ryService.getAnData1(dcwjId, vo);

        //获取问卷调查题目
        LambdaQueryWrapper<SchoolDcwjNr> nrlqw = new LambdaQueryWrapper<>();
        nrlqw.eq(SchoolDcwjNr::getDcwjId, dcwjId).orderByAsc(SchoolDcwjNr::getNrPx).orderByDesc(SchoolDcwjNr::getCreateTime);
        List<SchoolDcwjNr> nrs = schoolDcwjNrService.list(nrlqw);

        LambdaQueryWrapper<SchoolDcwjAn> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolDcwjAn::getDcwjId, dcwjId)
        ;
        //a里要么有1个值，要么没有值
        List<SchoolDcwjAn> a = schoolDcwjAnService.list(lqw);

        //学生家长调查问卷回答的内容
        for (SchoolDcwjAnVo anVo : list) {
            List<SchoolDcwjAn> ans = new ArrayList<>();
            //设置空对象，是为了，通俗的说就是站位，如果不占位的话，就目前来说，如果用户第一题没写，第二题写了，那么第2题的答案会显示在第1题的位置
            SchoolDcwjAn entity = new SchoolDcwjAn();

            //获取该学生从第一题到最后一题的答案，如果当前题没有答案，，附空值
            for(SchoolDcwjNr nr : nrs){
//                LambdaQueryWrapper<SchoolDcwjAn> lqw = new LambdaQueryWrapper<>();
//                lqw
//                        .eq(SchoolDcwjAn::getDcwjId, dcwjId)
//                        .eq(SchoolDcwjAn::getRyId, anVo.getId())
//                        .eq(SchoolDcwjAn::getNrId, nr.getId())
//                ;
//                //a里要么有1个值，要么没有值
//                List<SchoolDcwjAn> a = anMapper.selectList(lqw);

                for (SchoolDcwjAn schoolDcwjAn : a) {
                    if (schoolDcwjAn.getRyId().equals(anVo.getId()) && schoolDcwjAn.getNrId().equals(nr.getId())){
                        ans.add(a.get(0));
                    }else {
                        ans.add(entity);
                    }
                }

//                if(StringUtils.isNotNull(a) && a.size() > 0){
//                    ans.add(a.get(0));
//                }else {
//                    ans.add(entity);
//                }
            }
            anVo.setList(ans);
        }
//        return list;

        List<ViewDataVo> voList = nrService.turnData(list);
        ajax.put("data", voList);
        ajax.put("total",getDataTable(list).getTotal());
        return ajax;
    }

    /**
     * 级部-问卷结果-明细数据-导出
     */
    @PostMapping("/export/{dcwjId}")
    public void export(HttpServletResponse response, @PathVariable("dcwjId") Long dcwjId, SchoolDcwjAnVo vo) throws UnknownHostException {
        SchoolDcwj dcwj = dcwjService.getById(dcwjId);
        //获取表头
        //获取标题(只获取后面的题目1。。。。等)
        List<SchoolDcwjNr> titleList = nrService.getNrBtByDcwjId(dcwjId);
        //表头为空时的操作
        if (StringUtils.isNull(titleList) || titleList.size() == 0) {
            throw new ServiceException("该调查问卷内容为空，请检查");
        }
        //获取类型为图片的标题id
        List<Long> picIds = new ArrayList<>();
        //处理表头 前几列是固定
        List<Object> titles = new ArrayList<>();
        titles.add(XUHAO);
        titles.add(SNAME);
        titles.add(IDCARD);
        titles.add(GRADENAME);
        titles.add(CLASSNAME);
        for (SchoolDcwjNr nr : titleList) {
            titles.add(nr.getNrBt());
            //获取类型为图片上传的标题
            if ("3".equals(nr.getNrLx())) {
                picIds.add(nr.getId());
            }
        }

        //获取内容,根据主表id，模糊查询，当答题为空时，为了防止导出出错，需要整理下数据
        List<DcwjRyExportVo> dataVoList = ryService.getAnExportData(dcwjId, vo,titleList.size());

        //内容为空时的操作
        if (StringUtils.isNull(dataVoList) || dataVoList.size() == 0) {
            throw new ServiceException("内容为空！！！");
        }

        //数据汇总
        List<List<Object>> sheetDataList = new ArrayList<>();
        sheetDataList.add(titles);

        for (DcwjRyExportVo exportVo : dataVoList) {
            List<Object> o = new ArrayList<>();
            //固定导出的
            o.add(exportVo.getXh());
            o.add(exportVo.getStudentName());
            o.add(exportVo.getIdCard());
            o.add(exportVo.getGradeName());
            o.add(exportVo.getClassName());

            //不固定的
            for (SchoolDcwjAn an : exportVo.getList()) {
                if(StringUtils.isNull(an.getNrId())){
                    o.add(" ");
                    continue;
                }
                if (picIds.contains(an.getNrId())) {
                    try {
                        o.add(new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + p + an.getUserAnswer()));
                    } catch (Exception e) {
                        throw new UnknownHostException("转换URL出错");
                    }
                } else {
                    o.add(an.getUserAnswer());
                }
            }

            //当用户没有填写记录时,上面for循环不执行，所以不固定的那些列就没有数据
            for(int i = 0 ;i < titleList.size();i++){
                o.add(" ");
            }

            List<Object> objects = new ArrayList<>();
            for (int a = 0; a < titles.size(); a++) {
                objects.add(o.get(a));
            }
            sheetDataList.add(objects);
        }
        ExcelUtils.export(response, dcwj.getDcwjName(), sheetDataList);
    }

    /**
     * 级部/班主任/教务-问卷结果-明细数据-详情
     * id 为ry表对应主键
     * 排序？
     */
    @GetMapping(value = "/queryById/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ryService.getDetails(id));
    }


    /**
     * 级部/教务-问卷结果-统计
     * id为主表id
     */
    @GetMapping("/getCount/{dcwjId}")
    public AjaxResult getCount(@PathVariable("dcwjId") Long dcwjId) {
        return AjaxResult.success(ryService.getCount(dcwjId));
    }

    /**
     * 新增回答结果
     */
    @Log(title = "回答结果", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolDcwjAn schoolDcwjAn) {
        LambdaQueryWrapper<SchoolDcwjAn> luw = new LambdaQueryWrapper<>();
        luw.
                eq(SchoolDcwjAn::getDcwjId, schoolDcwjAn.getDcwjId()).
                eq(SchoolDcwjAn::getNrId, schoolDcwjAn.getNrId()).
                eq(SchoolDcwjAn::getRyId, schoolDcwjAn.getRyId());
        SchoolDcwjAn dcwjAn = schoolDcwjAnService.getOne(luw);

        if (StringUtils.isNull(dcwjAn)) {
            throw new ServiceException("不能重复作答");
        }

        schoolDcwjAn.insert();
        return toAjax(schoolDcwjAnService.insertSchoolDcwjAn(schoolDcwjAn));
    }

    /**
     * 修改回答结果
     */
    @Log(title = "回答结果", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolDcwjAn schoolDcwjAn) {
        return toAjax(schoolDcwjAnService.updateSchoolDcwjAn(schoolDcwjAn));
    }

    /**
     * 删除回答结果
     */
    @Log(title = "回答结果", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(schoolDcwjAnService.removeByIds(ids));
    }
}
