package com.nantian.cloud.jly.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jly.entity.CheckPersons;
import com.nantian.cloud.jly.entity.CompanyCalculater;
import com.nantian.cloud.jly.entity.InspectionData;
import com.nantian.cloud.jly.service.CheckPersonsService;
import com.nantian.cloud.jly.service.CompanyCalculaterService;
import com.nantian.cloud.jly.service.InspectionDataService;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.lang.invoke.ConstantCallSite;
import java.math.BigInteger;
import java.util.*;


/**
 * 能源计量人员表
 *
 * @author
 * @date 2018-09-27 15:20:44
 */
@RestController
@AllArgsConstructor
@Api(value = "checkPersons", tags = "能源计量人员表")
@RequestMapping("/checkPersons")
public class CheckPersonsController {
    private final CheckPersonsService checkPersonsService;
    private final MinioTemplate minioTemplate;
    private final InspectionDataService inspectionDataService;
    private final CompanyCalculaterService companyCalculaterService;

    /**
     * 分页查询
     *
     * @param page         分页对象
     * @param checkPersons 能源计量人员表对象
     * @return
     */
    @SysLog("能源计量人员表-分页查询")
    @GetMapping("/page")
    @ApiOperation(value = "条件查询能源计量人员表", notes = "条件查询能源计量人员表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "CheckPersons", value = "能源计量人员表对象", required = false, dataType = "json", paramType = "path")
    })
    public R getcheckPersonsPage(Page page, CheckPersons checkPersons) {
        checkPersons.setDelFlag("1"); //查询未删除数据
        //return R.ok(checkPersonsService.page(page, Wrappers.query(checkPersons)));
        return R.ok(checkPersonsService.getPageScope(page, checkPersons));
    }

    /**
     * 查询计量人员，如果企业没有上传计量人员，就查询企业计量人员信息表
     *
     * @return
     */
    @SysLog("能源计量人员表-条件查询能源计量人员表")
    @GetMapping("/query")
    @ApiOperation(value = "条件查询能源计量人员表", notes = "条件查询能源计量人员表")
    public R getcheckPersonsQuery(BigInteger checkPlanId, String epc) {
        QueryWrapper<CheckPersons> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("check_plan_id", checkPlanId);
        queryWrapper.eq("epc", epc);
        queryWrapper.eq("del_flag", "1");
        List<CheckPersons> list = checkPersonsService.list(queryWrapper);
        if (list.size() > 0) {
            return R.ok(list);
        } else {
            List<CheckPersons> checkPersonsList = new ArrayList<>();
            QueryWrapper<CompanyCalculater> queryWrapperPro = new QueryWrapper<>();
            queryWrapperPro.eq("enterprise_code", epc);
            queryWrapperPro.eq("del_flag", "1");
            List<CompanyCalculater> listPro = companyCalculaterService.list(queryWrapperPro);
            listPro.forEach(res -> {
                CheckPersons checkPersons = new CheckPersons();
                checkPersons.setEpc(res.getEnterpriseCode());
                checkPersons.setName(res.getCalculaterName());
                checkPersons.setDept(res.getDept());
                checkPersons.setDuties(res.getJob());
                checkPersons.setMajorDulties(res.getTechnicalPost());
                checkPersonsList.add(checkPersons);
            });
            return R.ok(checkPersonsList);
        }
//        checkPersons.setDelFlag("1"); //查询未删除数据
        //return R.ok(checkPersonsService.page(page, Wrappers.query(checkPersons)));

    }

    /**
     * 审查计划的计量人员同步到计量人员管理
     *
     * @return
     */
    @SysLog("能源计量人员表-同步")
    @GetMapping("/getcheckPersonsConfigCalculater")
    @ApiOperation(value = "条件查询能源计量人员表", notes = "能源计量人员表")
    public R getcheckPersonsConfigCalculater(BigInteger checkPlanId, String epc) {

        //查询出计量人员管理
        QueryWrapper<CompanyCalculater> queryWrapperPro = new QueryWrapper<>();
        queryWrapperPro.eq("enterprise_code", epc);
        queryWrapperPro.eq("del_flag", "1");
        List<CompanyCalculater> listPro = companyCalculaterService.list(queryWrapperPro);
        ArrayList<String> al = new ArrayList();
        listPro.forEach(v -> {
            al.add(v.getCalculaterName());
        });
        //查询出审查计划的计量人员
        QueryWrapper<CheckPersons> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("check_plan_id", checkPlanId);
        queryWrapper.eq("epc", epc);
        queryWrapper.eq("del_flag", "1");
        List<CheckPersons> list = checkPersonsService.list(queryWrapper);
        List<CompanyCalculater> companyCalculaterList = new ArrayList<>();
        list.forEach(res -> {
            if (al.indexOf(res.getName()) == -1) {
                CompanyCalculater persons = new CompanyCalculater();
                persons.setEnterpriseCode(res.getEpc());
                persons.setCalculaterName(res.getName());
                persons.setDept(res.getDept());
                persons.setJob(res.getDuties());
                persons.setTechnicalPost(res.getMajorDulties());
                persons.setCertificateNo(res.getCertNum());
                persons.setExam(res.getTestFlag());
                persons.setRemark(res.getComments());
                companyCalculaterList.add(persons);
            }

        });
        companyCalculaterService.saveBatch(companyCalculaterList);
        return R.ok("同步成功");


    }


    /**
     * 根据id查询
     *
     * @param checkPersonsId
     * @return R
     */
    @SysLog("能源计量人员表-根据id查询")
    @GetMapping("/{checkPersonsId}")
    @ApiOperation(value = "根据id查询能源计量人员表", notes = "根据id查询能源计量人员表")
    @ApiImplicitParam(name = "checkPersonsId", value = "能源计量人员表id", required = true, dataType = "int", paramType = "path")
    public R getById(@PathVariable("checkPersonsId") Integer checkPersonsId) {
        return R.ok(checkPersonsService.getById(checkPersonsId));
    }

    /**
     * 新增
     */
    @SysLog("能源计量人员表-新增")
    @PostMapping("/save")
    @ApiOperation(value = "新增能源计量人员表", notes = "新增能源计量人员表")
    @ApiImplicitParam(name = "CheckPersons", value = "能源计量人员表对象", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody CheckPersons checkPersons) {
        ScUser u = SecurityUtils.getUser();
        checkPersons.setUserid(u.getId());
        checkPersons.setDeptId(u.getDeptId());
        checkPersons.setDelFlag("1");
        checkPersons.setUpdateTime(new Date());
        boolean save = checkPersonsService.save(checkPersons); //新增

        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkPersons.getCheckPlanId(), checkPersons.getEpc());
        checkPersonsService.updateInspectionData(u, checkPersons, inspectionData); //更新中间表
        return save ? R.ok("新增能源计量人员表成功") : R.failed("新增能源计量人员表失败");
    }

    /**
     * 修改
     */
    @SysLog("能源计量人员表-修改")
    @PutMapping
    @ApiOperation(value = "修改能源计量人员表", notes = "修改能源计量人员表")
    @ApiImplicitParam(name = "CheckPersons", value = "能源计量人员表对象集合", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody CheckPersons checkPersons) {
        ScUser u = SecurityUtils.getUser();
        checkPersons.setUserid(u.getId());
        checkPersons.setUpdateTime(new Date());
        boolean b = checkPersonsService.updateById(checkPersons);
        return b ? R.ok("修改能源计量人员表成功") : R.failed("修改能源计量人员表失败");
    }

    /**
     * 更新
     */
    @SysLog("能源计量人员表-更新")
    @PostMapping("/renew")
    @ApiOperation(value = "更新能源计量人员表（修改和新增接口）", notes = "更新能源计量人员表（修改和新增接口）")
    @ApiImplicitParam(name = "data", value = "能源计量人员", required = true, dataType = "string", paramType = "path")
    public R renew(@RequestBody CheckPersons checkPersons) {

        /*JSONObject json = JSONObject.parseObject(s);
        String ss = json.getString("data");
        CheckPersons checkPersons = (CheckPersons) JSONArray.parseArray(ss, CheckPersons.class);*/

        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkPersons.getCheckPlanId(), checkPersons.getEpc());
        if (inspectionData != null) {
            if ("Y".equals(inspectionData.getEnergyMeteringPersonnelState())) {  //已审核
                return R.failed("能源计量人员一览表已审核，不能进行增加、修改、删除操作！");
            }
        }

        ScUser u = SecurityUtils.getUser();
        checkPersonsService.updateInspectionData(u, checkPersons, inspectionData); //更新中间表

        return R.ok(checkPersonsService.saveOrUpdate(checkPersons));
    }

    /**
     * 导入excel
     */
    @SysLog("能源计量人员表-导入excel")
    @PostMapping("excelImport")
    @ApiOperation(value = "导入excel", notes = "导入excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path"),
            @ApiImplicitParam(name = "checkPlanId", value = "审查计划id", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "epc", value = "企业社会信用编码", required = true, dataType = "string", paramType = "path")
    })
    public R excelImport(MultipartFile file, BigInteger checkPlanId, String epc) throws FileFormatException {
        if (checkPlanId == null) {
            return R.failed("审查计划id不能为空！");
        }
        if (epc == null || "".equals(epc)) {
            return R.failed("企业社会信用编码不能为空！");
        }
        ScUser u = SecurityUtils.getUser();
        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkPlanId, epc);
        if (inspectionData == null) {
            CheckPersons checkPersons = new CheckPersons();
            if (u.getId() != null) {
                checkPersons.setUserid(u.getId());
            }
            if (u.getDeptId() != null) {
                checkPersons.setDeptId(u.getDeptId());
            }
            checkPersons.setDelFlag("1");
            checkPersons.setUpdateTime(new Date());
            checkPersonsService.updateInspectionData(u, checkPersons, inspectionData);  //更新中间表
//            return R.failed("没有查询到自查18项资料记录");
        } else {
            if ("Y".equals(inspectionData.getEnergyMeteringPersonnelState())) {  //已审核
                return R.failed("能源计量人员一览表已审核，不能进行增加、修改、删除操作！");
            }
        }

        return checkPersonsService.excelImport(file, checkPlanId, epc, inspectionData);
    }

    /**
     * 批量更新
     */
    @SysLog("能源计量人员表-批量更新")
    @PostMapping("/renewBatch")
    @ApiOperation(value = "批量新增能源计量人员表（批量修改和新增接口）", notes = "批量新增能源计量人员表（批量修改和新增接口）")
    @ApiImplicitParam(name = "CheckPersons", value = "能源计量人员表对象集合", required = true, dataType = "json", paramType = "path")
    //public R saveBatch(@RequestBody  List<CheckPersons> checkPersonsList) {
    public R renewBatch(@RequestBody String s) {
        System.err.println("批量更新能源计量人员：" + s);

        JSONObject json = JSONObject.parseObject(s);
        String ss = json.getString("data");
        String mend = json.getString("mend");
        List<CheckPersons> checkPersonsList = (List<CheckPersons>) JSONArray.parseArray(ss, CheckPersons.class);

        ScUser u = SecurityUtils.getUser();
        List<CheckPersons> newCcheckPersonsList = new ArrayList<>();
        if (checkPersonsList.size() > 0) {
            for (CheckPersons checkPersons : checkPersonsList) {
                if (u.getId() != null) {
                    checkPersons.setUserid(u.getId());
                }
                if (u.getDeptId() != null) {
                    checkPersons.setDeptId(u.getDeptId());
                }
                checkPersons.setDelFlag("1");
                checkPersons.setUpdateTime(new Date());
                newCcheckPersonsList.add(checkPersons);
            }
            //更新中间表
            InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkPersonsList.get(0).getCheckPlanId(), checkPersonsList.get(0).getEpc());
            if (inspectionData != null) {
                if ("Y".equals(inspectionData.getEnergyMeteringPersonnelState())) {  //已审核
                    return R.failed("能源计量人员一览表已审核，不能进行增加、修改、删除操作！");
                }
                if ("Z".equals(mend)){  //整改上传
                    inspectionData.setEnergyMeteringPersonnelState("Z");
                }
            }
            checkPersonsService.updateInspectionData(u, checkPersonsList.get(0), inspectionData);  //更新中间表
            return R.ok(checkPersonsService.saveOrUpdateBatch(newCcheckPersonsList));
        } else {
            return R.failed("数据为空！");
        }


    }

    /**
     * 根据id上传任职证明文件
     */
    @SysLog("能源计量人员表-根据id上传任职证明文件")
    @PostMapping("/uploadById")
    @ApiOperation(value = "根据id上传任职证明文件", notes = "根据id上传任职证明文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "任职证明文件", required = true, dataType = "File", paramType = "path"),
            @ApiImplicitParam(name = "id", value = "能源计量人员id", required = true, dataType = "int", paramType = "path")
    })
    public R uploadById(@RequestParam("file") MultipartFile file, Long id) throws Exception {
        CheckPersons checkPersons = checkPersonsService.getById(id);
        if (checkPersons == null) {
            return R.failed("上传任职证明文件失败，原因：获取能源计量人员信息失败！");
        } else {
            //上传文件
            String uuid = UUID.randomUUID().toString();
            InputStream inputStream = file.getInputStream(); //得到文件流
            String fileName = file.getOriginalFilename(); //文件名
            //minioTemplate.putObject("jly", uuid, inputStream);
            minioTemplate.putObject("jly", uuid, inputStream, inputStream.available(), "application/octet-stream");
            //更新人员任职证明文件信息
            ScUser u = SecurityUtils.getUser();
            if (u.getId() != null) {
                checkPersons.setUserid(u.getId());
            }
            checkPersons.setUpdateTime(new Date());
            //fileName + "<" + uuid   文件名、uuid的拼接
            checkPersons.setCertFile(fileName + "<" + uuid);
            checkPersonsService.updateById(checkPersons);
            return R.ok(fileName + "<" + uuid);
        }
    }


    /**
     * 删除
     *
     * @param checkPersonsId
     * @return R
     */
    @SysLog("能源计量人员表-删除")
    @DeleteMapping
    @ApiOperation(value = "根据id删除能源计量人员表", notes = "根据id删除能源计量人员表")
    @ApiImplicitParam(name = "checkPersonsId", value = "能源计量人员表id", required = true, dataType = "int", paramType = "path")
    public R removeById(Long checkPersonsId) {
        CheckPersons checkPersons = checkPersonsService.getById(checkPersonsId);

        InspectionData inspectionData = inspectionDataService.getByPlanIdAndEpc(checkPersons.getCheckPlanId(), checkPersons.getEpc());
        if ("Y".equals(inspectionData.getEnergyMeteringPersonnelState())) {  //已审核
            return R.failed("能源计量人员一览表已审核，不能进行增加、修改、删除操作！");
        }

        //未审核
        ScUser u = SecurityUtils.getUser();
        if (u.getId() != null) {
            checkPersons.setUserid(u.getId());
        }
        checkPersons.setDelFlag("4");
        checkPersons.setUpdateTime(new Date());
        boolean b = checkPersonsService.updateById(checkPersons);//修改注销状态

        CheckPersons newCheckPersons = new CheckPersons();
        newCheckPersons.setDelFlag("1");
        newCheckPersons.setCheckPlanId(checkPersons.getCheckPlanId());
        newCheckPersons.setEpc(checkPersons.getEpc());
        IPage<CheckPersons> page = checkPersonsService.page(new Page<>(), Wrappers.query(newCheckPersons));
        if (page.getRecords().size() == 0) { //没有数据
            inspectionData.setEnergyMeteringPersonnel("D");
            inspectionData.setUserid(u.getId());
            inspectionData.setUpdateTime(new Date());
            inspectionDataService.updateById(inspectionData);
        }
        return b ? R.ok("删除成功") : R.failed("删除失败");
    }


    /**
     * 批量删除
     */
    @SysLog("能源计量人员表-批量删除")
    @PostMapping("/removeAll")
    public R removeAll(@RequestBody String ids) { //BigInteger checkPlanId,String epc
        JSONObject json = JSONObject.parseObject(ids);
        String ss = json.getString("ids");
        String[] strArray = ss.split(",");
        List list = Arrays.asList(strArray);
        return R.ok(checkPersonsService.removeByIds(list));
    }


}
