package org.jeecg.modules.finance.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 javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.entity.FdCustomer;
import org.jeecg.modules.basedata.entity.FdPersonnel;
import org.jeecg.modules.basedata.service.IFdCustomerService;
import org.jeecg.modules.basedata.service.IFdPersonnelService;
import org.jeecg.modules.finance.entity.FdSupplementaryContractReceivables;
import org.jeecg.modules.finance.entity.FdSupplementaryContractReceivablesB;
import org.jeecg.modules.finance.service.IFdSupplementaryContractReceivablesBService;
import org.jeecg.modules.finance.service.IFdSupplementaryContractReceivablesService;

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.projectManagement.entity.FdProjectFile;
import org.jeecg.modules.projectManagement.service.IFdProjectFileService;
import org.jeecg.modules.sampleAndConsumableManagement.controller.FdColumnManagementController;
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.validation.BindingResult;
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： gur
 * @date： 2019-07-19
 * @version： V1.0
 */
@RestController
@RequestMapping("/finance/fdSupplementaryContractReceivables")
@Slf4j
public class FdSupplementaryContractReceivablesController {
    @Autowired
    private IFdSupplementaryContractReceivablesService fdSupplementaryContractReceivablesService;

    @Resource
    private FdColumnManagementController fdColumnManagementController;

    @Resource
    private IFdSupplementaryContractReceivablesBService fdSupplementaryContractReceivablesBService;

    @Resource
    private IFdPersonnelService fdPersonnelService;

    @Resource
    private ISysSerialPatternService sysSerialPatternService;

    @Resource
    private IFdCustomerService iFdCustomerService;
    
    @Resource
    IFdProjectFileService iFdProjectFileService;

    /**
     * 分页列表查询
     *
     * @param fdSupplementaryContractReceivables
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    @RequiresPermissions("url:contractAccountReceivable:view")
    public Result<IPage<FdSupplementaryContractReceivables>> queryPageList(FdSupplementaryContractReceivables fdSupplementaryContractReceivables,
                                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                           HttpServletRequest req) {
        Result<IPage<FdSupplementaryContractReceivables>> result = new Result<IPage<FdSupplementaryContractReceivables>>();
        String receiptNumber = fdSupplementaryContractReceivables.getReceiptNumber();
        if (StringUtils.isNotBlank(fdSupplementaryContractReceivables.getReceiptNumber())) {
            fdSupplementaryContractReceivables.setReceiptNumber(null);
        }
        String contractCode = fdSupplementaryContractReceivables.getContractCode();
        if (StringUtils.isNotBlank(fdSupplementaryContractReceivables.getContractCode())) {
            fdSupplementaryContractReceivables.setContractCode(null);
        }
        QueryWrapper<FdSupplementaryContractReceivables> queryWrapper = QueryGenerator.initQueryWrapper(fdSupplementaryContractReceivables, req.getParameterMap());
        if (StringUtils.isNotBlank(receiptNumber)) {
            queryWrapper.like("receipt_number", receiptNumber);
        }
        if (StringUtils.isNotBlank(contractCode)) {
            queryWrapper.like("contract_code", contractCode);
        }
        queryWrapper.eq("del_flag", "0");
        queryWrapper.orderByDesc("create_time");
        Page<FdSupplementaryContractReceivables> page = new Page<FdSupplementaryContractReceivables>(pageNo, pageSize);
        IPage<FdSupplementaryContractReceivables> pageList = fdSupplementaryContractReceivablesService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param fdSupplementaryContractReceivables
     * @return
     */
    @PostMapping(value = "/add")
    @NotDuplicate
    public Result<FdSupplementaryContractReceivables> add(@RequestBody @Valid FdSupplementaryContractReceivables fdSupplementaryContractReceivables, BindingResult bindingResult) {
        Result<FdSupplementaryContractReceivables> result = new Result<FdSupplementaryContractReceivables>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdSupplementaryContractReceivablesService.save(fdSupplementaryContractReceivables);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdSupplementaryContractReceivables
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdSupplementaryContractReceivables> edit(@RequestBody @Valid FdSupplementaryContractReceivables fdSupplementaryContractReceivables, BindingResult bindingResult) {
        Result<FdSupplementaryContractReceivables> result = new Result<FdSupplementaryContractReceivables>();
        FdSupplementaryContractReceivables fdSupplementaryContractReceivablesEntity = fdSupplementaryContractReceivablesService.getById(fdSupplementaryContractReceivables.getId());
        if (fdSupplementaryContractReceivablesEntity == null) {
            result.error500("未找到对应实体");
        } else {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            boolean ok = fdSupplementaryContractReceivablesService.updateById(fdSupplementaryContractReceivables);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

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

    /***
     * @Title:删除
            * @Description:TODO
            * @param id
            * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.finance.entity.FdSupplementaryContractReceivables>
            * @exception
            * @author 陈创
            * @date 2019/11/1 17:33
            * @updatehistory:
     *   2019/11/1 17:33 删除
            */
    @DeleteMapping(value = "/delete")
    @NotDuplicate
    @RequiresPermissions("contractAccountReceivable:delete")
    public Result<FdSupplementaryContractReceivables> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdSupplementaryContractReceivables> result = new Result<FdSupplementaryContractReceivables>();
        FdSupplementaryContractReceivables fdSupplementaryContractReceivables = fdSupplementaryContractReceivablesService.getById(id);
        if (fdSupplementaryContractReceivables == null) {
            result.error500("未找到对应实体");
        } else {
            fdSupplementaryContractReceivables.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
            boolean ok = fdSupplementaryContractReceivablesService.updateById(fdSupplementaryContractReceivables);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

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

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdSupplementaryContractReceivables> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdSupplementaryContractReceivables> result = new Result<FdSupplementaryContractReceivables>();
        FdSupplementaryContractReceivables fdSupplementaryContractReceivables = fdSupplementaryContractReceivablesService.getById(id);
        if (fdSupplementaryContractReceivables == null) {
            result.error500("未找到对应实体");
        } else {
            //获取客户档案的信用期
            if(fdSupplementaryContractReceivables.getPkBidparty()!=null&&!fdSupplementaryContractReceivables.getPkBidparty().equals("")){
                try {
                    FdCustomer fdCustomer=iFdCustomerService.getById(fdSupplementaryContractReceivables.getPkBidparty());
                    fdSupplementaryContractReceivables.setCreditPeriod(fdCustomer.getCreditPeriod());
                } catch (Exception e) {
                    e.printStackTrace();
                    result.error500("未找到客户（申办方）");
                }
            }
            // Map<String,Object> msp = Maps.newHashMap();
            // msp.put("del_flag","0");
            // msp.put("pk_supplementary_contract_receivables",id);
            // List<FdSupplementaryContractReceivablesB> fdSupplementaryContractReceivablesBList = (List<FdSupplementaryContractReceivablesB>)fdSupplementaryContractReceivablesBService.listByMap(msp);
            //子表明细
            LambdaQueryWrapper<FdSupplementaryContractReceivablesB> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(FdSupplementaryContractReceivablesB::getDelFlag,"0");
            lambdaQueryWrapper.eq(FdSupplementaryContractReceivablesB::getPkSupplementaryContractReceivables,id);
            lambdaQueryWrapper.orderByAsc(FdSupplementaryContractReceivablesB::getSerialNumber);
            List<FdSupplementaryContractReceivablesB> fdSupplementaryContractReceivablesBList=fdSupplementaryContractReceivablesBService.list(lambdaQueryWrapper);
            fdSupplementaryContractReceivables.setFdSupplementaryContractReceivablesBList(fdSupplementaryContractReceivablesBList);
            result.setResult(fdSupplementaryContractReceivables);
            result.setSuccess(true);
        }
        return result;
    }

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdSupplementaryContractReceivables> pageList = fdSupplementaryContractReceivablesService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "补充合同应收款表列表");
        mv.addObject(NormalExcelConstants.CLASS, FdSupplementaryContractReceivables.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<FdSupplementaryContractReceivables> listFdSupplementaryContractReceivabless = ExcelImportUtil.importExcel(file.getInputStream(), FdSupplementaryContractReceivables.class, params);
                for (FdSupplementaryContractReceivables fdSupplementaryContractReceivablesExcel : listFdSupplementaryContractReceivabless) {
                    fdSupplementaryContractReceivablesService.save(fdSupplementaryContractReceivablesExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdSupplementaryContractReceivabless.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }


    /**
     * @Author gurui
     * @Description //TODO 添加补充合同应收款表同时添加其子表
     * @Date 13:58 2019/7/19
     * @Param [fdSupplementaryContractReceivables, bindingResult]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.finance.entity.FdSupplementaryContractReceivables>
     **/
    @PostMapping(value = "/addAll")
    @NotDuplicate
    @RequiresPermissions(value = {"contractAccountReceivable:add","contractAccountReceivable:update"},logical = Logical.OR)
    public Result<FdSupplementaryContractReceivables> addAll(@RequestBody @Valid FdSupplementaryContractReceivables fdSupplementaryContractReceivables, BindingResult bindingResult) {
        Result<FdSupplementaryContractReceivables> result = new Result<FdSupplementaryContractReceivables>();
        try {
            //获取编码:合同号_Amd#+按合同流水号增加
            CallResult<String> resultSerial = sysSerialPatternService.getNextSerial(fdSupplementaryContractReceivables, "fd_supplementary_contract_receivables", "supplemental_contract_code", true);
            if(!resultSerial.isSucceed()){
                result.error500("获取编码失败");
                return result;
            }
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;

            }
            //合同补充单号
            fdSupplementaryContractReceivables.setSupplementalContractCode(resultSerial.getContent());

            if(fdSupplementaryContractReceivables.getId()==null||fdSupplementaryContractReceivables.getId().equals("")){
                // LambdaQueryWrapper<FdSupplementaryContractReceivables> queryWrapper=new LambdaQueryWrapper<>();
                // queryWrapper.eq(FdSupplementaryContractReceivables::getContractCode,fdSupplementaryContractReceivables.getContractCode());
                // queryWrapper.eq(FdSupplementaryContractReceivables::getDelFlag,"0");
                // List<FdSupplementaryContractReceivables> fdSupplementaryContractReceivablesList=fdSupplementaryContractReceivablesService.list(queryWrapper);
                // if(!fdSupplementaryContractReceivablesList.isEmpty()&&fdSupplementaryContractReceivablesList.size()>0){
                //     result.error500("合同号已存在！");
                //     return result;
                // }
            }
            fdSupplementaryContractReceivablesService.addAll(fdSupplementaryContractReceivables);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO 根据合同id查询相关信息
     * @Date 14:18 2019/7/19
     * @Param [contractId]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.finance.entity.FdSupplementaryContractReceivables>
     **/
    @GetMapping(value = "/querySupplementartByConId")
    public Result<FdSupplementaryContractReceivables> querySupplementartByConId(@RequestParam(name = "pkProjectFile", required = true) String pkProjectFile) {
        Result<FdSupplementaryContractReceivables> result = new Result<FdSupplementaryContractReceivables>();
        FdSupplementaryContractReceivables fdSupplementaryContractReceivables = fdSupplementaryContractReceivablesService.querySupplementartByConId(pkProjectFile);
        if (fdSupplementaryContractReceivables == null) {
            result.error500("未找到对应实体");
        } else {
            LambdaQueryWrapper<FdPersonnel> queryPerson1 = new LambdaQueryWrapper<>();
            queryPerson1.eq(FdPersonnel::getId,fdSupplementaryContractReceivables.getBdPersonInCharge());
            List<FdPersonnel> list = fdPersonnelService.list(queryPerson1);
            for (FdPersonnel fdPersonnel:list){
                fdSupplementaryContractReceivables.setBdPersonInChargeName(fdPersonnel.getName());
            }
            LambdaQueryWrapper<FdPersonnel> queryPerson2 = new LambdaQueryWrapper<>();
            queryPerson2.eq(FdPersonnel::getId,fdSupplementaryContractReceivables.getPmPersonInCharge());
            List<FdPersonnel> list2 = fdPersonnelService.list(queryPerson2);
            for (FdPersonnel fdPersonnel:list2){
                fdSupplementaryContractReceivables.setPmPersonInChargeName(fdPersonnel.getName());
            }

            String contractPartyName = fdColumnManagementController.getContractPartyName(fdSupplementaryContractReceivables.getPkContractParty());
            fdSupplementaryContractReceivables.setContractPartyName(contractPartyName);
            result.setResult(fdSupplementaryContractReceivables);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO 删除补充合同应收款表同时删除其子表
     * @Date 14:19 2019/7/19
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.finance.entity.FdSupplementaryContractReceivables>
     **/
    @DeleteMapping(value = "/deleteAll")
    public Result<FdSupplementaryContractReceivables> deleteAll(@RequestParam(name = "id", required = true) String id) {
        Result<FdSupplementaryContractReceivables> result = new Result<FdSupplementaryContractReceivables>();
        FdSupplementaryContractReceivables fdSupplementaryContractReceivables = fdSupplementaryContractReceivablesService.getById(id);
        if (fdSupplementaryContractReceivables == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdSupplementaryContractReceivablesService.deleteAll(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * @Author gurui
     * @Description //TODO 弃审核数据 使其状态为0
     * @Date 14:20 2019/7/19
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.finance.entity.FdSupplementaryContractReceivables>
     **/
    @GetMapping(value = "/auditBatch")
    public Result<FdSupplementaryContractReceivables> auditBatch(@RequestParam(name = "ids", required = true) List<String> ids) {
        Result<FdSupplementaryContractReceivables> result = new Result<>();
        String message = "";
        if (ids.isEmpty()) {
            message += "请选择数据</br>";
        }
        Map<String, Object> map = null;
        try {
            //执行service
            map = fdSupplementaryContractReceivablesService.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 14:21 2019/7/19
     * @Param [ids]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.finance.entity.FdSupplementaryContractReceivables>
     **/
    @GetMapping(value = "/reviewBatch")
    public Result<FdSupplementaryContractReceivables> reviewBatch(@RequestParam(name = "ids", required = true) List<String> ids) {
        Result<FdSupplementaryContractReceivables> result = new Result<>();
        String message = "";
        if (ids.isEmpty()) {
            message += "请选择数据</br>";
        }
        Map<String, Object> map = null;
        try {
            //执行service
            map = fdSupplementaryContractReceivablesService.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<java.util.List<org.jeecg.modules.projectManagement.entity.FdProjectFile>>
            * @exception 
            * @author 陈创
            * @date 2019/10/15 11:25
            * @updatehistory:
     *   2019/10/15 11:25 新增
            */
    @GetMapping(value = "/supplementContractList")
    public Result<List<FdProjectFile>> supplementContractList(){
        Result<List<FdProjectFile>> result=new Result<>();
        try {
            List<FdProjectFile> fdProjectFileList=fdSupplementaryContractReceivablesService.supplementContractList();
            result.setSuccess(true);
            result.setResult(fdProjectFileList);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }


}
