package com.nantian.cloud.jljc.controller;

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.jljc.entity.EnterpriseInfo;
import com.nantian.cloud.jljc.entity.TTrainingPerson;
import com.nantian.cloud.jljc.service.DictRegionService;
import com.nantian.cloud.jljc.service.EnterpriseInfoService;
import com.nantian.cloud.jljc.service.TTrainingPersonService;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.annotation.Inner;
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.commons.lang.StringUtils;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import static java.lang.Integer.decode;


/**
 * 培训活动-人员信息
 *
 * @date 2020-09-03 13:23:34
 */
@CrossOrigin
@AllArgsConstructor
@Api(value = "ttrainingperson", tags = "培训活动-人员信息")
@RestController
@RequestMapping("/ttrainingperson")
public class TTrainingPersonController {
    @Autowired
    private TTrainingPersonService tTrainingPersonService;
    @Autowired
    private EnterpriseInfoService enterpriseInfoService;
    @Autowired
    private DictRegionService dictRegionService;

    /**
     * 分页查询
     */
    @SysLog("分页获取培训人员(带权限)")
    @ApiOperation(value = "分页获取培训人员(带权限)", notes = "分页获取培训人员(带权限)")
    @GetMapping("/page")
    @ApiImplicitParam(name = "TTrainingPerson", value = "分页获取培训人员", required = false, paramType = "path")
    public R page(Page page, TTrainingPerson tTrainingPerson) {
        return R.ok(tTrainingPersonService.pageByScope(page,tTrainingPerson));
    }


    /**
     * 点查看报名情况
     * @param id
     * @return
     */
    @SysLog("根据项目ID查询人员列表")
    @ApiOperation(value = "根据项目ID查询人员列表", notes = "根据项目ID查询人员列表")
    @GetMapping("/getPerson")
    @ResponseBody
    public R getPersonInfo(@RequestParam(value = "id") Integer id,long current, long size){
        Page page = new Page(current, size);
        TTrainingPerson tTrainingPerson=new TTrainingPerson();
        tTrainingPerson.setTrainingId(id);
        return R.ok(tTrainingPersonService.page(page, Wrappers.query(tTrainingPerson).eq("del_flag",1).orderByDesc("update_time")));

//        List<TTrainingPerson> personList= tTrainingPersonService.getPerson(id);
       // return R.ok(personList);
    }


    @SysLog("根据企业信用代码获取报名人员")
    @ApiOperation(value = "根据企业信用代码获取报名人员", notes = "根据企业信用代码获取报名人员")
    @GetMapping("/getPageByEpc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "epc", value = "企业编号", required = false, paramType = "path"),
            @ApiImplicitParam(name = "trainingId", value = "培训ID", required = false, paramType = "path"),
            @ApiImplicitParam(name = "current", value = "页码", required = false, paramType = "path"),
            @ApiImplicitParam(name = "size", value = "每页显示", required = false, paramType = "path")
    })
    public R getPageByEpc(String epc, Integer trainingId, long current, long size) {
        Page page = new Page(current, size);
        TTrainingPerson t = new TTrainingPerson();
        t.setEpc(epc);
        t.setTrainingId(trainingId);
        return R.ok(tTrainingPersonService.page(page, Wrappers.query(t).eq("del_flag",1).orderByDesc("update_time")));
    }

    @SysLog("根据培训ID获取培训人员")
    @ApiOperation(value = "根据培训ID获取培训人员", notes = "根据培训ID获取培训人员")
    @GetMapping("/getPageByTrainingId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "trainingId", value = "培训ID", required = false, paramType = "path"),
            @ApiImplicitParam(name = "current", value = "页码", required = false, paramType = "path"),
            @ApiImplicitParam(name = "size", value = "每页显示", required = false, paramType = "path")
    })
    public R getPageByTrainingId(Integer trainingId, long current, long size) {
        Page page = new Page(current, size);

        TTrainingPerson t = new TTrainingPerson();
        t.setTrainingId(trainingId);
        IPage p = tTrainingPersonService.page(page, Wrappers.query(t));
        List list = p.getRecords();

        for (int i = 0; i < list.size(); i++) {
            TTrainingPerson o = (TTrainingPerson) list.get(i);
            if (o != null) {
                try{
                    String epc = o.getEpc();
                    if(StringUtils.isNotBlank(epc)){
                        EnterpriseInfo te = new EnterpriseInfo();
                        te.setEnterpriseCode(epc);
                        EnterpriseInfo one = enterpriseInfoService.getOne(Wrappers.query(te).select("cmp_name", "enterprise_code"));
                        if(one!=null) {
                            o.setEnterpriseName(one.getCmpName());
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return R.ok(p);
    }

    /**
     * 信息
     */
    @SysLog("获取培训人员")
    @ApiOperation(value = "获取培训人员", notes = "获取培训人员")
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        return R.ok(tTrainingPersonService.getById(id));
    }

    /**
     * 保存
     */
    @SysLog("新增培训人员")
    @ApiOperation(value = "新增培训人员", notes = "新增培训人员")
    @PostMapping("/save")
    @ApiImplicitParam(name = "TTrainingPerson", value = "新增培训人员", required = true, paramType = "path")
    public R save(@RequestBody TTrainingPerson tTrainingPerson) {
        String[] location;
        location=tTrainingPerson.getLocation().split(" / ");
        tTrainingPerson.setLocation(location[1]+","+location[2]);
        ScUser u = SecurityUtils.getUser();
        if(isSignUp(tTrainingPerson.getTrainingId(),tTrainingPerson.getName(),tTrainingPerson.getTelephone())){
            return R.failed(2,"不可重复报名！");
        }
        tTrainingPerson.setUserid(u.getId());
        tTrainingPerson.setDeptId(u.getDeptId());
        tTrainingPerson.setDelFlag("1");
        tTrainingPerson.setUpdateTime(new Date());
        return R.ok(tTrainingPersonService.save(tTrainingPerson));
    }

    /**
     * 保存
     */
    @Inner(value = false)
    @SysLog("系统外新增培训人员")
    @ApiOperation(value = "系统外新增培训人员", notes = "系统外新增培训人员")
    @PostMapping("/saveOut")
    @ApiImplicitParam(name = "TTrainingPerson", value = "系统外新增培训人员", required = true, paramType = "path")
    public R saveOut(@RequestBody String str) throws Exception {
        String temp = URLDecoder.decode(str,"UTF-8");
        String temp1 = temp.substring(0,temp.length()-1);
        TTrainingPerson tTrainingPerson = JSONObject.parseObject(temp1,TTrainingPerson.class);
        if(isSignUp(tTrainingPerson.getTrainingId(),tTrainingPerson.getName(),tTrainingPerson.getTelephone())){
            return R.failed(2,"不可重复报名！");
        }
        String[] areaCode = tTrainingPerson.getTerritorial().split(",");
        tTrainingPerson.setDeptId(decode(areaCode[1]));
        tTrainingPerson.setDelFlag("1");
        tTrainingPerson.setUpdateTime(new Date());
        return R.ok(tTrainingPersonService.save(tTrainingPerson));
    }

    /**
     * 修改
     */
    @SysLog("更新培训人员")
    @ApiOperation(value = "更新培训人员", notes = "更新培训人员")
    @PutMapping("/update")
    public R update(@RequestBody TTrainingPerson tTrainingPerson) {
        String[] location;
        location=tTrainingPerson.getLocation().split(" / ");
        tTrainingPerson.setLocation(location[1]+","+location[2]);
        ScUser u = SecurityUtils.getUser();
        tTrainingPerson.setUserid(u.getId());
        tTrainingPerson.setUpdateTime(new Date());
        return R.ok(tTrainingPersonService.updateById(tTrainingPerson));
    }
    /**
     * 修改
     */
    @SysLog("更新培训人员")
    @ApiOperation(value = "更新培训人员", notes = "更新培训人员")
    @PutMapping("/updateTraining")
    public R updateTraining(@RequestBody TTrainingPerson tTrainingPerson) {
        ScUser u = SecurityUtils.getUser();
        tTrainingPerson.setUserid(u.getId());
        tTrainingPerson.setUpdateTime(new Date());
        return R.ok(tTrainingPersonService.updateById(tTrainingPerson));
    }

    /**
     * 删除
     */
    @SysLog("删除培训人员")
    @ApiOperation(value = "删除培训人员", notes = "删除培训人员")
    @DeleteMapping("/delete")
    public R delete(Integer id) {
        TTrainingPerson person = tTrainingPersonService.getById(id);
        if(person==null) {
            return R.failed("删除失败，人员不存在！");
        }
        person.setDelFlag("4");
        person.setUpdateTime(new Date());
        return R.ok(tTrainingPersonService.updateById(person));
    }


    /**
     * 培训人员管理页面查询按钮     单位enterpriseName    培训名称name    年度updateTime
     * @param enterpriseName
     * @param name
     * @return
     */
    @SysLog("培训人员管理页面查询按钮")
    @ApiOperation(value = "培训人员管理页面查询按钮", notes = "培训人员管理页面查询按钮")
    @GetMapping("/get")
    @ResponseBody
    public R getByInfo(@RequestParam(value = "enterpriseName") String  enterpriseName,
                       @RequestParam(value = "name") String  name,
                       @RequestParam(value = "updateTime") Date updateTime) {
        List<TTrainingPerson> personList = tTrainingPersonService.getInfo(enterpriseName,name,updateTime);
        return R.ok(personList);
    }


    /**
     * 统计该培训课题的报名人数
     * @return
     */
    @SysLog("统计报名人数")
    @ApiOperation(value = "统计报名人数", notes = "统计报名人数")
    @GetMapping("/getCount")
    @ResponseBody
    public R getCount(@RequestParam(value = "trainingId") Integer trainingId){
        return R.ok(tTrainingPersonService.getCount(trainingId));
    }

    /**
     * 根据属地，单位，姓名 查询人员的基本新情况   4
     * @param territorial   long current, long size
     * @return
     */
    @SysLog("查询培训人员的基本情况")
    @ApiOperation(value = "查询人员的基本情况", notes = "查询人员的基本情况")
    @GetMapping("/getPersonInfo")
    @ResponseBody
    public R getPersonInfo(@RequestParam(value = "territorial",required = false) String territorial,
                           @RequestParam(value = "enterpriseName",required = false) String enterpriseName,
                           @RequestParam(value = "name",required = false) String name,
                           @RequestParam(value = "trainingSession",required = false) String trainingSession,
                           @RequestParam(value = "trainingId") Integer trainingId,
                           @RequestParam(value = "current") long current,
                           @RequestParam(value = "size") long size){
        Page page = new Page(current, size);
        TTrainingPerson t = new TTrainingPerson();
        t.setTrainingId(trainingId);
        return R.ok(tTrainingPersonService.page(page, Wrappers.query(t).eq("del_flag",1).likeRight("territorial",territorial).like("name",name).like("enterprise_name",enterpriseName).like(StringUtils.isNotBlank(trainingSession),"training_session",trainingSession)));
//        return R.ok(tTrainingPersonService.getPersonInfo(territorial,enterpriseName,name,trainingId));
    }
    /**
     * 查询培训人员信息和培训信息
     * @return
     */
    @SysLog("查询培训人员信息和培训信息")
    @ApiOperation(value = "查询培训人员信息和培训信息", notes = "查询培训人员信息和培训信息")
    @GetMapping("/getTrainingPersonInfo")
    @ResponseBody
    public R getTrainingPersonInfo(@RequestParam(value = "year",required = false) String year,
                                   @RequestParam(value = "trainingName",required = false) String trainingName,
                                   @RequestParam(value = "current") long current,
                                   @RequestParam(value = "size") long size){
        ScUser u = SecurityUtils.getUser();
        Page page = new Page(current, size);
        return R.ok(tTrainingPersonService.getTrainingPersonInfo(page,u.getId(),year,trainingName));
    }

    @SysLog("导入培训人员信息")
    @PostMapping("/excelImportPerson")
    @ApiOperation(value = "导入excel", notes = "导入excel")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path")
    public R excelImport(@RequestParam MultipartFile file) throws FileFormatException {
        return  tTrainingPersonService.excelImport(file);
    }

    /*
    判断是否已报名，不能重复报名
     */

    public boolean isSignUp(Integer trainingId, String personName,String telephone){
        TTrainingPerson tTrainingPerson = tTrainingPersonService.getOne(new QueryWrapper<>(new TTrainingPerson())
                .eq("training_id",trainingId)
                .eq("name",personName)
                .eq("telephone",telephone)
                .eq("del_flag","1"));
        if (tTrainingPerson != null){
            return true;
        }
        return false;
    }

















}
