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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.utils.UploadToServer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.util.UserInfoUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.domain.schoolDcwj.SchoolDcwjRy;
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.wechat.vo.schoolDcwj.SchoolDcwjVo;
import yangtz.cs.liu.wechat.vo.schoolDcwj.Vo_SchoolDcwj;
import yangtz.cs.liu.wechat.vo.schoolDcwj.Vo_SchoolDcwjNr;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.ruoyi.common.utils.DateUtils.isEffectiveDate;

@RestController
@RequestMapping("/wx/schoolDcwj")
public class WxSchoolDcwjController extends BaseController {

    @Autowired
    private UserInfoUtil userInfoUtil;

    @Autowired
    private ISchoolDcwjService schoolDcwjService;

    @Autowired
    private ISchoolDcwjAnService schoolDcwjAnService;

    @Autowired
    private ISchoolDcwjRyService schoolDcwjRyService;

    @Autowired
    private ISchoolDcwjNrService schoolDcwjNrService;

    @Value("${ruoyi.serverAddress}")
    private String serverAddress;

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

    public static final String IS = "1";    //是(填写过)

    public static final String PIC = "3";    //题目类型为图片题


    /*
    获取调查问卷列表 ==>家长+教职工
     */
    @GetMapping("/getDcwjList")
    public TableDataInfo getDcwjList(String state) {
        startPage();
        List<Vo_SchoolDcwj> list ;
        if (isNotNull(userInfoUtil.getStudentId())) {   //家长
            list = schoolDcwjService.getDcwjList(userInfoUtil.getStudentId(), state);
        }else {     //教职工
            list = schoolDcwjService.teacherGetDcwjList(userInfoUtil.getTeacherId(), state);
        }
        for (Vo_SchoolDcwj vo_schoolDcwj : list) {
            //判断当前时间是否在问卷有效时间内
            Date date = new Date();
            boolean flag = isEffectiveDate(date, vo_schoolDcwj.getDcwjKssj(), vo_schoolDcwj.getDcwjJssj());
            vo_schoolDcwj.setFlag(flag);
        }
        return getDataTable(list);
    }

    /**
     * 获取某一个调查问卷下题目+用户回答详情(查看)  ==>家长+教职工
     *
     * @return
     */
    @GetMapping("/getDcwjNrList/{dcwjId}")
    public TableDataInfo getDcwjNrList(@PathVariable("dcwjId") Long dcwjId) {
        startPage();
        List<Vo_SchoolDcwjNr> list = schoolDcwjNrService.getDcwjNrList(dcwjId,userInfoUtil.getStudentId(),userInfoUtil.getTeacherId());
        for(Vo_SchoolDcwjNr nr : list){
            if(PIC.equals(nr.getNrLx())){
                if(StringUtils.isNotNull(nr.getUserAnswer()) && !"".equals(nr.getUserAnswer())){
                    String url = serverAddress+nr.getUserAnswer();
                    byte[] b = ImageUtils.readFile(url);
                    //转为base64传过去
                    String base64 = Base64.encodeBase64String(b);
                    nr.setPicData("data:image/jpeg;base64,"+base64);
                }
            }
        }
        return getDataTable(list);
    }


    /**
     * 图片上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            //String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            Map map = UploadToServer.uploadAvatar(serverAddress,file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", map.get("url"));
            return ajax;
        }
        return AjaxResult.error("上传图片异常");
    }

    /**
     * 提交问卷内容 ==>家长+教职工
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/commit/{dcwjId}")
    public AjaxResult commit(@RequestBody List<SchoolDcwjAn> schoolDcwjAnList,@PathVariable("dcwjId") Long dcwjId) {
        judge(dcwjId, new Date());
        LambdaQueryWrapper<SchoolDcwjRy> rylqw = new LambdaQueryWrapper<>();
        rylqw
                .eq(isNotNull(userInfoUtil.getStudentId()), SchoolDcwjRy::getStudentId, userInfoUtil.getStudentId())
                .eq(isNotNull(userInfoUtil.getTeacherId()), SchoolDcwjRy::getTeacherId, userInfoUtil.getTeacherId())
                .eq(isNotNull(dcwjId), SchoolDcwjRy::getDcwjId, dcwjId);
        SchoolDcwjRy ry = schoolDcwjRyService.getOne(rylqw);
        for (SchoolDcwjAn schoolDcwjAn : schoolDcwjAnList) {
            schoolDcwjAn.setRyId(ry.getId());
        }
        schoolDcwjAnService.saveBatch(schoolDcwjAnList);
        //提交问卷内容之后，修改school_dcwj_ry表中ry_zdzt地状态为已填写（1）
        return AjaxResult.success();
    }

    /**
     * 修改 ==>家长+教职工
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/edit/{dcwjId}")
    public AjaxResult edit(@RequestBody List<SchoolDcwjAn> schoolDcwjAnList, @PathVariable("dcwjId") Long dcwjId) {
        LambdaQueryWrapper<SchoolDcwj> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolDcwj::getId, dcwjId);
        SchoolDcwj schoolDcwj = schoolDcwjService.getOne(lqw);
        //判断当前时间是否在问卷有效期内
        Date date = new Date();
        boolean flag = isEffectiveDate(date, schoolDcwj.getDcwjKssj(), schoolDcwj.getDcwjJssj());
        if (flag == false) {
            new ServiceException("已超出问卷有效期范围，不可修改！");
        }

        LambdaQueryWrapper<SchoolDcwjRy> rylqw = new LambdaQueryWrapper<>();
        rylqw
                .eq(isNotNull(userInfoUtil.getStudentId()), SchoolDcwjRy::getStudentId, userInfoUtil.getStudentId())
                .eq(isNotNull(userInfoUtil.getTeacherId()), SchoolDcwjRy::getTeacherId, userInfoUtil.getTeacherId())
                .eq(isNotNull(dcwjId), SchoolDcwjRy::getDcwjId, dcwjId);
        SchoolDcwjRy ry = schoolDcwjRyService.getOne(rylqw);
        for (SchoolDcwjAn schoolDcwjAn : schoolDcwjAnList) {
            schoolDcwjAn.setRyId(ry.getId());
        }

        LambdaQueryWrapper<SchoolDcwjAn> anLqw = new LambdaQueryWrapper<>();
        anLqw
                .eq(SchoolDcwjAn::getDcwjId, dcwjId)
                .eq(isNotNull(ry.getId()), SchoolDcwjAn::getRyId, ry.getId());
        schoolDcwjAnService.remove(anLqw);
        schoolDcwjAnService.saveBatch(schoolDcwjAnList);
        judge(dcwjId, date);
        return AjaxResult.success();
    }


    /**
     *判断是第一次填写，还是什么... ==>家长+教职工
     */
    public void judge(Long dcwjId, Date date) {
        LambdaQueryWrapper<SchoolDcwjRy> rylqw = new LambdaQueryWrapper<>();
        rylqw
                .eq(isNotNull(userInfoUtil.getStudentId()), SchoolDcwjRy::getStudentId, userInfoUtil.getStudentId())
                .eq(isNotNull(userInfoUtil.getTeacherId()), SchoolDcwjRy::getTeacherId, userInfoUtil.getTeacherId())
                .eq(isNotNull(dcwjId), SchoolDcwjRy::getDcwjId, dcwjId);
        SchoolDcwjRy ry = schoolDcwjRyService.getOne(rylqw);

        //判断是否为第一次填写，如果为第一次填写....，不是第一次填写.....
        LambdaQueryWrapper<SchoolDcwjRy> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(isNotNull(dcwjId), SchoolDcwjRy::getDcwjId, dcwjId)
                .eq(isNotNull(ry.getId()), SchoolDcwjRy::getId, ry.getId());
        SchoolDcwjRy schoolDcwjRy = schoolDcwjRyService.getOne(lqw);
        if (schoolDcwjRy.getRyZdzt().equals(IS)) {
            schoolDcwjRy.setRyUtime(date);
        } else {    //第一次填写
            schoolDcwjRy.setRyZdzt(IS);
            //schoolDcwjRy.setRyUtime(date);
            schoolDcwjRy.setRyCtime(date);
        }
        schoolDcwjRyService.updateById(schoolDcwjRy);
    }

}
