package com.ozs.web.controller.base;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ozs.base.domain.BaseExpert;
import com.ozs.base.domain.BaseProfessional;
import com.ozs.base.domain.vo.BaseExpertVo;
import com.ozs.base.domain.vo.BaseProfessionalVo;
import com.ozs.base.service.BaseExpertService;
import com.ozs.base.service.BaseProfessionalService;
import com.ozs.common.annotation.Log;
import com.ozs.common.constant.ModularConstans;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.utils.PageUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanUtils;
import com.ozs.system.domain.vo.SysRegionVO;
import com.ozs.system.service.ISysDictDataService;
import com.ozs.system.service.SysRegionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 专家库管理
 *
 * @author sunhh
 */
@Api(tags = "专家库管理")
@RestController
@RequestMapping("/base/expert")
public class BaseExpertController extends BaseController {

    @Autowired
    private BaseExpertService baseExpertService;
    @Autowired
    private SysRegionService sysRegionService;
    @Autowired
    private BaseProfessionalService baseProfessionalService;
    @Autowired
    private ISysDictDataService dictDataService;


    @ApiOperation(value = "新增专家库" , notes = "必传 专家库名称")
    @PostMapping("/insertExpert")
    @PreAuthorize("@ss.hasPermi('base:expert:insertExpert')")
    @Log(title = ModularConstans.expert, businessType = BusinessType.INSERT)
    public AjaxResult insertExpert(@RequestBody BaseExpertVo baseExpertVo) {
        if (StringUtils.isNull(baseExpertVo) || StringUtils.isNull(baseExpertVo.getExpertName())) {
            return error("专家库名称不能为空");
        }
        baseExpertVo.setCreated(getUserId().toString());
        baseExpertVo.setCreateTime(new Date());
        baseExpertVo.setUpdated(baseExpertVo.getCreated());
        baseExpertVo.setUpdateTime(baseExpertVo.getCreateTime());
        if (ObjectUtils.isEmpty(baseExpertVo.getMajorType())) {
            return error("专业类型为空");
        }
        LambdaQueryWrapper<BaseProfessional> lw = new LambdaQueryWrapper();
        lw.eq(BaseProfessional::getProfessionalCode, baseExpertVo.getMajorType());
        List<BaseProfessional> list = baseProfessionalService.list(lw);
        if (ObjectUtils.isEmpty(list) || list.size() < 1) {
            return error("专业类型传值错误");
        }
        LambdaQueryWrapper<BaseExpert> l = new LambdaQueryWrapper();
        l.eq(BaseExpert::getIdNumber, baseExpertVo.getIdNumber());
        List<BaseExpert> list1 = baseExpertService.list(l);
        if (!ObjectUtils.isEmpty(list1) && list1.size() > 0) {
            return error("身份证号已经存在");
        }
        SysRegionVO sysRegionVO = sysRegionService.selectInfoByCode(baseExpertVo.getLocalArea());
        if (ObjectUtils.isEmpty(sysRegionVO)) {
            return error("该区域在数据库中不存在");
        }
        return toAjax(baseExpertService.insertExpert(baseExpertVo));
    }

    @ApiOperation(value = "删除专家库", notes = "必传 id")
    @PostMapping("/deleteExpert")
    @PreAuthorize("@ss.hasPermi('base:expert:deleteExpert')")
    @Log(title = ModularConstans.expert, businessType = BusinessType.DELETE)
    public AjaxResult deleteExpert(@RequestBody BaseExpert baseExpert) {
        if (StringUtils.isNull(baseExpert) || StringUtils.isNull(baseExpert.getId())) {
            return error("专家库id不能为空");
        }
        return toAjax(baseExpertService.removeById(baseExpert.getId()));
    }

    @ApiOperation(value = "修改专家库", notes = "必传 id 及修改数据")
    @PostMapping("/updateExpert")
    @PreAuthorize("@ss.hasPermi('base:expert:updateExpert')")
    @Log(title = ModularConstans.expert, businessType = BusinessType.UPDATE)
    public AjaxResult updateProfessional(@RequestBody BaseExpert baseExpert) {
        if (StringUtils.isNull(baseExpert) || StringUtils.isNull(baseExpert.getId())) {
            return error("专家库id和修改数据不能为空");
        }

        baseExpert.setUpdated(getUserId().toString());
        baseExpert.setUpdateTime(new Date());
        if (ObjectUtils.isEmpty(baseExpert.getMajorType())) {
            return error("专业类型为空");
        }
        LambdaQueryWrapper<BaseProfessional> lw = new LambdaQueryWrapper();
        lw.eq(BaseProfessional::getProfessionalCode, baseExpert.getMajorType());
        List<BaseProfessional> list = baseProfessionalService.list(lw);
        if (ObjectUtils.isEmpty(list) || list.size() < 1) {
            return error("专业类型传值错误");
        }
        LambdaQueryWrapper<BaseExpert> l = new LambdaQueryWrapper();
        l.eq(BaseExpert::getIdNumber, baseExpert.getIdNumber());
        List<BaseExpert> list1 = baseExpertService.list(l);
        if (!ObjectUtils.isEmpty(list1) && list.size() > 0) {
            if (!list1.get(0).getId().equals(baseExpert.getId())) {
                return error("身份证号已经存在");
            }
        }
        SysRegionVO sysRegionVO = sysRegionService.selectInfoByCode(baseExpert.getLocalArea());
        if (ObjectUtils.isEmpty(sysRegionVO)) {
            return error("该区域在数据库中不存在");
        }
        return toAjax(baseExpertService.updateById(baseExpert));
    }

    @ApiOperation(value = "查询专家库", notes = "非必传 查询条件：品目名称")
    @PostMapping("/selectExpert")
    @PreAuthorize("@ss.hasPermi('base:expert:selectExpert')")
    @Log(title = ModularConstans.expert, businessType = BusinessType.QUERY)
    public AjaxResult selectExpert(@RequestBody BaseExpertVo baseExpertVo) {
        LambdaQueryWrapper<BaseExpert> lw = new LambdaQueryWrapper<BaseExpert>();
        if (!StringUtils.isBlank(baseExpertVo.getExpertName())) {
            lw.like(BaseExpert::getExpertName, baseExpertVo.getExpertName());
        }
        if (!StringUtils.isBlank(baseExpertVo.getMajorType())) {
            lw.eq(BaseExpert::getMajorType, baseExpertVo.getMajorType());
        }
        if (!ObjectUtils.isEmpty(baseExpertVo.getMajorGrade())) {
            lw.eq(BaseExpert::getMajorGrade, baseExpertVo.getMajorGrade());
        }
        if (!ObjectUtils.isEmpty(baseExpertVo.getVarietyPurchase())) {
            lw.eq(BaseExpert::getVarietyPurchase, baseExpertVo.getVarietyPurchase());
        }
        lw.orderBy(true, false, BaseExpert::getCreateTime);
        List<BaseExpert> list = baseExpertService.list(lw);
        List<BaseExpertVo> listVo = BeanUtils.entityListToVOList(list, BaseExpertVo.class);
        for (BaseExpertVo vo : listVo) {
            // 区域
            if (StringUtils.isNotNull(vo.getLocalArea())) {
                String parentAdministrativeDivisionNames = sysRegionService.getParentAdministrativeDivisionNames(vo.getLocalArea());
                vo.setLocalAreaName(parentAdministrativeDivisionNames);
            }
            // 专业类型
            if (!org.apache.commons.lang3.StringUtils.isBlank(vo.getMajorType())) {
                LambdaQueryWrapper<BaseProfessional> lwe = new LambdaQueryWrapper<>();
                lwe.eq(BaseProfessional::getProfessionalCode, vo.getMajorType());
                List<BaseProfessional> list1 = baseProfessionalService.list(lwe);
                if (!ObjectUtils.isEmpty(list1)) {
                    vo.setMajorTypeName(list1.get(0).getProfessionalName());
                }
            }
            // 专家类型
            if (StringUtils.isNotEmpty(vo.getExpertType())) {
                String expertType = vo.getExpertType();
                List<String> expertTypeList = Arrays.stream(expertType.split(",")).map(s -> s.trim()).collect(Collectors.toList());
                for (String eT : expertTypeList) {
                    String expertTypeName = dictDataService.selectDictLabel("expert_type", eT);
                    if (StringUtils.isNotEmpty(expertTypeName)) {
                        vo.setExpertTypeName(expertTypeName);
                    }
                }
            }
        }
        Page pages = PageUtils.getPages(baseExpertVo.getPageNum().intValue(), baseExpertVo.getPageSize().intValue(), listVo);
        return success(pages);
    }

    @ApiOperation(value = "黑白名单开关", notes = "必传id,status 其他字段不传； 黑名单传0，白名单传1")
    @PostMapping("/updateSupplierType")
    @PreAuthorize("@ss.hasPermi('base:expert:updateSupplierType')")
    @Log(title = ModularConstans.expert, businessType = BusinessType.UPDATE)
    public AjaxResult updateSupplierType(@RequestBody BaseExpert baseExpert) {
        if (StringUtils.isNull(baseExpert) || StringUtils.isNull(baseExpert.getId())
                || StringUtils.isNull(baseExpert.getStatus())) {
            return error("状态及ID不能为空");
        }
//        LambdaQueryWrapper<BaseExpert> lw = new LambdaQueryWrapper<BaseExpert>();
//        if (!StringUtils.isNull(baseExpert.getId())) {
//            lw.eq(BaseExpert::getId, baseExpert.getId());
//        }
//        if (!StringUtils.isBlank(baseExpert.getStatus())) {
//            lw.eq(BaseExpert::getStatus, baseExpert.getStatus());
//        }
        return toAjax(baseExpertService.updateSupplierType(baseExpert));
    }

    @ApiOperation(value = "评审项目", notes = "必传：分页，专家ID")
    @PostMapping("/selectReviewProject")
    @PreAuthorize("@ss.hasPermi('base:expert:selectReviewProject')")
    @Log(title = ModularConstans.expert, businessType = BusinessType.OTHER)
    public AjaxResult selectReviewProject(@RequestBody BaseExpertVo baseExpertVo) {
        if (StringUtils.isNull(baseExpertVo)
                || StringUtils.isNull(baseExpertVo.getPageNum())
                || StringUtils.isNull(baseExpertVo.getPageSize())
                || StringUtils.isNull(baseExpertVo.getId())) {
            return error("专家ID、分页 不能为空");
        }
        return baseExpertService.selectReviewProject(baseExpertVo);
    }

    @ApiOperation(value = "抽取专家", notes = "必传：分页；非必传：专家名称，开始结束时间")
    @PostMapping("/selectExtractionExpert")
    @PreAuthorize("@ss.hasPermi('base:expert:selectExtractionExpert')")
    @Log(title = ModularConstans.expert, businessType = BusinessType.OTHER)
    public AjaxResult selectExtractionExpert(@RequestBody BaseExpertVo baseExpertVo) {
        if (StringUtils.isNull(baseExpertVo)
                || StringUtils.isNull(baseExpertVo.getPageNum())
                || StringUtils.isNull(baseExpertVo.getPageSize())) {
            return error("分页 不能为空");
        }
        return baseExpertService.selectExtractionExpert(baseExpertVo);
    }
}
