package com.ruoyi.web.controller.buyerapi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;

import javax.servlet.http.HttpServletResponse;

import com.ruoyi.buyerapi.domain.BuyerDeptEmployeeExcel;
import com.ruoyi.buyerapi.domain.BuyerDeviceWorkHourExcel;
import com.ruoyi.buyerapi.domain.BuyerDeviceWorkhour;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
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 com.ruoyi.buyerapi.domain.BuyerDeptEmployee;
import com.ruoyi.buyerapi.service.IBuyerDeptEmployeeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 企业信息员工Controller
 *
 * @author ruoyi
 * @date 2022-09-22
 */
@Api(tags = "企业信息员工")
@RestController
@RequestMapping("/buyer/employee")
public class BuyerDeptEmployeeController extends BaseController {
    @Autowired
    private IBuyerDeptEmployeeService buyerDeptEmployeeService;

    /**
     * 检查当前人员是否存在
     */
    @ApiOperation(value = "检查当前人员是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idNumber", value = "证件号", required = true, paramType = "query"),
    })
    @GetMapping("/check")
    public AjaxResult check(BuyerDeptEmployee buyerDeptEmployee) {
        AjaxResult ajaxResult = new AjaxResult();
        List<BuyerDeptEmployee> list = buyerDeptEmployeeService.selectBuyerDeptEmployeeList(buyerDeptEmployee);
        if (list.size() > 0) {
            ajaxResult.put("code", 200);
            ajaxResult.put("repeat", true);
            ajaxResult.put("msg", "证件号已存在，请修改");
            return ajaxResult;
        } else {
            ajaxResult.put("code", 200);
            ajaxResult.put("repeat", false);
            return ajaxResult;
        }
    }

    /**
     * 查询企业信息员工列表
     */
    @ApiOperation(value = "查询企业信息员工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "query"),
            @ApiImplicitParam(name = "idNumber", value = "证件号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "birthdate", value = "出生日期", required = true, paramType = "query"),
            @ApiImplicitParam(name = "college", value = "毕业院校", required = true, paramType = "query"),
            @ApiImplicitParam(name = "major", value = "所学专业", required = true, paramType = "query"),
            @ApiImplicitParam(name = "education", value = "学历", required = true, paramType = "query"),
            @ApiImplicitParam(name = "employeeStatus", value = "员工状态（1在职2离职）", required = true, paramType = "query"),
            @ApiImplicitParam(name = "employeeType", value = "员工类型（1全职2在职）", required = true, paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别", required = true, paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('buyer:employee:list')")
    @GetMapping("/list")
    public TableDataInfo list(BuyerDeptEmployee buyerDeptEmployee) {
        startPage();
        List<BuyerDeptEmployee> list = buyerDeptEmployeeService.selectBuyerDeptEmployeeList(buyerDeptEmployee);
        return getDataTable(list);
    }

    /**
     * 查询项目员工列表
     */
    @ApiOperation(value = "查询项目员工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startDate", value = "开始日期", required = true, paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束日期", required = true, paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('buyer:employee:list')")
    @GetMapping("/lists")
    public AjaxResult lists(BuyerDeptEmployee buyerDeptEmployee) {
        AjaxResult ajaxResult = new AjaxResult();
        if (buyerDeptEmployee.getStartDate() == null) {
            buyerDeptEmployee.setStartDate(DateUtils.getNowDate());
        }
        List<BuyerDeptEmployee> list = buyerDeptEmployeeService.selectBuyerDeptEmployeeLists(buyerDeptEmployee);
        ajaxResult.put("data", list);
        return ajaxResult;
    }

    /**
     * 导入数据
     */
    @ApiOperation(value = "导入数据")
    @PostMapping("/importTable")
    public AjaxResult importTable(MultipartFile file) throws Exception {
        ExcelUtil<BuyerDeptEmployeeExcel> util = new ExcelUtil<>(BuyerDeptEmployeeExcel.class);
        List<BuyerDeptEmployeeExcel> buyerDeptEmployeeExcels = util.importExcel(file.getInputStream());
        int i = 0;
        // 数据是否正确的标准
        boolean correct = false;
        for (BuyerDeptEmployeeExcel buyerDeptEmployeeExcel : buyerDeptEmployeeExcels) {
            i++;
            BuyerDeptEmployee buyerDeptEmployee = BeanUtil.copyProperties(buyerDeptEmployeeExcel, BuyerDeptEmployee.class);
            try {
                if (StringUtils.isNotBlank(buyerDeptEmployee.getName()) && StringUtils.isNotBlank(buyerDeptEmployee.getIdNumber())
                        && StringUtils.isNotBlank(buyerDeptEmployee.getSex()) && StringUtils.isNotBlank(buyerDeptEmployee.getEmployeeStatus())) {
                    correct = true;
                } else {
                    return AjaxResult.error("第" + i + "条数据有误，请修改");
                }
            } catch (Exception e) {
                return AjaxResult.error("第" + i + "条数据有误，请修改");
            }
        }
        if (correct) {
            for (BuyerDeptEmployeeExcel buyerDeptEmployeeExcel : buyerDeptEmployeeExcels) {
                BuyerDeptEmployee buyerDeptEmployee = BeanUtil.copyProperties(buyerDeptEmployeeExcel, BuyerDeptEmployee.class);
                // 重复数据直接跳过
                List<BuyerDeptEmployee> buyerDeptEmployees = buyerDeptEmployeeService.selectBuyerDeptEmployeeList(buyerDeptEmployee);
                if (buyerDeptEmployees.size() == 0) {
                    buyerDeptEmployee.setDeptId(SecurityUtils.getCompanyId());
                    buyerDeptEmployee.setId(IdUtil.simpleUUID());
                    buyerDeptEmployee.setCreateBy(SecurityUtils.getUsername());
                    buyerDeptEmployee.setCreateTime(DateUtils.getNowDate());
                    try {
                        buyerDeptEmployeeService.insertBuyerDeptEmployee(buyerDeptEmployee);
                    } catch (Exception e) {
                        return AjaxResult.error("导入数据有误，请检查");
                    }
                } else {
                    continue;
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 下载模板文件
     */
    @ApiOperation(value = "下载模板文件")
    @PostMapping("/downTemplate")
    public void downTemplate(HttpServletResponse response) {
        ExcelUtil<BuyerDeptEmployeeExcel> util = new ExcelUtil<BuyerDeptEmployeeExcel>(BuyerDeptEmployeeExcel.class);
        List<BuyerDeptEmployeeExcel> list = new ArrayList<>();
        BuyerDeptEmployeeExcel bean = new BuyerDeptEmployeeExcel();
        bean.setName("张三");
        bean.setSex("0");
        bean.setIdNumber("500xxxxxxxxxxxxxxx");
        bean.setBirthdate("2022-12-12");
        bean.setEducation("（小学/初中/中专/大专/本科/硕士/博士）中选择");
        bean.setCollege("清华大学");
        bean.setMajor("计算机专业");
        bean.setDept("xxx部门");
        bean.setPost("工程师");
        bean.setProfessional("高级工程师");
        bean.setHiredate("2022-12-12");
        bean.setEmployeeType("1");
        bean.setEmployeeStatus("2");
        bean.setResignationDate("2022-12-12");
        list.add(bean);
        util.importTemplateExcel(response, list, "企业人员台账");
    }

    /**
     * 获取企业信息员工详细信息
     */
    @ApiOperation(value = "获取企业信息员工详细信息")
    @PreAuthorize("@ss.hasPermi('buyer:employee:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(buyerDeptEmployeeService.selectBuyerDeptEmployeeById(id));
    }

    /**
     * 新增企业信息员工
     */
    @ApiOperation(value = "新增企业信息员工")
    @PreAuthorize("@ss.hasPermi('buyer:employee:add')")
    @Log(title = "企业信息员工", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BuyerDeptEmployee buyerDeptEmployee) {
        buyerDeptEmployee.setId(IdUtil.simpleUUID());
        buyerDeptEmployee.setCreateBy(getUsername());
        return toAjax(buyerDeptEmployeeService.insertBuyerDeptEmployee(buyerDeptEmployee));
    }

    /**
     * 修改企业信息员工
     */
    @ApiOperation(value = "修改企业信息员工")
    @PreAuthorize("@ss.hasPermi('buyer:employee:edit')")
    @Log(title = "企业信息员工", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BuyerDeptEmployee buyerDeptEmployee) {
        buyerDeptEmployee.setUpdateBy(getUsername());
        return toAjax(buyerDeptEmployeeService.updateBuyerDeptEmployee(buyerDeptEmployee));
    }

    /**
     * 删除企业信息员工
     */
    @ApiOperation(value = "删除企业信息员工")
    @PreAuthorize("@ss.hasPermi('buyer:employee:remove')")
    @Log(title = "企业信息员工", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(buyerDeptEmployeeService.deleteBuyerDeptEmployeeByIds(ids));
    }
}
