package com.liang.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liang.common.JsonTool;
import com.liang.common.base.BaseResult;
import com.liang.common.utils.DateUtil;
import com.liang.entity.BasePerson;
import com.liang.entity.SysLsUserEntity;

import com.liang.service.BaseAreaService;
import com.liang.service.BaseEducationService;
import com.liang.service.LsUserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Delete;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.liang.common.base.BaseController.RESULT_ROWS;
import static com.liang.common.base.BaseController.RESULT_TOTAL;

/**
 * @Author ly
 * @Date 2024/4/3 9:42
 * @Version 1.0
 */
@Controller
@RequestMapping("/lsUser")
public class LsUserController {

    @Resource
    private LsUserService lsUserService;
    @Resource
    private BaseEducationService baseEducationService;

    // 允许的表格文件扩展名列表
    private final List<String> allowedExtensions = Arrays.asList("xls", "xlsx", "csv");


    @ApiOperation(value = "页面初始化", notes = "页面初始化")
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public String init( Model model) {
        List<Map<String, String>> xlList = baseEducationService.getEducationList();
        model.addAttribute("xlList", xlList);
        return "lsuserinfo/list";
    }
    /**
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/all",method = RequestMethod.GET)
    public BaseResult UserAll(@RequestParam("page") Integer pageNum,
                              @RequestParam("limit") Integer pageSize,
                              @RequestParam(required = false, defaultValue = "", value = "xm") String xm,
                              @RequestParam(required = false, defaultValue = "", value = "zt") Integer zt,
                              @RequestParam(required = false, defaultValue = "", value = "xl") String xl,
                              @RequestParam(required = false, defaultValue = "", value = "sfzh") String sfzh){
        Map<String, String> paraMap = new HashMap<>();
        PageHelper.startPage(pageNum, pageSize);
        if (zt == null){
            paraMap.put("xm", xm);
            paraMap.put("xl",xl);
            paraMap.put("sfzh",sfzh);
            List<SysLsUserEntity> list = lsUserService.UserAll(paraMap);
            PageInfo<SysLsUserEntity> pageinfo = new PageInfo<>(list);
            // 取出查询结果
            List<SysLsUserEntity> rows = pageinfo.getList();
            int total = (int) pageinfo.getTotal();
            Map<String, Object> result = new HashMap<>();
            result.put(RESULT_ROWS, rows);
            result.put(RESULT_TOTAL, total);
            result.put("list",list);
            return BaseResult.success(result);
        }
        paraMap.put("xm", xm);
        paraMap.put("xl",xl);
        paraMap.put("zt",String.valueOf(zt));
        List<SysLsUserEntity> list = lsUserService.UserAll(paraMap);
        PageInfo<SysLsUserEntity> pageinfo = new PageInfo<>(list);
        // 取出查询结果
        List<SysLsUserEntity> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);
        result.put("list",list);
        return BaseResult.success(result);
    }



    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model) {

        List<Map<String, String>> xlList = baseEducationService.getEducationList();

        model.addAttribute("xlList", xlList);

        return "lsuserinfo/add";
    }

    @RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
    public String forEdit(@PathVariable Integer id){
        return "lsuserinfo/add";
    }
    /**
     * 保存数据
     * @param
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public BaseResult saveOperLog(@RequestBody SysLsUserEntity sysLsUserEntity) {

        Map<String, String>map = new HashMap<>();
        map.put("sfzh",sysLsUserEntity.getSfzh());
        List<SysLsUserEntity> list = lsUserService.getUserxm(map);

        if (list.size() == 0) {
            SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(System.currentTimeMillis());
            sysLsUserEntity.setCjsj(formatter.format(date));

            int num  = lsUserService.saveOperLog(sysLsUserEntity);
            return BaseResult.success("新增临时人员成功!");
        }
            return BaseResult.failure("新建临时人员失败，该人员已存在!");
    }

    @RequestMapping(value="/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult batchDelete(@RequestBody SysLsUserEntity sysLsUserEntity,@PathVariable Integer id){
        sysLsUserEntity.setZt(lsUserService.getUserId(id).getZt());
        sysLsUserEntity.setId(id);
        sysLsUserEntity.setX(1);
        boolean a = lsUserService.upDate(sysLsUserEntity);
        if (a != true){
            return BaseResult.failure("修改失败");
        }
        return BaseResult.success("修改成功");
    }
    /**
     * 删除数据
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult delete (@PathVariable Integer id){

        SysLsUserEntity sysLsUserEntity = lsUserService.getUserId(id);
        sysLsUserEntity.setX(0);
        boolean flag = lsUserService.upDate(sysLsUserEntity);
        if (flag) {
            return BaseResult.success("删除成功");
        } else {
            return BaseResult.failure("删除失败");
        }

    }

    /**
     * 修改数据
     * @param
     * @return
     */
    @RequestMapping (value = "up/{id}",method = RequestMethod.GET)
    public  String  updates(Model model,@PathVariable Integer id){

        SysLsUserEntity sysLsUserEntit = lsUserService.getUserId(id);

        model.addAttribute("ls",sysLsUserEntit);
        List<Map<String, String>> xlList = baseEducationService.getEducationList();

        model.addAttribute("xlList", xlList);

        return "lsuserinfo/adds";
    }


    @RequestMapping(value = "/getId/{id}",method = RequestMethod.GET)
    @ResponseBody
    public BaseResult getId(Model model,@PathVariable Integer id){
        if (id != null){
            SysLsUserEntity sysLsUserEntity = lsUserService.getUserId(id);
            Map<String, Object> result = new HashMap<>();
            result.put(RESULT_ROWS, sysLsUserEntity);
            model.addAttribute("sy",sysLsUserEntity);


            return BaseResult.success(result);
        }
        return BaseResult.failure("该人员不存在");
    }

    @PostMapping("/file")
    @ResponseBody
    public BaseResult handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()){
            return BaseResult.failure("上传文件异常，上传失败！");
        }
        List<SysLsUserEntity> lists = new ArrayList<>();
        Integer h = 0;
        try{
            // 验证文件类型

            DateUtil dateUtil = new DateUtil();
            String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename());
            if (!allowedExtensions.contains(fileExtension.toLowerCase())) {
                return BaseResult.failure("只允许上传 Excel文件");
            }
            // 开始解析这个文件
            List<List<String>> spreadsheetData = parseSpreadsheet(file.getInputStream(), fileExtension);
            System.out.println(spreadsheetData);
            // 循环比较 spreadsheetData 中的 长度 是否与 各个元素相等
            for (int i = 0;i<spreadsheetData.size();i++){
                SysLsUserEntity sysLsUserEntity = new SysLsUserEntity();
                if (spreadsheetData.get(i).size()!= spreadsheetData.get(0).size()){
                    sysLsUserEntity.setXm(String.valueOf(i+1));
                    sysLsUserEntity.setXmfzr("请将第"+(i+1)+"条数据补充完整");
                    lists.add(sysLsUserEntity);
                    spreadsheetData.remove(i);
                }
                continue;
            }
            spreadsheetData.remove(0);
            List<SysLsUserEntity> list = new ArrayList<>();
            for (List<String> row : spreadsheetData) {
                SysLsUserEntity employee = new SysLsUserEntity();
                // 设置员工信息
                employee.setXm(row.get(0));
                employee.setXb(row.get(1));
                employee.setPhone(row.get(2));
                employee.setSfzh(row.get(3));
                employee.setXl(row.get(4));
                employee.setByxy(row.get(5));
                employee.setZy(row.get(6));
                employee.setQpsj(dateUtil.convertDate(row.get(7)));
                employee.setDqsj(dateUtil.convertDate(row.get(8)));
                System.out.println(row.get(9));
                employee.setGznr(row.get(9));
                // 将对象添加到列表中
                list.add(employee);
            }
            for(int i = 0; i<list.size();i++){
                SysLsUserEntity sysLsUserEntity = new SysLsUserEntity();
                // 校验合同起始时间和到期时间是否在三个月 内
                if (dateUtil.areDatesWithinThreeMonths(list.get(i).getDqsj(), list.get(i).getQpsj()) !=true) {
                    sysLsUserEntity.setXm(list.get(i).getXm());
                    // xmfzr 这个字段存储未能存储原因
                    sysLsUserEntity.setXmfzr("聘用日期不能大于三个月");
                    sysLsUserEntity.setSfzh(list.get(i).getSfzh());
                    sysLsUserEntity.setDqsj(list.get(i).getDqsj());
                    sysLsUserEntity.setQpsj(list.get(i).getQpsj());
                    if (list.get(i).getXm().isEmpty() && list.get(i).getSfzh().isEmpty()){
                        continue;
                    }
                    lists.add(sysLsUserEntity);
                    continue;
                }
                // 校验当前传入的 身份证号 是否在数据库中存在
                if (lsUserService.jy(list.get(i).getSfzh()) != true){
                    sysLsUserEntity.setXm(list.get(i).getXm());
                    sysLsUserEntity.setSfzh(list.get(i).getSfzh());
                    sysLsUserEntity.setDqsj(list.get(i).getDqsj());
                    sysLsUserEntity.setQpsj(list.get(i).getQpsj());
                    // xmfzr 这个字段存储未能存储原因
                    sysLsUserEntity.setXmfzr("该人员身份证已存在");
                    if (list.get(i).getXm().isEmpty() && list.get(i).getSfzh().isEmpty()){
                        continue;
                    }
                    lists.add(sysLsUserEntity);

                    continue;
                }
               Integer mum = lsUserService.saveOperLog(list.get(i));
               if (mum > 0){
                   h++;
                   // 循环比较 spreadsheetData 中的 长度 是否与 各个元素相等
               }
            }
        }catch (Exception a){
            a.printStackTrace();
            h++;
        }
        // 获取文件名后缀
        if (h == 0){
            return BaseResult.failure(43,"成员录入失败,人员已存在！");
        }
        return BaseResult.success("成员录入成功",lists);


    }
    private List<List<String>> parseSpreadsheet(InputStream inputStream, String fileExtension) throws IOException {
        Workbook workbook = null;
        if (fileExtension.equalsIgnoreCase("xlsx")) {
            workbook = new XSSFWorkbook(inputStream);
        } else if (fileExtension.equalsIgnoreCase("xls")) {
            throw new IOException("上传的Excel文件格式不支持，请上传xlsx格式文件。");
        } else if (fileExtension.equalsIgnoreCase("csv")) {
            throw new IOException("上传的文件是CSV格式，当前不支持解析，请上传Excel文件。");
        }

        List<List<String>> spreadsheetData = new ArrayList<>();
        if (workbook != null) {
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = sheet.iterator();

            while (iterator.hasNext()) {
                Row currentRow = iterator.next();
                Iterator<Cell> cellIterator = currentRow.iterator();

                List<String> rowData = new ArrayList<>();
                while (cellIterator.hasNext()) {
                    Cell currentCell = cellIterator.next();
                    rowData.add(currentCell.toString());
                }

                spreadsheetData.add(rowData);
            }

            workbook.close();
        }

        return spreadsheetData;
    }


}
