package com.yeejoin.amos.boot.module.elevator.flc.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.annotation.ResubmitCheck;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.elevator.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.boot.module.elevator.flc.api.dto.EquipmentDto;
import com.yeejoin.amos.boot.module.elevator.flc.api.dto.EquipmentIndexDto;
import com.yeejoin.amos.boot.module.elevator.flc.api.dto.UnitInfoDto;
import com.yeejoin.amos.boot.module.elevator.flc.api.entity.Equipment;
import com.yeejoin.amos.boot.module.elevator.flc.api.entity.EquipmentIndex;
import com.yeejoin.amos.boot.module.elevator.flc.api.entity.UnitInfo;
import com.yeejoin.amos.boot.module.elevator.flc.biz.service.impl.EquipmentIndexServiceImpl;
import com.yeejoin.amos.boot.module.elevator.flc.biz.service.impl.EquipmentServiceImpl;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
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.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 装备信息表
 *
 * @author system_generator
 * @date 2021-11-25
 */
@RestController
@Api(tags = "装备信息表Api")
@RequestMapping(value = "/equipment")
public class EquipmentController extends BaseController {

    @Autowired
    EquipmentServiceImpl equipmentServiceImpl;


    @Autowired
    EquipmentIndexServiceImpl equipmentIndexServiceImpl;



    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    /**
     * 新增装备信息表
     *
     * @return
     */
    @ResubmitCheck
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增装备信息表", notes = "新增装备信息表")
    public ResponseModel save(@RequestBody EquipmentDto model) {
        try {
            model = equipmentServiceImpl.createEquipment(model);
            return CommonResponseUtil.success(model);
        } catch (Exception e) {
            return CommonResponseUtil.failure("该手机号已经注册");
        }

    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个装备信息", notes = "根据sequenceNbr查询单个装备信息")
    public ResponseModel<EquipmentDto> selectOne(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(equipmentServiceImpl.getEquipmentById(sequenceNbr));
    }



    /**
     * 根据sequenceNbr更新
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/updateEquipment")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新装备信息表", notes = "根据sequenceNbr更新装备信息表")
    public ResponseModel<EquipmentDto> updateEquip20ment(@RequestBody EquipmentDto model) {
        if (ValidationUtil.isEmpty(model)
                || ValidationUtil.isEmpty(model.getSequenceNbr())) {
            throw new BadRequest("参数校验失败.");
        }
        model = equipmentServiceImpl.updateEquipment(model);
        return ResponseHelper.buildResponse(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) {
        return ResponseHelper.buildResponse(equipmentServiceImpl.deleteById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr删除
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/delete_batch")
    @ApiOperation(httpMethod = "DELETE", value = "批量删除装备信息", notes = "批量删除装备信息")
    public ResponseModel<Boolean> deleteBySequenceNbr(@RequestParam(value = "sequenceNbrList") List<Long> sequenceNbrList){
        return ResponseHelper.buildResponse(equipmentServiceImpl.batchDelete(sequenceNbrList));
    }


    /**
     * 列表分页查询
     *
     * @param pageNum  当前页
     * @param pageSize 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/list")
    @ApiOperation(httpMethod = "GET", value = "装备列表查询", notes = "装备列表查询")
    public ResponseModel<IPage<EquipmentDto>> queryForPage(String pageNum, String pageSize, String sort, EquipmentDto equipmentDto) {
        Page<Equipment> pageBean;
        IPage<Equipment> page;
        QueryWrapper<Equipment> equipmentQueryWrapper = new QueryWrapper<Equipment>();
        setQueryWrapper(equipmentQueryWrapper, equipmentDto, sort);
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = equipmentServiceImpl.page(pageBean, equipmentQueryWrapper);
        int num= equipmentServiceImpl.count(equipmentQueryWrapper);
        pageBean.setTotal(num);
        IPage<EquipmentDto> equipmentDtoIPager = BeanDtoVoUtils.equipmentIPageDto(page);
        equipmentDtoIPager.getRecords().stream().forEach( dto -> {

            // 封装详细参数
            List<EquipmentIndex> indexList = equipmentIndexServiceImpl.list(new LambdaQueryWrapper<EquipmentIndex>().eq(EquipmentIndex::getEquipmentId,dto.getSequenceNbr()));
            List<EquipmentIndexDto> dtoList = new ArrayList<>();
            indexList.stream().forEach(t -> {
                EquipmentIndexDto temp = new EquipmentIndexDto();
                BeanUtils.copyProperties(t,temp);
                dtoList.add(temp);
            });
            dto.setEquipmentIndex(dtoList);

        });
        return ResponseHelper.buildResponse(equipmentDtoIPager);
    }


    private QueryWrapper<Equipment> setQueryWrapper(QueryWrapper<Equipment> queryWrapper, EquipmentDto equipmentDto, String sort) {
        queryWrapper.eq("is_delete", false);

        // 获取用户所在单位 保存设备所属单位
        OrgUsr myUnit = null;
        AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
        List<CompanyModel> companys = user.getCompanys();
        for(CompanyModel c : companys) {
            myUnit = iOrgUsrService.getOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete,false).eq(OrgUsr::getAmosOrgId,c.getSequenceNbr()));
        }
        if(myUnit == null) {
            throw  new BadRequest("该用户非企业人员无法查询企业设备");
        }
        queryWrapper.eq("equip_unit_id", myUnit.getSequenceNbr());

        if(sort!=null) {  // 排序失效
            String[] date=  sort.split(",");
            if(date[1].equals("ascend")) {
                queryWrapper.orderByAsc(RedisKey.humpToLine(date[0]));
            }else {
                queryWrapper.orderByDesc(RedisKey.humpToLine(date[0]));
            }
        }else {
            queryWrapper.orderByDesc("rec_date");
        }

        if(!ValidationUtil.isEmpty(equipmentDto.getCode())) {  // 设备代码
            queryWrapper.like("code",equipmentDto.getCode());
        }

        if (!ValidationUtil.isEmpty(equipmentDto.getProductCode())) { // 产品编号
            queryWrapper.like("product_code",equipmentDto.getProductCode());
        }
        if (!ValidationUtil.isEmpty(equipmentDto.getInnerCode())) { // 单位内部编码
            queryWrapper.like("inner_code",equipmentDto.getInnerCode());
        }
        if (!ValidationUtil.isEmpty(equipmentDto.getName())) { // 设备名称
            queryWrapper.like("name",equipmentDto.getName());
        }
        if(!ValidationUtil.isEmpty(equipmentDto.getCategoryId())) { // 设备类别
            queryWrapper.eq("category_id",equipmentDto.getCategoryId());
        }
        if(!ValidationUtil.isEmpty(equipmentDto.getTypeId())) { // 设备种类
            queryWrapper.eq("type_id",equipmentDto.getTypeId());
        }
        if(!ValidationUtil.isEmpty(equipmentDto.getVarietyId())) { // 设备品种
            queryWrapper.eq("variety_id",equipmentDto.getVarietyId());
        }
        if (!ValidationUtil.isEmpty(equipmentDto.getDesignUnitName())) { // 设计单位
            queryWrapper.like("design_unit_name",equipmentDto.getDesignUnitName());
        }
        if (!ValidationUtil.isEmpty(equipmentDto.getManufacturer())) { // 制造单位
            queryWrapper.like("manufacturer",equipmentDto.getManufacturer());
        }
        if(!ValidationUtil.isEmpty(equipmentDto.getStatus())) { // 状态
            queryWrapper.eq("status",equipmentDto.getStatus());
        }

        return queryWrapper;
    }


    /**
     * 获取设备ID
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getEquipmentId")
    @ApiOperation(httpMethod = "GET", value = "获取设备ID", notes = "获取设备ID")
    public ResponseModel<String> getEquipmentId() {
        return ResponseHelper.buildResponse(UUID.randomUUID().toString().replace("-",""));
    }

    /**
     * 获取设备种类接口
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getEquipmentType")
    @ApiOperation(httpMethod = "GET", value = "获取设备种类接口", notes = "获取设备种类接口")
    public ResponseModel<List<Object>> getEquipmentType() {

        return ResponseHelper.buildResponse(equipmentServiceImpl.getEquipmentType());
    }


    /**
     * 获取设备类别接口
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getEquipmentClass/{typeCode}")
    @ApiOperation(httpMethod = "GET", value = "获取设备类别接口", notes = "获取设备类别接口")
    public ResponseModel<List<Object>> getEquipmentClass(@PathVariable(value = "typeCode") String typeCode) {

        return ResponseHelper.buildResponse(equipmentServiceImpl.getEquipmentClass(typeCode));
    }


}
