package com.yeejoin.amos.boot.module.common.biz.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.dao.mapper.DataDictionaryMapper;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.Menu;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import com.yeejoin.amos.boot.module.common.api.dto.FireExpertsDto;
import com.yeejoin.amos.boot.module.common.api.entity.FireExperts;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.excel.ExcelUtil;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireExpertsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 消防专家
 *
 * @author system_generator
 * @date 2021-06-25
 */
@RestController
@Api(tags = "消防专家Api")
@RequestMapping(value = "/common/fire-experts")
public class FireExpertsController extends BaseController {

    @Autowired
    FireExpertsServiceImpl fireExpertsServiceImpl;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    DataDictionaryServiceImpl dataDictionaryService;

    @Autowired
    private OrgUsrMapper orgUsrMapper;



    /**
     * 新增
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
    public ResponseModel<FireExpertsDto> save(@RequestBody FireExpertsDto model) {
        ReginParams reginParams = getSelectedOrgInfo();
        String companyId = reginParams.getPersonIdentity().getCompanyId();
        if (StringUtils.isNotEmpty(companyId)) {
            OrgUsr orgUsr = orgUsrMapper.queryBySequenceNbr(companyId);
            model.setBizOrgCode(orgUsr.getBizOrgCode());
            model.setBizOrgName(orgUsr.getBizOrgName());
        }
        if (model.getExpertCode() != null){
            String expertCode = model.getExpertCode();
            DataDictionary zjly = dataDictionaryService.getByCode(expertCode, "ZJLY");
            model.setExpert(zjly.getName());
        }
        /*3183 联动专家，岗位选择字节点保存后概要中数据缺失 chenzhao 2021-10-19 */
        if (model.getJobsCode() != null){
            DataDictionary gwmc= dataDictionaryService.getByCode(model.getJobsCode() , "GWMC");
            model.setJobs(gwmc.getName());
        }
        /*3183 联动专家，岗位选择字节点保存后概要中数据缺失 chenzhao 2021-10-19 */
        model = fireExpertsServiceImpl.createWithModel(model);
        return ResponseHelper.buildResponse(model);
    }

    /**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
    public ResponseModel<FireExpertsDto> updateBySequenceNbrFireExperts(@RequestBody FireExpertsDto model,
                                                                        @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        ReginParams reginParams = getSelectedOrgInfo();
        String companyId = reginParams.getPersonIdentity().getCompanyId();
        if (StringUtils.isNotEmpty(companyId)) {
            OrgUsr orgUsr = orgUsrMapper.queryBySequenceNbr(companyId);
            model.setBizOrgCode(orgUsr.getBizOrgCode());
            model.setBizOrgName(orgUsr.getBizOrgName());
        }
       /*bug 3098 联动专家，编辑时领域选择子分类保存，领域数据未修改 chenzhao 2021-10-14 */
        model.setSequenceNbr(sequenceNbr);
        if (model.getExpertCode() != null){
            String expertCode = model.getExpertCode();
            DataDictionary zjly = dataDictionaryService.getByCode(expertCode, "ZJLY");
            model.setExpert(zjly.getName());
        }
        /*3183 联动专家，岗位选择字节点保存后概要中数据缺失 chenzhao 2021-10-19 */
        if (model.getJobsCode() != null){
            DataDictionary gwmc= dataDictionaryService.getByCode(model.getJobsCode() , "GWMC");
            model.setJobs(gwmc.getName());
        }
        /*3183 联动专家，岗位选择字节点保存后概要中数据缺失 chenzhao 2021-10-19 */
        /*bug 3098 联动专家，编辑时领域选择子分类保存，领域数据未修改 chenzhao 2021-10-14 */
        return ResponseHelper.buildResponse(fireExpertsServiceImpl.updateWithModel(model));
    }

    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除", notes = "根据sequenceNbr删除")
    public ResponseModel<Boolean> deleteBySequenceNbr(@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        FireExperts fireExperts = fireExpertsServiceImpl.getById(sequenceNbr);
        fireExperts.setIsDelete(true);
        return ResponseHelper.buildResponse(fireExpertsServiceImpl.updateById(fireExperts));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个", notes = "根据sequenceNbr查询单个")
    public ResponseModel<FireExpertsDto> selectOne(@PathVariable Long sequenceNbr) {
        FireExpertsDto fireExpertsDto = fireExpertsServiceImpl.queryBySeq(sequenceNbr);
        Date birthdayTime = fireExpertsDto.getBirthdayTime();
        int age = DateUtils.getAge(birthdayTime);
        fireExpertsDto.setAge(age);
        return ResponseHelper.buildResponse(fireExpertsDto);
    }

    /**
     * 列表分页查询
     *
     * @param current        当前页
     * @param size           每页大小
     * @param fireExpertsDto 查询参数
     * @return 返回结果
     * @throws Exception 
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "分页查询", notes = "分页查询")
    public ResponseModel<IPage<FireExpertsDto>> queryForPage(@RequestParam(value = "current") int current,
                                                             @RequestParam(value = "size") int size,
                                                             FireExpertsDto fireExpertsDto) throws Exception {
        Page<FireExpertsDto> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
		/*  修改bug ： 4827 开始*/
        String expertCode =  fireExpertsDto.getExpertCode();
        List<String> expertCodeArr = new ArrayList<String>();
        expertCodeArr.add(expertCode);
        List<DataDictionary>  detaList =   dataDictionaryService.getAllChildNodes("ZJLY", fireExpertsDto.getExpertCode()!=null?Long.parseLong(fireExpertsDto.getExpertCode()):null);
        
        if(detaList!=null && detaList.size()>0 ) {
        	 for (DataDictionary i : detaList) {
        		 expertCodeArr.add(i.getCode());
     		}
        }
        /*  修改bug ： 4827  结束*/
        Page<FireExpertsDto> fireExpertsDtoPage = fireExpertsServiceImpl.queryForFireExpertsPage1(page, false,
                fireExpertsDto.getName(), expertCodeArr, fireExpertsDto.getBizOrgCode());
        List<FireExpertsDto> fireExpertsDtoList = fireExpertsDtoPage.getRecords().stream().map(item -> {
            item.setAge(DateUtils.getAge(item.getBirthdayTime()));
            return item;
        }).collect(Collectors.toList());
        fireExpertsDtoPage.setRecords(fireExpertsDtoList);
        return ResponseHelper.buildResponse(fireExpertsDtoPage);
    }

    /**
     * 列表全部数据查询
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表全部数据查询", notes = "列表全部数据查询")
    @GetMapping(value = "/list")
    public ResponseModel<List<FireExpertsDto>> selectForList() {
        List<FireExpertsDto> fireExpertsDtoList = fireExpertsServiceImpl.queryForFireExpertsList(false,null,null, null);
        fireExpertsDtoList.stream().map(item -> {
            item.setAge(DateUtils.getAge(item.getBirthdayTime()));
            return item;
        }).collect(Collectors.toList());

        return ResponseHelper.buildResponse(fireExpertsDtoList);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getExpertsTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取专家领域树", notes = "获取专家领域树")
    public ResponseModel<Object> getExpertsTree(@RequestParam(required = false) String bizOrgCode) throws Exception {
//        String type = "ZJLY";
//        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("type", type);
//        queryWrapper.orderByAsc("sort_num");

        Collection<DataDictionary> list = dataDictionaryService.getDataDictionaryAndCount(bizOrgCode);
        list.forEach(i->{
        	i.setName(i.getName()+" ("+i.getCount()+")");
        });
        List<Menu> menus = TreeParser.getTree(null, list, DataDictionary.class.getName(), "getCode", 0, "getName"
                , "getParent",null,null);
        Menu menu = new Menu(-1L, "专家领域", -1L, menus,0);
        List<Menu> menuList = new ArrayList<>();
        menuList.add(menu);
        // 创建挂在主节点
        return ResponseHelper.buildResponse(menuList);
    }

    /**
     *
     * 导入航空器信息
     *
     * **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/ImportData")
    @ApiOperation(httpMethod = "POST", value = "导入消防专家", notes = "导入消防专家")
    public Boolean ImportData (@RequestPart MultipartFile multipartFile)  {
        List<FireExperts> aircraftList = new ArrayList<>();
        try {

            EasyExcel.read(multipartFile.getInputStream(), FireExpertsDto.class, new AnalysisEventListener<FireExpertsDto>() {

                // 每读取一行就调用该方法
                @Override
                public void invoke(FireExpertsDto data, AnalysisContext context) {

                    FireExperts fireExperts = new FireExperts();
                    BeanUtils.copyProperties(data,fireExperts);
                    aircraftList.add(fireExperts);
                }
                // 全部读取完成就调用该方法
                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    System.out.println("读取完成");
                }
            }).sheet().doRead();

            fireExpertsServiceImpl.saveBatch(aircraftList);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
