package com.liang.controller;

import cn.hutool.core.util.StrUtil;
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.common.exception.CustomException;
import com.liang.common.utils.Tools;
import com.liang.entity.StaSourceFee;
import com.liang.entity.baobiao.ClUtilEntity;
import com.liang.service.PrjAnnualbudgetService;
import com.liang.service.StaSourceFeeService;
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;

/**
 * 资料费(StaExpertFee)表控制层
 */
@Controller
@RequestMapping("staSourceFee")
public class StaSourceFeeController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private StaSourceFeeService staSourceFeeService;

    @Resource
    private PrjAnnualbudgetService prjAnnualbudgetService;

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

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

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

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

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

    /**
     * 批量保存资料费
     *
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/batchInsert/{zb}", method = RequestMethod.POST)
    public BaseResult batchInsert(@RequestBody String data, @PathVariable Integer zb) {
        //删除资料费
        staSourceFeeService.deleteByZb(zb);
        List<StaSourceFee> expenseList = JsonTool.parseArray(data, StaSourceFee.class);
        if (Tools.isEmpty(expenseList) || Tools.isEmpty(data)) {
            throw new CustomException("请录入差旅费");
        }
        expenseList.forEach(item->item.setZb(zb));

        int num = staSourceFeeService.insertBatch(expenseList);
        if (num == expenseList.size()) {
            return BaseResult.success("差旅费保存成功！");
        } else {
            return BaseResult.failure("差旅费保存失败！");
        }

    }

    private String GetApproveRecordBH(String partBh) {
        String kyfh = "";
        List<StaSourceFee> list = staSourceFeeService.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 "stasourcefee/update";
    }

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


    //项目报表（资料费用）页面
    @RequestMapping("/search")
    public String search(Model model) {

        List<String> yearList = prjAnnualbudgetService.getYearList();
        model.addAttribute("yearList", yearList);
        return "statistical/sourceFee";
    }

    //资料费用全部及条件查询
    @ResponseBody
    @RequestMapping(value = "/searchData", method = RequestMethod.POST)
    public BaseResult searchData(@RequestParam("page") Integer pageNum,
                                 @RequestParam("limit") Integer pageSize,
                                 @RequestParam(required = false, defaultValue = "", value = "XMMC") String xmmc,
                                 @RequestParam(required = false, defaultValue = "", value = "TSMC") String tsmc,
                                 @RequestParam(required = false, defaultValue = "", value = "CBS") String cbs,
                                 @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) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, String> map = new HashMap<>();
        map.put("xmmc",xmmc);
        map.put("tsmc",tsmc);
        map.put("cbs",cbs);
        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 = staSourceFeeService.searchSourceCost(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{

        ObjectMapper objectMapper = new ObjectMapper();
        ClUtilEntity clUtil = objectMapper.readValue(formDate, ClUtilEntity.class);
        Map<String, String> map = new HashMap<>();
        map.put("xmmc",clUtil.getXmmc());
        map.put("tsmc",clUtil.getTsmc());
        map.put("cbs",clUtil.getCbs());
        map.put("qsrq",clUtil.getQsrq());
        map.put("jsrq",clUtil.getJsrq());
        map.put("erpbh",clUtil.getErpbh());
        map.put("bh",clUtil.getFysqbh());
        map.put("nf", clUtil.getNf());
        List<HashMap<String, Object>> staFeasibilityreport = staSourceFeeService.searchSourceCost(map);
        return BaseResult.success(staFeasibilityreport);
    }

}
