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.BizLargeLivestockFarmer;
import com.ruoyi.web.modules.industryservice.service.IBizLargeLivestockFarmerService;
import com.ruoyi.web.modules.industryservice.support.LargeLivestockFarmerExcelParser;

/**
 * 养殖大户数据填报 REST 接口。
 * <p>
 * Base Path：{@code /dataModel/largeLivestockFarmer}<br>
 * 权限前缀：{@code dataModel:largeLivestockFarmer:*}（list/query/add/edit/remove/import/export）<br>
 * 菜单前端组件路径：{@code dataModel/largeLivestockFarmer/index}
 * </p>
 */
@RestController
@RequestMapping("/dataModel/largeLivestockFarmer")
public class BizLargeLivestockFarmerController extends BaseController
{
    @Autowired
    private IBizLargeLivestockFarmerService bizLargeLivestockFarmerService;

    /** 分页列表；筛选条件随查询对象绑定（年、月、乡镇、企业名称等） */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizLargeLivestockFarmer query)
    {
        startPage();
        List<BizLargeLivestockFarmer> list = bizLargeLivestockFarmerService.selectBizLargeLivestockFarmerList(query);
        return getDataTable(list);
    }

    /** 详情 */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizLargeLivestockFarmerService.selectBizLargeLivestockFarmerById(id));
    }

    /** 新增；默认未做发布态控制，创建人取当前登录用户 */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:add')")
    @Log(title = "养殖大户数据填报", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody BizLargeLivestockFarmer row)
    {
        row.setCreateBy(getUsername());
        return toAjax(bizLargeLivestockFarmerService.insertBizLargeLivestockFarmer(row));
    }

    /** 修改；需传主键 id */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:edit')")
    @Log(title = "养殖大户数据填报", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody BizLargeLivestockFarmer row)
    {
        row.setUpdateBy(getUsername());
        return toAjax(bizLargeLivestockFarmerService.updateBizLargeLivestockFarmer(row));
    }

    /** 批量物理删除，路径参数为逗号分隔 id */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:remove')")
    @Log(title = "养殖大户数据填报", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bizLargeLivestockFarmerService.deleteBizLargeLivestockFarmerByIds(ids, getUsername()));
    }

    /** 年份下拉选项 */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:list')")
    @GetMapping("/yearOptions")
    public AjaxResult yearOptions()
    {
        return success(bizLargeLivestockFarmerService.listYearOptions());
    }

    /** 乡镇下拉（列表筛选 / 导出可选乡镇） */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:list')")
    @GetMapping("/townOptions")
    public AjaxResult townOptions()
    {
        return success(bizLargeLivestockFarmerService.listTownOptions());
    }

    /** 村级组织树（新增/编辑选村） */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:list')")
    @GetMapping("/villageTree")
    public AjaxResult villageTree()
    {
        return success(bizLargeLivestockFarmerService.listVillageTree());
    }

    /** 月份下拉 1～12 */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:list')")
    @GetMapping("/monthOptions")
    public AjaxResult monthOptions()
    {
        return success(bizLargeLivestockFarmerService.listMonthOptions());
    }

    /**
     * Excel 导入。
     * multipart：{@code file}（.xlsx）+ {@code statYear} + {@code statMonth}。
     * 年月以表单为准；按 (年,月,村,企业名称) upsert。
     */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer: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(bizLargeLivestockFarmerService.importData(file, statYear, statMonth, getUsername()));
    }

    /** 下载官方导入模板（classpath：{@link LargeLivestockFarmerExcelParser#TEMPLATE_CLASSPATH}） */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws Exception
    {
        ClassPathResource resource = new ClassPathResource(LargeLivestockFarmerExcelParser.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());
        }
    }

    /**
     * 按年月导出 xlsx。
     *
     * @param townDeptId 可选；不传则导出该月全部乡镇数据；填表人=当前登录用户
     */
    @PreAuthorize("@ss.hasPermi('dataModel:largeLivestockFarmer: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 = bizLargeLivestockFarmerService.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);
    }
}
