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.StudentCertUpload;
import com.winsun.bean.SysUser;
import com.winsun.mapper.StudentCertUploadMapper;
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("/studentDwkVerify")
public class StudentDwkVerifyController extends BaseController {

    @Autowired
    private StudentCertUploadMapper studentCertUploadMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;

    private static String PATH1 = "StudentCertUpload1";
    private static String PATH2 = "StudentCertUpload2";
    private static String PATH3 = "StudentCertUpload3";
    private static String PATH4 = "StudentCertUpload4";
    /**
     * 大王卡证件稽核信息添加
     *
     * @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").toString();
        String substName = hashMap.get("substName").toString();
        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").toString());
            managerKpi.setRechargeNum(Integer.valueOf(hashMap.get("rechargeNum").toString()));
            managerKpi.setRechargeWage(Integer.valueOf(hashMap.get("rechargeWage").toString()));
            managerKpi.setKpi(Integer.valueOf(hashMap.get("kpi").toString()));
            managerKpi.setKpiWage(Integer.valueOf(hashMap.get("kpiWage").toString()));
            managerKpi.setWage(Integer.valueOf(hashMap.get("wage").toString()));
            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 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<StudentCertUpload> wrapper = new EntityWrapper<>();
        StudentCertUpload studentCard = new StudentCertUpload();
        studentCard.setAuditState(state);
        wrapper.in("id", list);
        studentCertUploadMapper.update(studentCard,wrapper);
        return ResponseData.success("修改成功！");
    }

    /**
     *
     * @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<StudentCertUpload>> 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();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        Page<StudentCertUpload> page = new Page<>(pageNo, pageSize);
        Wrapper<StudentCertUpload> 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<StudentCertUpload> aPackage = studentCertUploadMapper.selectPage(page, studentCardWrapper);
        page.setRecords(aPackage);
        return ResponseData.success(page, "查询成功！");
    }

    /**
     * 学生证证件照上传
     * @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 idCard,String userName, String orderPhone, String linkPhone,
                                              String file1,String file2,String file3,String file4) {

        Wrapper<StudentCertUpload> wrapper = new EntityWrapper<>();
        wrapper.eq("id", idCard);
        StudentCertUpload student = new StudentCertUpload();
        student.setUserName(userName);
        student.setOrderPhone(orderPhone);
        student.setLinkPhone(linkPhone);
        if(StringUtils.isNotBlank(file1)){
            String file01 = PicturesUtil.uploadPictures(file1, "",PATH1);
            student.setStudentCardUrl(file01);
        }
        if(StringUtils.isNotBlank(file2)){
            String file02 = PicturesUtil.uploadPictures(file2, "",PATH2);
            student.setSchoolCardUrl(file02);
        }
        if(StringUtils.isNotBlank(file3)){
            String file03 = PicturesUtil.uploadPictures(file3, "",PATH3);
            student.setNoticeUrl(file03);
        }
        if(StringUtils.isNotBlank(file4)){
            String file04 = PicturesUtil.uploadPictures(file4, "",PATH4);
            student.setOtherUrl(file04);
        }
        Integer integer1 = studentCertUploadMapper.update(student,wrapper);
        if(integer1==1){
            return ResponseData.success("上传成功！");
        }
        return ResponseData.error("上传失败！");
    }

    /**
     *
     * @param ids
     * @return
     */
    @Permission(menuname = "查询大王卡证件稽核信息", value = "queryById", method = RequestMethod.POST)
    public ResponseData<StudentCertUpload> 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<StudentCertUpload> studentCardWrapper = new EntityWrapper<>();
        studentCardWrapper.eq(StringUtils.isNotBlank(id),"id",id);
        StudentCertUpload studentCard = studentCertUploadMapper.selectList(studentCardWrapper).get(0);

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

    /**
     *
     * @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<StudentCertUpload> 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<StudentCertUpload> studentCards = studentCertUploadMapper.selectList(studentCardWrapper);
        List<Map<String, Object>> list = new LinkedList<>();
        for (StudentCertUpload 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", "无效");
            if(null != studentCard.getAuditDate()){
                map.put("uploadDate", DateUtil.formatDate(studentCard.getAuditDate(),"yyyy-mm-dd"));
            }else {
                map.put("uploadDate", "");
            }
            map.put("agentBusinessman", studentCard.getAgentBusinessman());

            list.add(map);
        }
        List<Integer> list1 = new ArrayList<>();
        list1.add(4500);
        list1.add(4500);
        list1.add(4500);
        list1.add(4500);
        list1.add(4500);
        list1.add(4500);
        list1.add(4500);
        list1.add(4500);
        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook2(ExcelDealUtils.studentCertExcel("大王卡证件稽核清单"), 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);
        }
    }

}
