package org.jeecg.modules.financeManage.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.basedata.entity.FdCustomer;
import org.jeecg.modules.basedata.service.IFdCustomerService;
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.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.financeManage.entity.FdProjectReceivablesB;
import org.jeecg.modules.financeManage.entity.FdProjectReceivables;
import org.jeecg.modules.financeManage.vo.FdProjectReceivablesPage;
import org.jeecg.modules.financeManage.service.IFdProjectReceivablesService;
import org.jeecg.modules.financeManage.service.IFdProjectReceivablesBService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
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 com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 项目应收款主表
 * @author： jeecg-boot
 * @date： 2019-07-22
 * @version： V1.0
 */
@RestController
@RequestMapping("/financeManage/fdProjectReceivables")
@Slf4j
public class FdProjectReceivablesController {
    @Autowired
    private IFdProjectReceivablesService fdProjectReceivablesService;
    @Autowired
    private IFdProjectReceivablesBService fdProjectReceivablesBService;
    @Autowired
    IFdCustomerService iFdCustomerService;

    /**
     * 分页列表查询
     *
     * @param fdProjectReceivables
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @RequiresPermissions("url:accountReceivable:view")
    public Result<IPage<FdProjectReceivables>> queryPageList(FdProjectReceivables fdProjectReceivables,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             HttpServletRequest req) {
        fdProjectReceivables.setDelFlag("0");
        Result<IPage<FdProjectReceivables>> result = new Result<IPage<FdProjectReceivables>>();
        String contractno = fdProjectReceivables.getContractno();
        if (StringUtils.isNotBlank(fdProjectReceivables.getContractno())) {
            fdProjectReceivables.setContractno(null);
        }
        String code = fdProjectReceivables.getCode();
        if (StringUtils.isNotBlank(fdProjectReceivables.getCode())) {
            fdProjectReceivables.setCode(null);
        }
        QueryWrapper<FdProjectReceivables> queryWrapper = QueryGenerator.initQueryWrapper(fdProjectReceivables, req.getParameterMap());
        if (StringUtils.isNotBlank(contractno)) {
            queryWrapper.like("contractno", contractno);
        }
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("code", code);
        }
        queryWrapper.lambda().eq(FdProjectReceivables::getDelFlag,"0");
        queryWrapper.lambda().orderByDesc(FdProjectReceivables::getCreateTime);
        Page<FdProjectReceivables> page = new Page<FdProjectReceivables>(pageNo, pageSize);
        IPage<FdProjectReceivables> pageList = fdProjectReceivablesService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param fdProjectReceivablesPage
     * @return
     */
    @PostMapping(value = "/add")
    @NotDuplicate
    @RequiresPermissions("accountReceivable:add")
    public Result<FdProjectReceivables> add(@RequestBody @Validated FdProjectReceivablesPage fdProjectReceivablesPage, BindingResult bindingResult) {
        Result<FdProjectReceivables> result = new Result<FdProjectReceivables>();
        try {
            FdProjectReceivables fdProjectReceivables = new FdProjectReceivables();
            BeanUtils.copyProperties(fdProjectReceivablesPage, fdProjectReceivables);
            StringBuilder stringBuilder = new StringBuilder();
           if (bindingResult.hasErrors()) {
               //实体错误信息
               bindingResult.getAllErrors().stream().forEach(error -> stringBuilder.append(error.getDefaultMessage() + "<br/>"));
               result.error500(stringBuilder.toString());
               return result;
           }
            if (fdProjectReceivablesPage.getFdProjectReceivablesBList().size() < 1) {
                result.error500("明细不能为空");
                return result;
            }

            fdProjectReceivablesService.saveMain(fdProjectReceivables, fdProjectReceivablesPage.getFdProjectReceivablesBList());
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdProjectReceivablesPage
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    @RequiresPermissions("accountReceivable:update")
    public Result<FdProjectReceivables> edit(@RequestBody @Valid FdProjectReceivablesPage fdProjectReceivablesPage, BindingResult bindingResult) {
        Result<FdProjectReceivables> result = new Result<FdProjectReceivables>();
        FdProjectReceivables fdProjectReceivables = new FdProjectReceivables();
        BeanUtils.copyProperties(fdProjectReceivablesPage, fdProjectReceivables);
        FdProjectReceivables fdProjectReceivablesEntity = fdProjectReceivablesService.getById(fdProjectReceivables.getId());

        if (fdProjectReceivablesEntity == null) {
            result.error500("未找到对应实体");
        } else {

            StringBuilder stringBuilder = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //实体错误信息
                bindingResult.getAllErrors().stream().forEach(error -> stringBuilder.append(error.getDefaultMessage() + "<br/>"));
                result.error500(stringBuilder.toString());
                return result;
            }
            if (fdProjectReceivablesPage.getFdProjectReceivablesBList().size() < 1) {
                result.error500("明细不能为空");
                return result;
            }
            boolean ok = fdProjectReceivablesService.updateById(fdProjectReceivables);
            fdProjectReceivablesService.updateAll(fdProjectReceivables, fdProjectReceivablesPage.getFdProjectReceivablesBList());
            result.success("修改成功!");
        }

        return result;
    }

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

        return result;
    }

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

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdProjectReceivables> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdProjectReceivables> result = new Result<FdProjectReceivables>();
        FdProjectReceivables fdProjectReceivables = fdProjectReceivablesService.getById(id);

        //获取客户档案的信用期
        if(fdProjectReceivables.getPkApplicant()!=null&&!fdProjectReceivables.getPkApplicant().equals("")){
            try {
                FdCustomer fdCustomer=iFdCustomerService.getById(fdProjectReceivables.getPkApplicant());
                fdProjectReceivables.setCreditPeriod(fdCustomer.getCreditPeriod());
            } catch (Exception e) {
                e.printStackTrace();
                result.error500("未找到客户（申办方）");
            }
        }

        if (fdProjectReceivables == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(fdProjectReceivables);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryFdProjectReceivablesBByMainId")
    public Result<List<FdProjectReceivablesB>> queryFdProjectReceivablesBListByMainId(@RequestParam(name = "id", required = true) String id) {
        Result<List<FdProjectReceivablesB>> result = new Result<List<FdProjectReceivablesB>>();
        List<FdProjectReceivablesB> fdProjectReceivablesBList = fdProjectReceivablesBService.selectByMainId(id);
        result.setResult(fdProjectReceivablesBList);
        result.setSuccess(true);
        return result;
    }

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdProjectReceivablesPage> pageList = new ArrayList<FdProjectReceivablesPage>();
        List<FdProjectReceivables> fdProjectReceivablesList = fdProjectReceivablesService.list(queryWrapper);
        for (FdProjectReceivables fdProjectReceivables : fdProjectReceivablesList) {
            FdProjectReceivablesPage vo = new FdProjectReceivablesPage();
            BeanUtils.copyProperties(fdProjectReceivables, vo);
            List<FdProjectReceivablesB> fdProjectReceivablesBList = fdProjectReceivablesBService.selectByMainId(fdProjectReceivables.getId());
            vo.setFdProjectReceivablesBList(fdProjectReceivablesBList);
            pageList.add(vo);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "项目应收款主表列表");
        mv.addObject(NormalExcelConstants.CLASS, FdProjectReceivablesPage.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<FdProjectReceivablesPage> list = ExcelImportUtil.importExcel(file.getInputStream(), FdProjectReceivablesPage.class, params);
                for (FdProjectReceivablesPage page : list) {
                    FdProjectReceivables po = new FdProjectReceivables();
                    BeanUtils.copyProperties(page, po);
                    fdProjectReceivablesService.saveMain(po, page.getFdProjectReceivablesBList());
                }
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }


    /**
     * 查询重复编码
     *
     * @param code
     * @return
     */
    @GetMapping(value = "/fingMoreCodeInfo")
    public Result fingMoreCodeInfo(@RequestParam(name = "code") String code, @RequestParam(name = "id") String id) {
        Result result = new Result();
        int list = fdProjectReceivablesService.fingMoreCode(code, id);
        if (list > 0) {
            result.setCode(1);
        } else {
            result.setCode(0);
        }
        return result;

    }

    /**
     * 审核
     *
     * @param ids
     * @return
     */
    @GetMapping(value = "/toExamine")
    public Result toExamine(@RequestParam(name = "ids") String ids, @RequestParam(name = "state") String state) {
        Result result = new Result();
        fdProjectReceivablesService.toExamine(ids, state);
        return result;

    }

    /***
     * @Title:发送财务收款通知给财务负责人
            * @Description:TODO
            * @param msg
            * @return org.jeecg.common.api.vo.Result
            * @exception
            * @author 陈创
            * @date 2019/8/13 20:13
            * @updatehistory:
     *   2019/8/13 20:13 邮件通知
            */
    @GetMapping(value = "/noticeFinance")
    public Result noticeFinance(String personnel,String title,String msg) {
        Result result = new Result();
        try {
            fdProjectReceivablesService.noticeFinance(personnel,title,msg);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            e.printStackTrace();
        }
        return result;
    }
}
