package com.ruoyi.web.controller.buyerapi;

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.BuyerDeptDeviceExcel;
import com.ruoyi.buyerapi.domain.BuyerDeptEmployee;
import com.ruoyi.buyerapi.domain.BuyerDeptEmployeeExcel;
import com.ruoyi.common.annotation.RepeatSubmit;
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.transaction.annotation.Transactional;
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.BuyerDeptDevice;
import com.ruoyi.buyerapi.service.IBuyerDeptDeviceService;
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/device")
public class BuyerDeptDeviceController extends BaseController {
    @Autowired
    private IBuyerDeptDeviceService buyerDeptDeviceService;

    /**
     * 查询设备是否存在
     */
    @ApiOperation(value = "查询设备是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "设备编码", required = true, paramType = "query"),
    })
    @GetMapping("/check")
    public AjaxResult check(BuyerDeptDevice buyerDeptDevice) {
        AjaxResult ajaxResult = new AjaxResult();
        List<BuyerDeptDevice> list = buyerDeptDeviceService.selectBuyerDeptDeviceList(buyerDeptDevice);
        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 = "code", value = "设备编码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "name", value = "设备名称", required = true, paramType = "query"),
            @ApiImplicitParam(name = "originalValue", value = "原值（元）", required = true, paramType = "query"),
            @ApiImplicitParam(name = "crippleValueRate", value = "残值率", required = true, paramType = "query"),
            @ApiImplicitParam(name = "productionUnit", value = "生产单位", required = true, paramType = "query"),
            @ApiImplicitParam(name = "depreciableLife", value = "折旧年限", required = true, paramType = "query"),
            @ApiImplicitParam(name = "buyDate", value = "购入时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "professionalDevice", value = "专用设备(1是2否)", required = true, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "设备状态(1正常2停用)", required = true, paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('buyer:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(BuyerDeptDevice buyerDeptDevice) {
        startPage();
        List<BuyerDeptDevice> list = buyerDeptDeviceService.selectBuyerDeptDeviceList(buyerDeptDevice);
        return getDataTable(list);
    }

    /**
     * 导入数据
     */
    @ApiOperation(value = "导入数据")
    @PostMapping("/importTable")
    public AjaxResult importTable(MultipartFile file) throws Exception {
        ExcelUtil<BuyerDeptDeviceExcel> util = new ExcelUtil<>(BuyerDeptDeviceExcel.class);
        List<BuyerDeptDeviceExcel> buyerDeptEmployeeExcels = util.importExcel(file.getInputStream());
        int i = 0;
        // 数据是否正确的标准
        boolean correct = false;
        for (BuyerDeptDeviceExcel buyerDeptDeviceExcel : buyerDeptEmployeeExcels) {
            i++;
            try {
                BuyerDeptDevice buyerDeptDevice = BeanUtil.copyProperties(buyerDeptDeviceExcel, BuyerDeptDevice.class);
                if (StringUtils.isNotBlank(buyerDeptDevice.getCode()) && StringUtils.isNotBlank(buyerDeptDevice.getName()) && StringUtils.isNotBlank(buyerDeptDevice.getOriginalValue().toString()) &&
                        StringUtils.isNotBlank(buyerDeptDevice.getCrippleValueRate().toString()) && StringUtils.isNotBlank(buyerDeptDevice.getBuyDate().toString()) && StringUtils.isNotBlank(buyerDeptDevice.getDepreciableLife().toString()) &&
                        StringUtils.isNotBlank(buyerDeptDevice.getProfessionalDevice()) && StringUtils.isNotBlank(buyerDeptDevice.getStatus())) {
                    correct = true;
                } else {
                    return AjaxResult.error("第" + i + "条数据有误，请修改");
                }
                // 判断系统是否存在此数据
                BuyerDeptDevice buyerDeptDeviceEntity = new BuyerDeptDevice();
                buyerDeptDeviceEntity.setCode(buyerDeptDevice.getCode());
                buyerDeptDeviceEntity.setName(buyerDeptDevice.getName());
                buyerDeptDeviceEntity.setOriginalValue(buyerDeptDevice.getOriginalValue());
                buyerDeptDeviceEntity.setCrippleValueRate(buyerDeptDevice.getCrippleValueRate());
                buyerDeptDeviceEntity.setBuyDate(buyerDeptDevice.getBuyDate());
                buyerDeptDeviceEntity.setProfessionalDevice(buyerDeptDevice.getProfessionalDevice());
                List<BuyerDeptDevice> list = buyerDeptDeviceService.selectBuyerDeptDeviceList(buyerDeptDeviceEntity);
                if (list.size() > 0) {
                    return AjaxResult.error("第" + i + "条数据系统已存在，请修改");
                }
            } catch (Exception e) {
                return AjaxResult.error("第" + i + "条数据有误，请修改");
            }

        }
        if (correct) {
            for (BuyerDeptDeviceExcel buyerDeptDeviceExcel : buyerDeptEmployeeExcels) {
                BuyerDeptDevice buyerDeptDevice = BeanUtil.copyProperties(buyerDeptDeviceExcel, BuyerDeptDevice.class);
                buyerDeptDevice.setDeptId(SecurityUtils.getCompanyId());
                buyerDeptDevice.setId(IdUtil.simpleUUID());
                buyerDeptDevice.setCreateBy(SecurityUtils.getUsername());
                buyerDeptDevice.setCreateTime(DateUtils.getNowDate());
                try {
                    buyerDeptDeviceService.insertBuyerDeptDevice(buyerDeptDevice);
                } catch (Exception e) {
                    return AjaxResult.error("导入数据有误，请检查");
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 下载模板文件
     */
    @ApiOperation(value = "下载模板文件")
    @PostMapping("/downTemplate")
    public void export(HttpServletResponse response) {
        ExcelUtil<BuyerDeptDeviceExcel> util = new ExcelUtil<BuyerDeptDeviceExcel>(BuyerDeptDeviceExcel.class);
        util.importTemplateExcel(response, "科研设备台账");
    }

    /**
     * 获取企业信息管理设备详细信息
     */
    @ApiOperation(value = "获取企业信息管理设备详细信息")
    @PreAuthorize("@ss.hasPermi('buyer:device:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(buyerDeptDeviceService.selectBuyerDeptDeviceById(id));
    }

    /**
     * 新增企业信息管理设备
     */
    @ApiOperation(value = "新增企业信息管理设备")
    @PreAuthorize("@ss.hasPermi('buyer:device:add')")
    @Log(title = "企业信息管理设备", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@RequestBody BuyerDeptDevice buyerDeptDevice) {
        buyerDeptDevice.setId(IdUtil.simpleUUID());
        buyerDeptDevice.setCreateBy(getUsername());
        return toAjax(buyerDeptDeviceService.insertBuyerDeptDevice(buyerDeptDevice));
    }

    /**
     * 修改企业信息管理设备
     */
    @ApiOperation(value = "修改企业信息管理设备")
    @PreAuthorize("@ss.hasPermi('buyer:device:edit')")
    @Log(title = "企业信息管理设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BuyerDeptDevice buyerDeptDevice) {
        buyerDeptDevice.setUpdateBy(getUsername());
        return toAjax(buyerDeptDeviceService.updateBuyerDeptDevice(buyerDeptDevice));
    }

    /**
     * 删除企业信息管理设备
     */
    @ApiOperation(value = "删除企业信息管理设备")
    @PreAuthorize("@ss.hasPermi('buyer:device:remove')")
    @Log(title = "企业信息管理设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(buyerDeptDeviceService.deleteBuyerDeptDeviceByIds(ids));
    }
}
