package com.ruoyi.web.modules.industryservice.controller;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StreamUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.modules.industryservice.domain.BizLivestockOwnershipHousehold;
import com.ruoyi.web.modules.industryservice.service.IBizLivestockOwnershipHouseholdService;
import com.ruoyi.web.modules.industryservice.support.LivestockOwnershipHouseholdExcelParser;

/**
 * 有无畜户数据填报 REST。
 * <p>Base：{@code /dataModel/livestockOwnershipHousehold}；权限 {@code dataModel:livestockOwnershipHousehold:*}</p>
 */
@RestController
@RequestMapping("/dataModel/livestockOwnershipHousehold")
public class BizLivestockOwnershipHouseholdController extends BaseController
{
    @Autowired
    private IBizLivestockOwnershipHouseholdService service;

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizLivestockOwnershipHousehold query)
    {
        startPage();
        List<BizLivestockOwnershipHousehold> list = service.selectBizLivestockOwnershipHouseholdList(query);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(service.selectBizLivestockOwnershipHouseholdById(id));
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:add')")
    @Log(title = "有无畜户数据填报", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody BizLivestockOwnershipHousehold row)
    {
        row.setCreateBy(getUsername());
        return toAjax(service.insertBizLivestockOwnershipHousehold(row));
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:edit')")
    @Log(title = "有无畜户数据填报", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody BizLivestockOwnershipHousehold row)
    {
        row.setUpdateBy(getUsername());
        return toAjax(service.updateBizLivestockOwnershipHousehold(row));
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:remove')")
    @Log(title = "有无畜户数据填报", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(service.deleteBizLivestockOwnershipHouseholdByIds(ids, getUsername()));
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:list')")
    @GetMapping("/yearOptions")
    public AjaxResult yearOptions()
    {
        return success(service.listYearOptions());
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:list')")
    @GetMapping("/monthOptions")
    public AjaxResult monthOptions()
    {
        return success(service.listMonthOptions());
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:list')")
    @GetMapping("/townOptions")
    public AjaxResult townOptions()
    {
        return success(service.listTownOptions());
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:list')")
    @GetMapping("/villageTree")
    public AjaxResult villageTree()
    {
        return success(service.listVillageTree());
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:import')")
    @Log(title = "有无畜户数据填报", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, @RequestParam("statYear") Integer statYear,
            @RequestParam("statMonth") Integer statMonth)
    {
        return success(service.importData(file, statYear, statMonth, getUsername()));
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws Exception
    {
        ClassPathResource resource = new ClassPathResource(LivestockOwnershipHouseholdExcelParser.TEMPLATE_CLASSPATH);
        if (!resource.exists())
        {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "模板文件不存在");
            return;
        }
        String fileName = URLEncoder.encode("有无畜户导入模板.xlsx", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
        try (InputStream in = resource.getInputStream())
        {
            StreamUtils.copy(in, response.getOutputStream());
        }
    }

    @PreAuthorize("@ss.hasPermi('dataModel:livestockOwnershipHousehold:export')")
    @Log(title = "有无畜户数据填报", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(@RequestParam("statYear") Integer statYear, @RequestParam("statMonth") Integer statMonth,
            @RequestParam(value = "townDeptId", required = false) Long townDeptId, HttpServletResponse response)
            throws Exception
    {
        byte[] data = service.exportByYearMonth(statYear, statMonth, townDeptId, getUsername());
        String fileName = URLEncoder.encode(statYear + "年" + statMonth + "月有无畜户数据.xlsx", "UTF-8").replaceAll("\\+",
                "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
        response.getOutputStream().write(data);
    }
}
