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

import com.alibaba.fastjson.JSON;
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.controller.BaseController;
import com.yeejoin.amos.boot.module.hygf.api.Enum.TaskTypeStationEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.CompanyDtoUserDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.PersonnelBusinessDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.UserDataDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.PersonnelBusiness;
import com.yeejoin.amos.boot.module.hygf.api.entity.UserMessage;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserMessageMapper;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.PersonnelBusinessServiceImpl;
import com.yeejoin.amos.boot.module.standard.api.entity.PublicAgencyUser;
import com.yeejoin.amos.boot.module.standard.api.mapper.PublicAgencyUserMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 人员业务信息表
 *
 * @author system_generator
 * @date 2023-09-01
 */
@RestController
@Api(tags = "人员业务信息表Api")
@RequestMapping(value = "/personnel-business")
public class PersonnelBusinessController extends BaseController {

    @Autowired
    PersonnelBusinessServiceImpl personnelBusinessServiceImpl;
    @Autowired
    PublicAgencyUserMapper publicAgencyUserMapper;
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    protected EmqKeeper emqKeeper;
    @Autowired
    UserMessageMapper userMessageMapper;
    /**
     * 新增人员业务信息表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增人员业务信息表", notes = "新增人员业务信息表")
	public ResponseModel<PersonnelBusinessDto> save(@RequestBody PersonnelBusinessDto model) {
	    model = personnelBusinessServiceImpl.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<PersonnelBusinessDto> updateBySequenceNbrPersonnelBusiness(@RequestBody PersonnelBusinessDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(personnelBusinessServiceImpl.updateWithModel(model));
	}

	/**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除人员业务信息表", notes = "根据sequenceNbr删除人员业务信息表")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(personnelBusinessServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/all/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除人员信息", notes = "根据sequenceNbr删除人员信息")
    public ResponseModel<Boolean> deleteAllBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(personnelBusinessServiceImpl.deleteAllBySequenceNbr(sequenceNbr));
    }

    /**
     * 根据sequenceNbrs批量删除
     *
     * @param sequenceNbrs 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/deleteDealerPerson")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbrs批量删除经销商人员信息", notes = "根据sequenceNbrs批量删除经销商人员信息")
    public ResponseModel<Boolean> deleteBySequenceNbrs(@RequestParam(value = "sequenceNbrs") String sequenceNbrs){
        return ResponseHelper.buildResponse(personnelBusinessServiceImpl.deleteBySequenceNbrs(sequenceNbrs));
    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个人员业务信息表",  notes = "根据sequenceNbr查询单个人员业务信息表")
	public ResponseModel<PersonnelBusinessDto> selectOne(@PathVariable Long sequenceNbr) {
	    return ResponseHelper.buildResponse(personnelBusinessServiceImpl.queryBySeq(sequenceNbr));
	}



	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "人员业务信息表分页查询",  notes = "人员业务信息表分页查询")
	public ResponseModel<Page<PersonnelBusinessDto>> queryForPage(@RequestParam(value = "current") int current,@RequestParam
                    (value = "size") int size) {
	    Page<PersonnelBusinessDto> page = new Page<PersonnelBusinessDto>();
	    page.setCurrent(current);
	    page.setSize(size);
	    return ResponseHelper.buildResponse(personnelBusinessServiceImpl.queryForPersonnelBusinessPage(page));
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "人员业务信息表列表全部数据查询",   notes = "人员业务信息表列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<PersonnelBusinessDto>> selectForList() {
	    return ResponseHelper.buildResponse(personnelBusinessServiceImpl.queryForPersonnelBusinessList());
	}



    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getPersonnelBusinessPage")
    @ApiOperation(httpMethod = "GET",value = "分页查询",  notes = "分页查询")
    public ResponseModel<IPage<CompanyDtoUserDto>> getPersonnelBusinessPage(CompanyDtoUserDto dto) {

        return ResponseHelper.buildResponse(personnelBusinessServiceImpl.getCompanyDtoUserDto(dto));
    }



    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/savePersonnelBusiness")
    @ApiOperation(httpMethod = "POST", value = "新增人员业务信息表", notes = "新增人员业务信息表")
    public ResponseModel<PersonnelBusinessDto> savePersonnelBusiness(@RequestBody UserDataDto model) {
        String  userid= getUserInfo().getUserId();
        LambdaQueryWrapper<PublicAgencyUser> qud=new LambdaQueryWrapper<>();
        qud.eq(PublicAgencyUser::getAmosUserId,userid);
        PublicAgencyUser publicAgencyUse=  publicAgencyUserMapper.selectOne(qud);
        LambdaQueryWrapper<PersonnelBusiness> qug=new LambdaQueryWrapper<>();
        qug.eq(PersonnelBusiness::getFoundationId,publicAgencyUse.getSequenceNbr());
        PersonnelBusiness personnelBusines=personnelBusinessMapper.selectOne(qug);
        //获取所属经销商
        model.setAmosDealerId(personnelBusines.getAmosDealerId());
       personnelBusinessServiceImpl.savePersonnelBusiness(model);
        return ResponseHelper.buildResponse(null);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/updatePersonnelBusiness")
    @ApiOperation(httpMethod = "POST", value = "新增人员业务信息表", notes = "新增人员业务信息表")
    public ResponseModel<PersonnelBusinessDto> updatePersonnelBusiness(@RequestBody UserDataDto model ,long id) {

        personnelBusinessServiceImpl.updatePersonnelBusiness(model, id);
        return ResponseHelper.buildResponse(null);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getPersonnelBusinessById")
    @ApiOperation(httpMethod = "GET",value = "详情",  notes = "详情")
    public ResponseModel<UserDataDto> getPersonnelBusinessById(String ids) {
        return ResponseHelper.buildResponse(personnelBusinessServiceImpl.getPersonnelBusinessById(ids));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/setlook")
    @ApiOperation(httpMethod = "GET",value = "详情",  notes = "详情")
    public ResponseModel<UserDataDto> setlook(String id) {
        FeignClientResult<List<String>> data=null;
        PublicAgencyUser publicAgencyUser= publicAgencyUserMapper.selectById(id);
        if("UNLOCK".equals(publicAgencyUser.getLockStatus())){
            publicAgencyUser.setLockStatus("LOCK");
            data= Privilege.agencyUserClient.lockUsers(publicAgencyUser.getAmosUserId());
        }else{
            publicAgencyUser.setLockStatus("UNLOCK");
             data= Privilege.agencyUserClient.unlockUsers(publicAgencyUser.getAmosUserId());
        }
        if(data==null||data.getResult()==null){
            throw new BadRequest("修改状态失败！");
        }

        publicAgencyUser.setLockTime(new Date());

        publicAgencyUserMapper.updateById(publicAgencyUser);

        return ResponseHelper.buildResponse(null);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/czPassword")
    @ApiOperation(httpMethod = "GET",value = "重置密码",  notes = "重置密码")
    public ResponseModel<UserDataDto> czPassword(String id) {
	    try {


        PublicAgencyUser publicAgencyUser= publicAgencyUserMapper.selectById(id);
        FeignClientResult data=Privilege.agencyUserClient.restorePassword(publicAgencyUser.getAmosUserId());
        LambdaQueryWrapper<PersonnelBusiness> qug=new LambdaQueryWrapper<>();
        qug.eq(PersonnelBusiness::getFoundationId,publicAgencyUser.getSequenceNbr());
        PersonnelBusiness personnelBusines=personnelBusinessMapper.selectOne(qug);
        UserMessage userMessage=  new UserMessage( TaskTypeStationEnum.重置密码.getCode(), publicAgencyUser.getSequenceNbr() ,  publicAgencyUser.getAmosUserId(),  new Date(),   "您的密码已重置成功,密码为：Z2%Op9.q 请尽快修改密码。",  personnelBusines.getAmosUnitOrgCode());


        if(data==null||data.getResult()==null){
            throw new BadRequest("修改状态失败！");
        }else{
            userMessageMapper.insert(userMessage);
            emqKeeper.getMqttClient().publish("MY_MESSAGE" , JSON.toJSONString(userMessage).getBytes(), 2 ,false);
        }
        }catch (Exception e){
            e.printStackTrace();
            throw new BadRequest("修改状态失败！");

        }
        return ResponseHelper.buildResponse(null);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/replace")
    @ApiOperation(httpMethod = "GET",value = "更换管理员",  notes = "更换管理员")
    public ResponseModel<UserDataDto> replace(String id) {
       try {
           personnelBusinessServiceImpl.replace(id);
           return ResponseHelper.buildResponse(null);
       }catch (Exception e){
           e.printStackTrace();
           throw new BadRequest("设置失败！");
       }

    }

    }
