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.StaMeetingFee;
import com.liang.entity.StaTravelexpenses;
import com.liang.entity.baobiao.ClfUtilEntity;
import com.liang.entity.baobiao.HyUtilEntity;
import com.liang.service.PrjAnnualbudgetService;
import com.liang.service.StaTravelexpensesService;
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;

/**
 * 差旅费(StaTravelexpenses)表控制层
 *
 * @author makejava
 * @since 2023-04-26 09:50:00
 */
@Controller
@RequestMapping("staTravelexpenses")
public class StaTravelexpensesController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private StaTravelexpensesService staTravelexpensesService;

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

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

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

    /**
     * 初始化差旅费列表
     *
     * @param zb
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list/{zb}", method = RequestMethod.POST)
    public BaseResult list(@PathVariable Integer zb) {
        List<StaTravelexpenses> list = staTravelexpensesService.getClfList(zb);

        PageInfo<StaTravelexpenses> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<StaTravelexpenses> 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 "statravelexpense/add";
    }

    /**
     * 批量保存差旅费
     *
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/batchInsert/{zb}", method = RequestMethod.POST)
    public BaseResult batchInsert(@RequestBody String data, @PathVariable Integer zb) {
        //删除差旅费
        staTravelexpensesService.deleteByZb(zb);
        DateFormat dateFormat = new SimpleDateFormat("yyyy");

        List<StaTravelexpenses> expenseList = JsonTool.parseArray(data, StaTravelexpenses.class);
        for (int i = 0; i < expenseList.size(); i++) {
            String partBh = "科研费号(" + dateFormat.format(new Date()) + ")";
            String kyfh = GetApproveRecordBH(partBh);
            expenseList.get(i).setKyfh(kyfh);
            expenseList.get(i).setZb(zb);
        }
        if (expenseList.size() > 0) {
            int num = staTravelexpensesService.insertBatch(expenseList);
            if (num == expenseList.size()) {
                return BaseResult.success("差旅费保存成功！");
            } else {
                return BaseResult.failure("差旅费保存失败！");
            }
        } else {
            return BaseResult.success("没有要保存的信息");
        }
    }

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

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

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

    @Resource
    private PrjAnnualbudgetService prjAnnualbudgetService;
    //项目报表（差旅费用）页面
    @RequestMapping("/search")
    public String search(Model model) {
        List<String> yearList = prjAnnualbudgetService.getYearList();
        model.addAttribute("yearList", yearList);

        return "statistical/travelexpenses";
    }

    //差旅费用全部及条件查询
    @ResponseBody
    @RequestMapping(value = "/searchData", method = RequestMethod.POST)
    public BaseResult searchData(@RequestParam(required = false, defaultValue = "", value = "XMMC") String xmmc,
                                 @RequestParam(required = false, defaultValue = "", value = "CCDD") String ccdd,
                                 @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("ccdd",ccdd);
        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 = staTravelexpensesService.searchTravelexpensesCost(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/{formDate}",method = RequestMethod.POST)
    public BaseResult getAll(@PathVariable(required = false)String formDate)throws Exception{

        Map<String, String> map = new HashMap<>();

        ObjectMapper objectMapper = new ObjectMapper();
        ClfUtilEntity util = objectMapper.readValue(formDate, ClfUtilEntity.class);
        map.put("xmmc",util.getXmmc());
        map.put("erpbh",util.getErpbh());
        map.put("bh",util.getFysqbh());
        map.put("nf",util.getNf());
        map.put("qsrq",util.getQsrq());
        map.put("jsrq",util.getJsrq());
        map.put("ccdd",util.getCcdd());
        List<HashMap<String, Object>> staFeasibilityreport = staTravelexpensesService.searchTravelexpensesCost(map);
        return BaseResult.success(staFeasibilityreport);
    }

}

