package com.winsun.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.auth.core.util.DateUtil;
import com.winsun.auth.core.util.IOUtils;
import com.winsun.bean.StudentCard;
import com.winsun.bean.SysUser;
import com.winsun.mapper.StudentCardMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.utils.ExcelDealUtils;
import com.winsun.utils.PicturesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 〈学生不限量证件〉
 *
 * @author PXL
 * @create 2020/5/20 10:19
 */
@Slf4j
@RestController
@RequestMapping("/studentCardVerify")
public class StudentCardVerifyController extends BaseController {

    @Autowired
    private StudentCardMapper studentCardMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;

    private static String PATH1 = "StudentCard1";
    private static String PATH2 = "StudentCard2";
    private static String PATH3 = "StudentCard3";
    private static String PATH4 = "StudentCard4";
    /**
     * 学生不限量证件信息添加
     *
     * @param lzKpi 添加对象json字符串
     * @return
     */
    @Permission(menuname = "添加学生不限量证件信息", value = "insert", method = RequestMethod.POST)
    public ResponseData<String> insertProduct(@RequestParam("lzKpi") String lzKpi) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        HashMap hashMap = JSON.parseObject(lzKpi, HashMap.class);
        Wrapper<SysUser> sysWrapper = new EntityWrapper<>();
        String account = hashMap.get("account")+"";
        String substName = hashMap.get("substName")+"";
        sysWrapper.eq(StringUtils.isNotBlank(account),"account",account);
        sysWrapper.eq(StringUtils.isNotBlank(substName),"name",substName);
        List<SysUser> sysUserList = sysUserMapper.selectList(sysWrapper);
        if(sysUserList.size()>0){
            /*ManagerKpi managerKpi = new ManagerKpi();
            managerKpi.setUserId(Integer.valueOf(sysUserList.get(0).getId()));
            managerKpi.setMonth(hashMap.get("month")+"");
            managerKpi.setRechargeNum(Integer.valueOf(hashMap.get("rechargeNum")+""));
            managerKpi.setRechargeWage(Integer.valueOf(hashMap.get("rechargeWage")+""));
            managerKpi.setKpi(Integer.valueOf(hashMap.get("kpi")+""));
            managerKpi.setKpiWage(Integer.valueOf(hashMap.get("kpiWage")+""));
            managerKpi.setWage(Integer.valueOf(hashMap.get("wage")+""));
            managerKpiMapper.insert(managerKpi);*/
            return ResponseData.success("添加成功！");
        }
        return ResponseData.error("账号不存在?");
    }

    /**
     * 学生不限量证件删除
     * @param id 需要删除的id
     * @return
     */
    @Permission(menuname = "删除正则信息", value = "delete", method = RequestMethod.POST)
    public ResponseData<String> deleteProduct(@RequestParam(name="id", required = false) String id,@RequestParam(name="isdel", required = false) String isdel) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        //Wrapper wrapper = new EntityWrapper<>();
        //wrapper.eq(StringUtils.isNotBlank(id),"id", id);
        //Map<String, Object> dataMapping = new HashMap<>();
        //dataMapping.put("is_del", isdel);
        //lzKpiMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if(StringUtils.isNotBlank(id)){
            /*lzWageMpapper.deleteById(id);*/
            return ResponseData.success("操作成功！");
        }
        return ResponseData.error("删除id不能为空!");
    }

    /**
     * 学生证证件照上传
     * @param idCard
     * @param userName
     * @param orderPhone
     * @param linkPhone
     * @param file1
     * @param file2
     * @param file3
     * @param file4
     * @return
     */
    @RequestMapping(value = "uploadCard", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData<String> uploadStuCard(String userName, String orderPhone, String linkPhone,
                                              String idCard,String file1,String file2,String file3,String file4) {

        Wrapper<StudentCard> wrapper = new EntityWrapper<>();
        wrapper.eq("order_phone", orderPhone);
        wrapper.eq("id_card", idCard);
        StudentCard student = new StudentCard();
        student.setUserName(userName);
        student.setOrderPhone(orderPhone);
        student.setLinkPhone(linkPhone);
        student.setIdCard(idCard);
        student.setUploadDate(new Date());
        if(StringUtils.isNotBlank(file1)){
            String file01 = PicturesUtil.uploadPictures(file1, "",PATH1);
            student.setStudentCardUrl(file01);
        }
        if(StringUtils.isNotBlank(file2)){
            String file02 = PicturesUtil.uploadPictures(file2,"",PATH2);
            student.setOtherImgUrl1(file02);
        }
        if(StringUtils.isNotBlank(file3)){
            String file03 = PicturesUtil.uploadPictures(file3, "",PATH3);
            student.setOtherImgUrl2(file03);
        }
        if(StringUtils.isNotBlank(file4)){
            String file04 = PicturesUtil.uploadPictures(file4, "",PATH4);
            student.setOtherImgUrl3(file04);
        }
        Integer integer1 = studentCardMapper.update(student,wrapper);
        if(integer1==1){
            return ResponseData.success("更新成功！");
        }else{
            student.setIsFirstUpload(1);
            student.setFirstUploadDate(new Date());
            studentCardMapper.insert(student);
            return ResponseData.success("上传成功！");
        }
    }

    /**
     * 修改学生不限量证件状态
     * @param ids
     * @param state
     * @return
     */
    @Permission(menuname = "修改学生不限量证件信息", value = "update", method = RequestMethod.POST)
    public ResponseData<String> updateProduct(@RequestParam("ids") String ids,@RequestParam("state") Integer state) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "业务稽核","稽核员"))) {
            return ResponseData.error("无数据权限");
        }
        List<String> list1 = Arrays.asList(ids.split(",")); //[a, b, c]
        List<Integer> list = new ArrayList<>();
        for (String s : list1) {
            list.add(Integer.valueOf(s));
        }
        Wrapper<StudentCard> wrapper = new EntityWrapper<>();
        StudentCard studentCard = new StudentCard();
        studentCard.setAuditState(state);
        wrapper.in("id", list);
        studentCardMapper.update(studentCard,wrapper);
        return ResponseData.success("修改成功！");
    }

    /**
     *
     * @param ids
     * @return
     */
    @Permission(menuname = "查询学生不限量证件信息", value = "queryById", method = RequestMethod.POST)
    public ResponseData<StudentCard> queryById(@RequestParam("ids") String ids) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        List<String> list1 = Arrays.asList(ids.split(",")); //[a, b, c]
        String id = "";
        if(list1.size()>0){
            id = list1.get(0);
        }else{
            return ResponseData.error("查询ID不能为空！！！");
        }
        Wrapper<StudentCard> studentCardWrapper = new EntityWrapper<>();
        studentCardWrapper.eq(StringUtils.isNotBlank(id),"id",id);
        StudentCard studentCard = studentCardMapper.selectList(studentCardWrapper).get(0);

        return ResponseData.success(studentCard, "查询成功！");
    }

    /**
     * @param userName
     * @param orderPhone
     * @param linkPhone
     * @param auditName
     * @param auditState
     * @param uploadDate
     * @param auditDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Permission(menuname = "查询学生证件信息", value = "list", method = RequestMethod.POST)
    public ResponseData<Page<StudentCard>> listProduct(
            @RequestParam(name = "userName", required = false) String userName,
            @RequestParam(name = "orderPhone", required = false) String orderPhone,
            @RequestParam(name = "linkPhone", required = false) String linkPhone,
            @RequestParam(name = "auditName", required = false) String auditName,
            @RequestParam(name = "auditState", required = false) String auditState,
            @RequestParam(name = "uploadDate", required = false) String uploadDate,
            @RequestParam(name = "auditDate", required = false) String auditDate,
            @RequestParam(name = "pageNo") int pageNo,
            @RequestParam(name = "pageSize") int pageSize) {
        ShiroUser user = getShiroUser();

        Page<StudentCard> page = new Page<>(pageNo, pageSize);
        Wrapper<StudentCard> studentCardWrapper = new EntityWrapper<>();
        studentCardWrapper.like(StringUtils.isNotBlank(userName),"user_name",userName, SqlLike.DEFAULT);
        studentCardWrapper.like(StringUtils.isNotBlank(auditName),"audit_name",auditName, SqlLike.DEFAULT);
        studentCardWrapper.eq(StringUtils.isNotBlank(orderPhone),"order_phone",orderPhone);
        studentCardWrapper.eq(StringUtils.isNotBlank(linkPhone),"link_phone",linkPhone);
        studentCardWrapper.eq(StringUtils.isNotBlank(auditState),"audit_state",auditState);
//        studentCardWrapper.orderBy("audit_date",false);
        studentCardWrapper.orderBy("upload_date", false);
        if(StringUtils.isNotBlank(uploadDate)){
            String[] dates = uploadDate.split("\\,");
            if(!uploadDate.equals(",")){
                studentCardWrapper.between("upload_date",dates[0],dates[1]);
            }
        }
        if(StringUtils.isNotBlank(auditDate)){
            String[] dates = auditDate.split("\\,");
            if(!auditDate.equals(",")){
                studentCardWrapper.between("audit_date",dates[0],dates[1]);
            }
        }
        List<StudentCard> aPackage = studentCardMapper.selectPage(page, studentCardWrapper);
        page.setRecords(aPackage);
        return ResponseData.success(page, "查询成功！");
    }

    /**
     *
     * @param auditState
     * @throws IOException
     */
    @Permission(menuname = "导出学生不限量证件信息", value = "excelOut", method = RequestMethod.POST)
    public void excelOut(@RequestParam(name = "userName", required = false) String userName,
                         @RequestParam(name = "orderPhone", required = false) String orderPhone,
                         @RequestParam(name = "linkPhone", required = false) String linkPhone,
                         @RequestParam(name = "auditName", required = false) String auditName,
                         @RequestParam(name = "auditState", required = false) String auditState,
                         @RequestParam(name = "uploadDate", required = false) String uploadDate,
                         @RequestParam(name = "auditDate", required = false) String auditDate)  throws IOException {

        Wrapper<StudentCard> studentCardWrapper = new EntityWrapper<>();
        studentCardWrapper.like(StringUtils.isNotBlank(userName),"user_name",userName, SqlLike.DEFAULT);
        studentCardWrapper.like(StringUtils.isNotBlank(auditName),"audit_name",auditName, SqlLike.DEFAULT);
        studentCardWrapper.eq(StringUtils.isNotBlank(orderPhone),"order_phone",orderPhone);
        studentCardWrapper.eq(StringUtils.isNotBlank(linkPhone),"link_phone",linkPhone);
        studentCardWrapper.eq(StringUtils.isNotBlank(auditState),"audit_state",auditState);
        studentCardWrapper.orderBy("audit_date",false);
        if(StringUtils.isNotBlank(uploadDate)){
            String[] dates = uploadDate.split("\\,");
            if(!uploadDate.equals(",")){
                studentCardWrapper.between("upload_date",dates[0],dates[1]);
            }
        }
        if(StringUtils.isNotBlank(auditDate)){
            String[] dates = auditDate.split("\\,");
            if(!auditDate.equals(",")){
                studentCardWrapper.between("audit_date",dates[0],dates[1]);
            }
        }
        List<StudentCard> studentCards = studentCardMapper.selectList(studentCardWrapper);
        List<Map<String, Object>> list = new LinkedList<>();
        for (StudentCard studentCard : studentCards) {
            Map<String, Object> map = new HashMap<>();
            map.put("userName", studentCard.getUserName());
            map.put("orderPhone", studentCard.getOrderPhone());
            map.put("linkPhone", studentCard.getLinkPhone());
            map.put("auditName", studentCard.getAuditName());
            if(null != studentCard.getAuditDate()){
                map.put("auditDate", DateUtil.formatDate(studentCard.getAuditDate(),"yyyy-mm-dd"));
            }else {
                map.put("auditDate", "");
            }
            Integer state = studentCard.getAuditState();
            if(state == 1)
                map.put("auditState", "未审核");
            else if (state == 2)
                map.put("auditState", "审核通过");
            else if (state == 3)
                map.put("auditState", "审核不通过");
            else if (state == 4)
                map.put("auditState", "无效");
            map.put("county", studentCard.getCounty());
            map.put("school", studentCard.getSchool());
            if(StringUtils.isNotBlank(studentCard.getIsComboMoney49()+"")){
                map.put("isComboMoney49", studentCard.getIsComboMoney49()==1?"是":"否");
            }else {
                map.put("isComboMoney49", "");
            }
            if(StringUtils.isNotBlank(studentCard.getIsFull()+"")){
                map.put("isFull", studentCard.getIsFull()==1?"是":"否");
            }else {
                map.put("isFull", "");
            }
            if(StringUtils.isNotBlank(studentCard.getIsClear()+"")){
                map.put("isClear", studentCard.getIsClear()==1?"是":"否");
            }else {
                map.put("isClear", "");
            }
            if(StringUtils.isNotBlank(studentCard.getIsUnderYears()+"")){
                map.put("isUnderYears", studentCard.getIsUnderYears()==1?"是":"否");
            }else {
                map.put("isUnderYears", "");
            }
            if(StringUtils.isNotBlank(studentCard.getIsStudentAccordance()+"")){
                map.put("isStudentAccordance", studentCard.getIsStudentAccordance()==1?"是":"否");
            }else {
                map.put("isStudentAccordance", "");
            }
            if(StringUtils.isNotBlank(studentCard.getIsSchoolAccordance()+"")){
                map.put("isSchoolAccordance", studentCard.getIsSchoolAccordance()==1?"是":"否");
            }else {
                map.put("isSchoolAccordance", "");
            }
            if(StringUtils.isNotBlank(studentCard.getIsComboMoney49()+"")){
                map.put("isUploadBeforeActivate", studentCard.getIsUploadBeforeActivate()==1?"是":"否");
            }else {
                map.put("isUploadBeforeActivate", "");
            }
            if(null != studentCard.getUploadDate()){
                map.put("uploadDate", DateUtil.formatDate(studentCard.getUploadDate(),"yyyy-mm-dd"));
            }else {
                map.put("uploadDate", "");
            }
            if(null != studentCard.getCrnActivateDate()){
                map.put("crnActivateDate", DateUtil.formatDate(studentCard.getCrnActivateDate(),"yyyy-mm-dd"));
            }else {
                map.put("crnActivateDate", "");
            }
            if(StringUtils.isNotBlank(studentCard.getIsFirstUpload()+"")){
                map.put("isFirstUpload", studentCard.getIsFirstUpload()==1?"是":"否");
            }else {
                map.put("isFirstUpload", "");
            }
            map.put("agentBusinessman", studentCard.getAgentBusinessman());
            list.add(map);
        }
        List<Integer> list1 = new ArrayList<>();
        list1.add(2500); list1.add(4500); list1.add(4500); list1.add(4500);
        list1.add(4500); list1.add(4500); list1.add(4500); list1.add(4500);
        list1.add(4500); list1.add(4500); list1.add(4500); list1.add(4500);
        list1.add(4500); list1.add(4500); list1.add(4500); list1.add(4500);
        list1.add(4500); list1.add(4500); list1.add(2500);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook2(ExcelDealUtils.studentCardExcel("学生不限量证件清单"), list,list1);
        try {
            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
    }

}
