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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.dto.UserDto;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormInstanceServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.dto.InstallNoticeDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProjectDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.WelderDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.WelderEquipmentDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProjectResource;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectResourceMapper;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.OrgServiceImpl;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.ProjectResourceServiceImpl;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.ProjectServiceImpl;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.WelderServiceImpl;
import com.yeejoin.amos.feign.privilege.Privilege;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
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 javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(tags = "焊工信息")
@RequestMapping(value = "/welder")
public class WelderController extends BaseController {
    @Autowired
    OrgServiceImpl orgService;
    @Autowired
    ProjectMapper projectMapper;

    @Autowired
    ProjectServiceImpl projectService;

    @Autowired
    WelderServiceImpl welderServiceImpl;

    @Autowired
    OrgServiceImpl orgServiceImpl;

    @Autowired
    ProjectResourceMapper projectResourceMapper;

    @Autowired
    ProjectResourceServiceImpl  projectResourceServiceImpl;
    @Autowired
    DynamicFormInstanceServiceImpl alertFormValueServiceImpl;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 新增/修改焊工信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/saveWelder", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增人员信息", notes = "新增人员信息")
    public ResponseModel<OrgUsrDto> saveWelder(@RequestBody JSONObject jsonObject, @RequestParam String bizOrgType ,
                                            @RequestParam(required = false) String sequenceNbr) {
        //当有seq时判断是否已绑定项目
        if (!ValidationUtil.isEmpty(sequenceNbr)){
            String sequenceNbrDept = orgService.getOrgUsrById(jsonObject.getString("sequenceNbr")).getParentId();
            //修改部门时判断用户是否是部门负责人
            if (!sequenceNbrDept.equals(jsonObject.getString("deptId"))) {
                LambdaQueryWrapper<DynamicFormInstance> wrapperDept = new LambdaQueryWrapper<>();
                wrapperDept.eq(DynamicFormInstance::getInstanceId, sequenceNbrDept);
                List<DynamicFormInstance> list = alertFormValueServiceImpl.list(wrapperDept);
                for (DynamicFormInstance i : list) {
                    //不为空时进入
                    if (!ValidationUtil.isEmpty(i.getFieldValue())){
                    if (i.getFieldValue().equals(jsonObject.getString("sequenceNbr"))) {
                        return CommonResponseUtil.failure("该人员为该部门负责人，请解除");
                    }
                }}
            }
        }
        try {
            OrgUsrDto orgUsrDto = welderServiceImpl.savePerson(jsonObject, bizOrgType, sequenceNbr);
            return ResponseHelper.buildResponse(orgUsrDto);
        }catch (Exception e){
            return CommonResponseUtil.failure("该用户绑定的手机号已存在，请更换号码");
        }



    }
    /**
     * 获取焊工信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/selectWelder")
    @ApiOperation(httpMethod = "GET", value = "获取焊工信息", notes = "获取焊工信息")
    public ResponseModel<List<JSONObject>> selectWelder() {
        List<JSONObject> jsonObjectList=new ArrayList<>();
//        LambdaQueryWrapper<Project> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(Project::getCode,code);
//        Project project = projectMapper.selectOne(wrapper);
        //根据登录人获取登录人单位下焊工
        List<Map> info = orgService.getCompanyWelder(new Page()).getRecords();
        for (Map<String,Object> map:info){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("name",map.get("name"));
            jsonObject.put("sequenceNbr",map.get("sequenceNbr"));
            jsonObjectList.add(jsonObject);
        }

        return ResponseHelper.buildResponse(jsonObjectList);
    }
    /**
     * 项目焊工人员分页查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "项目焊工人员分页查询列表", notes = "项目焊工人员分页查询列表")
    @GetMapping(value = "/getpageInfo")
    public ResponseModel<IPage<Map>> getpageInfo(){
        return ResponseHelper.buildResponse(welderServiceImpl.getpageInfo());
    }

    /**
     * 项目焊工人员删除
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @DeleteMapping(value = "/delWelder/{sequenceNbr}")
    @ApiOperation(httpMethod = "Delete", value = "项目焊工人员删除", notes = "项目焊工人员删除")
    public ResponseModel<Boolean> deleteByResourceId(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(projectResourceMapper.deleteByResourceId(sequenceNbr));
    }

    /**
     * 当前登陆人所在公司/单位/企业 下的 所有焊工人员分页查询
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "当前登陆人所在公司/单位/企业下的所有焊工人员分页列表", notes = "当前登陆人所在公司/单位/企业下的所有焊工人员分页查询列表")
    @GetMapping(value = "/getCompanyWelder")
    public ResponseModel<IPage> getCompanyWelder(
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String idNumber,
            @RequestParam(required = false) String licensedProject
    ){
        Page page = new Page();
        page.setCurrent(current);
        page.setSize(size);
        IPage companyWelder = orgServiceImpl.getCompanyWelder(page);

        List<Map> welderRecords = companyWelder.getRecords();
        try{
            //模糊查询
            if (name!=null||idNumber!=null||licensedProject!=null){
                if (name!=null) {welderRecords = welderRecords.stream().filter(n -> ((String)n.get("name")).indexOf(name)>-1).collect(Collectors.toList());}
                if (idNumber!=null) {welderRecords = welderRecords.stream().filter(n -> ((String)n.get("idNumber")).indexOf(idNumber)>-1).collect(Collectors.toList());}
                if (licensedProject!=null) {welderRecords = welderRecords.stream().filter(n -> ((String)n.get("licensedProject")).indexOf(licensedProject)>-1).collect(Collectors.toList());}
            }
        }catch (Exception e){
            e.getStackTrace();
            System.out.println("数据库数据出错");
        }


        Page records = page.setRecords(welderRecords);
        return ResponseHelper.buildResponse(records);
    }

    /**
     * 根据sequenceNbr查询人员信息
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询人员信息", notes = "根据sequenceNbr查询人员信息")
    public ResponseModel<Map> selectOneById(@PathVariable String sequenceNbr) {
        return ResponseHelper.buildResponse(orgServiceImpl.getdetialInfo(sequenceNbr));
    }

    /**
     * 根据sequenceNbr删除人员信息表
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @DeleteMapping(value = "/deleteOneById/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr删除人员信息表", notes = "根据sequenceNbr删除人员信息表")
    public ResponseModel<String> deleteOneById(@PathVariable List<Long> sequenceNbr) throws Exception {
//        Privilege.agencyUserClient.multDeleteUser(orgServiceImpl.getOrgUsrById(sequenceNbr).getAmosOrgId());
        LambdaQueryWrapper<ProjectResource> wrapper = new LambdaQueryWrapper<>();
        for (Long i : sequenceNbr) {
            wrapper.eq(ProjectResource::getResourceId, i);
            if (!projectResourceMapper.selectList(wrapper).isEmpty()) {

                return CommonResponseUtil.failure("无法删除,管材：" + orgServiceImpl.getdetialInfo(String.valueOf(i)).get("name") + "已绑定项目");
            }
            orgServiceImpl.delectInfo(String.valueOf(i));

        }
        return ResponseHelper.buildResponse("ok");
    }

    /**
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "", notes = "")
    @GetMapping(value = "/getUserInfo")
    @BusinessIdentify
    public ResponseModel<IPage> getUserInfo(int current, int size){
        IPage page = new Page();
        page.setCurrent(current);
        page.setSize(size);
        page = orgServiceImpl.getPersonInfo(String.valueOf(orgServiceImpl.getReginParams().getBusinessInfo().getCompanySequenceNbr()),page);
        List<Map> mapList = page.getRecords();
        for(Map map : mapList){
            try {
                map.put("dept", orgServiceImpl.getOrgUsrById(String.valueOf(map.get("deptId"))).getBizOrgName());
            } catch (Exception e) {
//                map.put("dept",String.valueOf(map.get("deptId")));
                map.put("dept", "");
            }
            if(OrgEnum.焊工.getKey().equals((String)map.get("type"))){
                map.put("typeName",OrgEnum.焊工.getName());
            }else{
                map.put("typeName",OrgEnum.管理员.getName());
            }
        }
        return ResponseHelper.buildResponse(page);
    }

    /**
     * 焊工持证项目统计
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "焊工持证项目统计", notes = "焊工持证项目统计")
    @GetMapping(value = "/welderStatistics")
    public ResponseModel<List<Map>> welderStatistics() {
        return ResponseHelper.buildResponse(welderServiceImpl.welderStatistics());
    }

    /**
     * 项目绑定焊工人员信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询项目已绑定焊工信息", notes = "查询项目已绑定焊工信息")
    @GetMapping(value = "/getWelderByProjectId")
    public ResponseModel<Object> getWelderByProjectId(@RequestParam(value = "projectId") String projectId,
                                                      @RequestParam(value = "current", required = false) Integer current,
                                                      @RequestParam(value = "size", required = false) Integer size,
                                                      @RequestParam(value = "name", required = false) String name) {
        return ResponseHelper.buildResponse(welderServiceImpl.getWelderByProjectId(projectId, current, size, name, null));
    }

    /**
     * 项目绑定焊工人员信息、以及空闲人员
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "项目绑定焊工人员信息、以及空闲人员", notes = "项目绑定焊工人员信息、以及空闲人员")
    @GetMapping(value = "/getAllListByProjectId")
    public ResponseModel<Object> getAllListByProjectId(@RequestParam(value = "projectId") String projectId,
                                                       @RequestParam(value = "current") int current,
                                                       @RequestParam(value = "size") int size,
                                                       @RequestParam(value = "name", required = false) String name) {
        return ResponseHelper.buildResponse(welderServiceImpl.getWelderByProjectId(projectId, current, size, name, "all"));
    }
}
