package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.dto.AuditorDto;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.entity.TExperts;
import com.nantian.cloud.jljc.service.CheckExpertService;
import com.nantian.cloud.jljc.service.RecordCertificateManagerService;
import com.nantian.cloud.jljc.service.TExpertsService;
import com.nantian.cloud.jljc.service.TExpertsService;
import com.nantian.cloud.jljc.vo.util.FileUtil;
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 lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;


/**
 * 节能专家库
 *
 * @date 2020-09-05
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tExperts")
@Api(value = "tExperts", tags = "节能专家库")
public class TExpertsController {
    private final TExpertsService tExpertsService;
    private final CheckExpertService checkExpertService;

    /**
     * 节能专家库列表
     */
    @GetMapping("/selectAll")
    @SysLog("节能专家库列表")
    @ApiOperation(value = "节能专家库列表", notes = "节能专家库列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json"),
            @ApiImplicitParam(name = "TExperts", value = "查询条件（name 名称关键字； type类型编码（J 节能减排，L 计量，G 公共机构）；industryCode行业编码； industryName 行业名称）" +
                    "position职务职称； profession专业/特长； label标签", required = false, dataType = "string")
    })
    //public R getCompInfo(Page page, String name, String type, String industryCode, String industryName) {
    public R getCompInfo(Page page, TExperts tExperts) {
        IPage expertsList = tExpertsService.getExpertsByPage(page, tExperts);
        return expertsList != null ? R.ok(expertsList) : R.failed("获取节能专家库失败！");
    }

    /**
     * 随机抽取专家
     */
    @GetMapping("/randomExperts")
    @SysLog("随机抽取专家")
    @ApiOperation(value = "随机抽取专家", notes = "随机抽取专家")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "num", value = "数量", required = true, dataType = "string"),
            @ApiImplicitParam(name = "TExperts", value = "专家(position职务职称，profession专业/特长，label标签)")
    })
    public R getRandomExperts(TExperts tExperts, Integer num) {
        return tExpertsService.getRandomExperts(tExperts, num);
    }

    @GetMapping("/random")
    public R getRandomInfo(Integer num, String type, String ptrade) {
        if (num == null) {
            return R.failed("num is not exited");
        }
        List<TExperts> list = tExpertsService.getExperts(type, ptrade);
        if (list.size() < num.intValue()) {
            return R.ok(list);
        } else {
            List<TExperts> newList = new ArrayList();
            Random r = new Random();
            int i = 0;
            while (i < num) {
                int n = r.nextInt(list.size());
                TExperts item = list.get(n);
                if (item != null) {
                    newList.add(item);
                    list.set(n, null);
                    i++;
                }
            }
            return R.ok(newList);
        }
    }


    @GetMapping("/relation")
    public void setRelationInfo(String id, String expertstable) {
        //System.out.println(epcId);

        ArrayList<TExperts> list = JSON.parseObject(expertstable, new TypeReference<ArrayList<TExperts>>() {
        });
        checkExpertService.deleteRelationsById(id);
        for (TExperts item : list) {
            CheckExpert ce = new CheckExpert();
            ce.setExpertId("" + item.getId());
            ce.setCheckId(id);
            checkExpertService.save(ce);
        }
    }

    @GetMapping("/getRelation")
    public R getRelationInfo(String id) {
//        System.out.println(epcId);

//        ArrayList<TExperts> list = JSON.parseObject(expertstable, new TypeReference<ArrayList<TExperts>>() {});
        List<CheckExpert> list = checkExpertService.getAllListById(id);
        List<TExperts> listexpert = new ArrayList<>();
        for (CheckExpert item : list) {
            TExperts ce = tExpertsService.getById(item.getExpertId());
            listexpert.add(ce);
        }
        return R.ok(listexpert);
    }

    /**
     * 根据id节能专家库
     */
    @GetMapping("/getById/{id}")
    @SysLog("根据id获取节能专家库")
    @ApiOperation(value = "根据id获取节能专家库", notes = "根据id获取节能专家库")
    @ApiImplicitParam(name = "id", value = "节能专家库id", required = true, dataType = "int", paramType = "path")
    public R getTExpertsById(@PathVariable("id") Integer id) {
        TExperts experts = tExpertsService.getExpertsById(id);
        return experts != null ? R.ok(experts) : R.failed("获取节能专家库失败！");
    }

    /**
     * 新增节能专家库
     */
    @PostMapping("/add")
    @SysLog("新增节能专家库")
    @ApiOperation(value = "新增节能专家库", notes = "新增节能专家库")
    @ApiImplicitParam(name = "TExperts", value = "节能专家库对象", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody TExperts tExperts) {
        ScUser u = SecurityUtils.getUser();
        tExperts.setUserid(u.getId());
        tExperts.setDeptId(u.getDeptId());
        tExperts.setUpdateTime(new Date());
        tExperts.setDelFlag("1");
        boolean flag = tExpertsService.addExperts(tExperts);
        return flag ? R.ok("新增节能专家库成功") : R.failed("新增节能专家库失败");
    }

    /**
     * 根据id修改节能专家库
     */
    @PutMapping("/update")
    @SysLog("根据id修改节能专家库")
    @ApiOperation(value = "根据id修改节能专家库", notes = "根据id修改节能专家库")
    @ApiImplicitParam(name = "TExperts", value = "节能专家库对象", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody TExperts tExperts) {
        ScUser u = SecurityUtils.getUser();
        tExperts.setUserid(u.getId());
        tExperts.setUpdateTime(new Date());
        boolean flag = tExpertsService.updateExpertsById(tExperts);
        return flag ? R.ok("修改节能专家库成功") : R.failed("修改节能专家库失败");
    }

    /**
     * 根据id删除节能专家库
     */
    @DeleteMapping("/delete")
    @SysLog("根据id删除节能专家库")
    @ApiOperation(value = "根据id删除节能专家库", notes = "根据id删除节能专家库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "id", value = "节能专家库id", required = true, dataType = "int", paramType = "path")
    })
    public R removeById(Integer userId, Integer id) {
        TExperts tExperts = new TExperts();
        if (id == null) {
            return R.failed("节能专家库id不能为空！");
        } else {
            tExperts.setId(id);
        }
        if (userId != null) {
            tExperts.setUserid(userId);
        }
        tExperts.setUpdateTime(new Date());
        tExperts.setDelFlag("4");
        boolean flag = tExpertsService.deleteExpertsById(tExperts);
        return flag ? R.ok("删除节能专家库成功") : R.failed("删除节能专家库失败");
    }
}
