package org.jeecg.modules.clinical.budget.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.extension.api.R;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.clinical.budget.entity.FdClinicalBudget;
import org.jeecg.modules.clinical.budget.service.IFdClinicalBudgetService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.service.ISysSerialPatternService;
import org.jeecg.modules.system.vo.CallResult;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 临床预算表
 * @author： jeecg-boot
 * @date： 2019-08-17
 * @version： V1.0
 */
@RestController
@RequestMapping("/clinical.budget/fdClinicalBudget")
@Slf4j
public class FdClinicalBudgetController {
    @Autowired
    private IFdClinicalBudgetService fdClinicalBudgetService;

    @Resource
    ISysSerialPatternService sysSerialPatternService;

    /**
     * 分页列表查询
     *
     * @param fdClinicalBudget
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @RequiresPermissions("url:clinicalBudget:view")
    public Result<IPage<FdClinicalBudget>> queryPageList(FdClinicalBudget fdClinicalBudget,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        Result<IPage<FdClinicalBudget>> result = new Result<IPage<FdClinicalBudget>>();
        String clinicalCode = fdClinicalBudget.getClinicalCode();
        if (StringUtils.isNotBlank(fdClinicalBudget.getClinicalCode())) {
            fdClinicalBudget.setClinicalCode(null);
        }
        String clinicalBudgetCode = fdClinicalBudget.getClinicalBudgetCode();
        if (StringUtils.isNotBlank(fdClinicalBudget.getClinicalBudgetCode())) {
            fdClinicalBudget.setClinicalBudgetCode(null);
        }
        QueryWrapper<FdClinicalBudget> queryWrapper = QueryGenerator.initQueryWrapper(fdClinicalBudget, req.getParameterMap());
        if (StringUtils.isNotBlank(clinicalCode)) {
            queryWrapper.like("clinical_code", clinicalCode);
        }
        if (StringUtils.isNotBlank(clinicalBudgetCode)) {
            queryWrapper.like("clinical_budget_code", clinicalBudgetCode);
        }
        queryWrapper.eq("del_flag","0");
        queryWrapper.lambda().orderByDesc(FdClinicalBudget::getCreateTime);
        Page<FdClinicalBudget> page = new Page<FdClinicalBudget>(pageNo, pageSize);
        IPage<FdClinicalBudget> pageList = fdClinicalBudgetService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param fdClinicalBudget
     * @return
     */
    @PostMapping(value = "/add")
    public Result<FdClinicalBudget> add(@RequestBody FdClinicalBudget fdClinicalBudget) {
        Result<FdClinicalBudget> result = new Result<FdClinicalBudget>();
        try {
            fdClinicalBudgetService.save(fdClinicalBudget);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdClinicalBudget
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<FdClinicalBudget> edit(@RequestBody FdClinicalBudget fdClinicalBudget) {
        Result<FdClinicalBudget> result = new Result<FdClinicalBudget>();
        FdClinicalBudget fdClinicalBudgetEntity = fdClinicalBudgetService.getById(fdClinicalBudget.getId());
        if (fdClinicalBudgetEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdClinicalBudgetService.updateById(fdClinicalBudget);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    // @DeleteMapping(value = "/delete")
    // public Result<FdClinicalBudget> delete(@RequestParam(name = "id", required = true) String id) {
    //     Result<FdClinicalBudget> result = new Result<FdClinicalBudget>();
    //     FdClinicalBudget fdClinicalBudget = fdClinicalBudgetService.getById(id);
    //     if (fdClinicalBudget == null) {
    //         result.error500("未找到对应实体");
    //     } else {
    //         boolean ok = fdClinicalBudgetService.removeById(id);
    //         if (ok) {
    //             result.success("删除成功!");
    //         }
    //     }
    //
    //     return result;
    // }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<FdClinicalBudget> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdClinicalBudget> result = new Result<FdClinicalBudget>();
        FdClinicalBudget fdClinicalBudget = fdClinicalBudgetService.getById(id);
        if (fdClinicalBudget == null) {
            result.error500("未找到对应实体");
        } else {
            fdClinicalBudget.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
            boolean ok = fdClinicalBudgetService.updateById(fdClinicalBudget);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdClinicalBudget> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdClinicalBudget> result = new Result<FdClinicalBudget>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.fdClinicalBudgetService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdClinicalBudget> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdClinicalBudget> result = new Result<FdClinicalBudget>();
        FdClinicalBudget fdClinicalBudget = fdClinicalBudgetService.getById(id);
        if (fdClinicalBudget == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(fdClinicalBudget);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<FdClinicalBudget> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                FdClinicalBudget fdClinicalBudget = JSON.parseObject(deString, FdClinicalBudget.class);
                queryWrapper = QueryGenerator.initQueryWrapper(fdClinicalBudget, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdClinicalBudget> pageList = fdClinicalBudgetService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "临床预算表列表");
        mv.addObject(NormalExcelConstants.CLASS, FdClinicalBudget.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("临床预算表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FdClinicalBudget> listFdClinicalBudgets = ExcelImportUtil.importExcel(file.getInputStream(), FdClinicalBudget.class, params);
                for (FdClinicalBudget fdClinicalBudgetExcel : listFdClinicalBudgets) {
                    fdClinicalBudgetService.save(fdClinicalBudgetExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdClinicalBudgets.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /***
     * @Title:查询项目档案中已审核的报价信息
     * @Description:TODO
     * @param
     * @return org.jeecg.common.api.vo.Result<java.util.List < org.jeecg.modules.clinical.budget.entity.FdClinicalBudget>>
     * @exception
     * @author 陈创
     * @date 2019/8/26 16:27
     * @updatehistory:
     *   2019/8/26 16:27 查询
     */
    @GetMapping(value = "/getQuotationList")
    public Result<List<FdClinicalBudget>> getQuotationList() {
        Result<List<FdClinicalBudget>> result = new Result<>();
        try {
            List<FdClinicalBudget> fdClinicalBudgetList = fdClinicalBudgetService.getQuotationList();
            result.setResult(fdClinicalBudgetList);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败:" + e.getMessage());
        }
        return result;
    }

    /***
     * @Title:根据报价id查询对应项目档案中已审核的报价信息
            * @Description:TODO
            * @param quotationId
            * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.clinical.budget.entity.FdClinicalBudget>
            * @exception
            * @author 陈创
            * @date 2019/8/26 16:30
            * @updatehistory:
     *   2019/8/26 16:30 新增
            */
    @GetMapping(value = "/getByQuotationId")
    public Result<FdClinicalBudget> getByQuotationId(String quotationId) {
        Result<FdClinicalBudget> result = new Result<>();
        try {
            FdClinicalBudget fdClinicalBudget=fdClinicalBudgetService.getByQuotationId(quotationId);
            result.setResult(fdClinicalBudget);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:保存全部表单
            * @Description:TODO
            * @param
            * @return org.jeecg.common.api.vo.Result
            * @exception
            * @author 陈创
            * @date 2019/8/27 20:01
            * @updatehistory:
     *   2019/8/27 20:01 新增
            */
    @PostMapping(value = "/addFdClinicalBudgetAdd")
    public Result addFdClinicalBudgetAdd(@RequestBody FdClinicalBudget fdClinicalBudget){
        Result result=new Result();
        try {
            //获取 客户缩写 001
            CallResult<String> resultSerial = sysSerialPatternService.getNextSerial(fdClinicalBudget, "fd_clinical_budget", "clinical_budget_code", true);
            if(!resultSerial.isSucceed()){
                result.error500("获取编码失败");
                return result;
            }
            fdClinicalBudget.setClinicalBudgetCode(resultSerial.getContent());
            fdClinicalBudgetService.addFdClinicalBudgetAdd(fdClinicalBudget);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO  弃审核数据,使其状态为0
     * @Date 17:10 2019/9/11
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.clinical.budget.entity.FdClinicalBudget>
     **/
    @GetMapping(value = "/auditBatch")
    public Result<FdClinicalBudget> auditBatch(@RequestParam(name="ids",required = true) List<String> ids){
        Result<FdClinicalBudget> result=new Result<>();
        String message="";
        if(ids.isEmpty()){
            message+="请选择数据</br>";
        }
        Map<String,Object> map= null;
        try {
            //执行service
            map = fdClinicalBudgetService.auditBatch(ids);
            result.setSuccess(true);
            result.setMessage(message+map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO  审核数据,使其状态为1
     * @Date 17:11 2019/9/11
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.clinical.budget.entity.FdClinicalBudget>
     **/
    @GetMapping(value = "/reviewBatch")
    public Result<FdClinicalBudget> reviewBatch(@RequestParam(name="ids",required = true) List<String> ids){
        Result<FdClinicalBudget> result=new Result<>();
        String message="";
        if(ids.isEmpty()){
            message+="请选择数据</br>";
        }
        Map<String,Object> map= null;
        try {
            //执行service
            map = fdClinicalBudgetService.reviewBatch(ids);
            result.setSuccess(true);
            result.setMessage(message+map.get("msg").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }

    /***
     * @Title:删除主表以及主表
            * @Description:TODO
            * @param
            * @return org.jeecg.common.api.vo.Result
            * @exception 
            * @author 陈创
            * @date 2019/9/12 12:06
            * @updatehistory:
     *   2019/9/12 12:06 新增
            */
    @DeleteMapping(value = "/deleteFdClinicalBudgetAll")
    public Result deleteFdClinicalBudgetAll(@RequestParam(name = "id") String id){
        Result result = new Result();
        try {
            fdClinicalBudgetService.deleteFdClinicalBudgetAll(id);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }
    
    /***
     * @Title:修改临床预算
            * @Description:TODO
            * @param
            * @return org.jeecg.common.api.vo.Result
            * @exception 
            * @author 陈创
            * @date 2019/9/12 13:50
            * @updatehistory:
     *   2019/9/12 13:50 新增
            */
    @PostMapping(value = "/updateFdClinicalBudgetAll")
    public Result updateFdClinicalBudgetAll(@RequestBody FdClinicalBudget fdClinicalBudget){
        Result result=new Result();
        try {
            fdClinicalBudgetService.updateFdClinicalBudgetAll(fdClinicalBudget);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 根据id导出全部数据
    * @Date 2020/8/5 10:10
    * @Param [fdClinicalBudget]
    * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.clinical.budget.entity.FdClinicalBudget>
    */
    @GetMapping(value = "/exportById")
    public Result<FdClinicalBudget> exportById(FdClinicalBudget fdClinicalBudget){
        Result<FdClinicalBudget> result=new Result<>();
        try {
            FdClinicalBudget fdClinicalBudgetResult=fdClinicalBudgetService.exportById(fdClinicalBudget);
            result.setResult(fdClinicalBudgetResult);
            result.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;

    }

}
