package com.liang.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liang.common.JsonTool;
import com.liang.common.base.BaseController;
import com.liang.common.base.BaseResult;
import com.liang.entity.StaBudgetapproval;
import com.liang.entity.StaPrintingFee;
import com.liang.entity.baobiao.UtilEntity;
import com.liang.service.PrjAnnualbudgetService;
import com.liang.service.StaPrintingFeeService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 打印费(StaPrintingFee)表控制层
 */
@Controller
@RequestMapping("staPrintingFee")
public class StaPrintingFeeController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private StaPrintingFeeService staPrintingFeeService;
    @Resource
    private PrjAnnualbudgetService prjAnnualbudgetService;

    /**
     * 分页查询
     *
     * @param staPrintingFee 筛选条件
     * @param pageRequest    分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<StaPrintingFee>> queryByPage(StaPrintingFee staPrintingFee, PageRequest pageRequest) {
        return ResponseEntity.ok(this.staPrintingFeeService.queryByPage(staPrintingFee, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<StaPrintingFee> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.staPrintingFeeService.queryById(id));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.staPrintingFeeService.deleteById(id));
    }

    /**
     * 初始化打印费列表
     *
     * @param zb
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list/{zb}", method = RequestMethod.POST)
    public BaseResult list(@PathVariable Integer zb) {
        List<StaPrintingFee> list = staPrintingFeeService.getDyfList(zb);

        PageInfo<StaPrintingFee> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaPrintingFee> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);

        return BaseResult.success(result);
    }

    /**
     * 新建数据
     *
     * @return
     */
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model) {
        return "staprintingfee/add";
    }

    /**
     * 批量保存打印费
     *
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/batchInsert/{zb}", method = RequestMethod.POST)
    public BaseResult batchInsert(@RequestBody String data, @PathVariable Integer zb) {
        //删除打印费
        staPrintingFeeService.deleteByZb(zb);
        DateFormat dateFormat = new SimpleDateFormat("yyyy");
        List<StaPrintingFee> expenseList = JsonTool.parseArray(data, StaPrintingFee.class);
        for (int i = 0; i < expenseList.size(); i++) {
            String partBh = "科研费号(" + dateFormat.format(new Date()) + ")";
            String sqkyfh = GetApproveRecordBH(partBh);
            expenseList.get(i).setSqkyfh(sqkyfh);
            expenseList.get(i).setZb(zb);
        }
        if (expenseList.size() > 0) {
            int num = staPrintingFeeService.insertBatch(expenseList);
            if (num == expenseList.size()) {
                return BaseResult.success("打印费保存成功！");
            } else {
                return BaseResult.failure("打印费保存失败！");
            }
        } else {
            return BaseResult.success("没有要保存的信息");
        }
    }

    private String GetApproveRecordBH(String partBh) {
        String sqkyfh = "";
        List<StaPrintingFee> list = staPrintingFeeService.queryBySqkyfh(partBh);
        if (list != null && list.size() > 0) {
            String _tmpBh = list.get(0).getSqkyfh();
            if (_tmpBh != null) {
                try {
                    _tmpBh = _tmpBh.substring(10);
                    Integer idx = Integer.parseInt(_tmpBh) + 1;
                    sqkyfh = partBh + String.format("%04d", idx);
                } catch (Exception er) {
                    sqkyfh = partBh + "1001";
                }
            } else
                sqkyfh = partBh + "1001";
        } else
            sqkyfh = partBh + "1001";
        return sqkyfh;
    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate", method = RequestMethod.GET)
    public String forUpdate() {
        return "staprintingfee/update";
    }

    /**
     * 查看数据
     *
     * @return
     */
    @RequestMapping(value = "/forView", method = RequestMethod.GET)
    public String forView() {
        return "staprintingfee/view";
    }

    //项目报表（印刷费用）页面
    @RequestMapping("/search")
    public String search(Model model) {
        List<String> yearList = prjAnnualbudgetService.getYearList();
        model.addAttribute("yearList", yearList);
        return "statistical/printingFee";
    }

    //印刷费用全部及条件查询
    @ResponseBody
    @RequestMapping(value = "/searchData", method = RequestMethod.POST)
    public BaseResult searchData(@RequestParam(required = false, defaultValue = "", value = "XMMC") String xmmc,
                                 @RequestParam(required = false, defaultValue = "", value = "QSRQ") String qsrq,
                                 @RequestParam(required = false, defaultValue = "", value = "JSRQ") String jsrq,
                                 @RequestParam(required = false, defaultValue = "", value = "ERPBH") String erpbh,
                                 @RequestParam(required = false, defaultValue = "", value = "FYSQBH")String fysqbh,
                                 @RequestParam(required = false, defaultValue = "", value = "NF")String nf,
                                 @RequestParam("page") Integer pageNum,
                                 @RequestParam("limit") Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Map<String, String> map = new HashMap<>();
        map.put("xmmc",xmmc);
        map.put("qsrq",qsrq);
        map.put("jsrq",jsrq);
        map.put("erpbh",erpbh);
        map.put("bh",fysqbh);
        map.put("nf",nf);
        List<HashMap<String, Object>> staFeasibilityreport = staPrintingFeeService.searchPrintingCost(map);
        PageInfo<HashMap<String, Object>> pageinfo = new PageInfo<>(staFeasibilityreport);
        List<HashMap<String, Object>> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);
        return BaseResult.success(result);
    }
    @ResponseBody
    @RequestMapping(value = "/getAll/{formData}",method = RequestMethod.POST)
    public  BaseResult getAll(@PathVariable(required = false) String formData)throws Exception{
        Map<String, String> map = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        UtilEntity util = objectMapper.readValue(formData, UtilEntity.class);
        map.put("xmmc",util.getXmmc());
        map.put("qsrq",util.getQsrq());
        map.put("jsrq",util.getJsrq());
        map.put("erpbh",util.getErpbh());
        map.put("bh",util.getFysqbh());
        map.put("nf",util.getNf());
        List<HashMap<String, Object>> staFeasibilityreport = staPrintingFeeService.searchPrintingCost(map);

        return BaseResult.success(staFeasibilityreport);
    }

}
